# Conflicts:
#	crates/horizon-client/src/game/remote.rs
This commit is contained in:
Ludovic Marie
2026-10-27 06:40:59 +01:00
176 changed files with 13597 additions and 832 deletions
+2 -1
View File
@@ -10,7 +10,8 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
`tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit.
- **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d`
folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and
`XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to
`XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the
launcher, `HORIZON_LAUNCHER_TRASH` and `HORIZON_LAUNCHER_CLIPBOARD` pointing into the scratch home. Never write to
`~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`.
- **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what.
Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a
+1 -1
View File
@@ -200,7 +200,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
return Err(format!("it didn't start: {reason}"));
}
let client: Vec<String> = mods.commands().map(str::to_owned).collect();
let server: Vec<String> = mods.server_commands().map(str::to_owned).collect();
let server: Vec<String> = mods.server_commands().map(|c| c.name.clone()).collect();
report.commands = [client.clone(), server.clone()].concat();
// A server mod plays with one player on, who joins, chats and leaves.
let steve = ServerPlayer {
@@ -163,6 +163,8 @@ pub fn main() -> Result<()> {
ArrowSound::HitGround => "hit",
ArrowSound::Splash => "splash",
ArrowSound::Extinguish => "extinguish",
ArrowSound::TridentHitGround => "trident_hit_ground",
ArrowSound::TridentHit => "trident_hit",
},
volume.to_bits(),
pitch.to_bits()
@@ -592,6 +592,7 @@ pub fn main() -> horizon_client::Result<()> {
pose,
num("maxCrossbowChageDuration"),
num("ticksUsingItem"),
false,
);
}
Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator => {
+137 -11
View File
@@ -35,8 +35,9 @@ enum Animate {
Campfire {
spawn_particles: bool,
},
/// Leaves: optional falling-leaf particle and chance, tinted by foliage.
Leaves(Option<(T, f32)>),
/// Leaves: optional falling-leaf particle and chance; a tinted leaf takes
/// the biome foliage colour unless a fixed colour is given (azalea).
Leaves(Option<(T, f32)>, Option<u32>),
NetherPortal,
EnchantingTable,
EndRod([i32; 3]),
@@ -49,6 +50,8 @@ enum Animate {
EnderChest,
/// FallingBlock with its dust colour.
Falling(u32),
/// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`).
Beehive,
RedstoneOre,
RedstoneWire {
power: u8,
@@ -104,10 +107,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
spawn_particles: false,
},
"oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves"
| "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01))),
"cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1))),
"pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02))),
"spruce_leaves" | "azalea_leaves" | "flowering_azalea_leaves" => Animate::Leaves(None),
| "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None),
"cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None),
"pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None),
"red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None),
"orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None),
"yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None),
// The azalea blocks drop tinted leaves of the fixed colour -9399763.
"azalea_leaves" | "flowering_azalea_leaves" => {
Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D))
}
"spruce_leaves" => Animate::Leaves(None, None),
"nether_portal" => Animate::NetherPortal,
"enchanting_table" => Animate::EnchantingTable,
"end_rod" => Animate::EndRod(facing()),
@@ -119,6 +129,14 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
"sand" => Animate::Falling(0xDBD3A0),
"red_sand" => Animate::Falling(0xA95821),
"gravel" => Animate::Falling(0x807C7B),
// AnvilBlock/ConcretePowderBlock.getDustColor is the map colour;
// DragonEggBlock's is black.
"anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7),
"dragon_egg" => Animate::Falling(0x000000),
_ if name.ends_with("_concrete_powder") => Animate::Falling(concrete_powder_color(
name.trim_end_matches("_concrete_powder"),
)),
"beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive,
"redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre,
"redstone_wire" => {
let power = prop("power").and_then(|p| p.parse().ok()).unwrap_or(0);
@@ -161,6 +179,27 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
_ => Animate::None,
}
}
/// `DyeColor.getMapColor` of a concrete powder colour.
fn concrete_powder_color(dye: &str) -> u32 {
match dye {
"white" => 0xFFFFFF,
"orange" => 0xD87F33,
"magenta" => 0xB24CD8,
"light_blue" => 0x6699D8,
"yellow" => 0xE5E533,
"lime" => 0x7FCC19,
"pink" => 0xF27FA5,
"gray" => 0x4C4C4C,
"light_gray" => 0x999999,
"cyan" => 0x4C7F99,
"purple" => 0x7F3FB2,
"blue" => 0x334CB2,
"brown" => 0x664C33,
"green" => 0x667F33,
"red" => 0x993333,
_ => 0x191919,
}
}
/// `RedstoneWireBlock.COLORS`.
fn redstone_color(power: u8) -> [f32; 3] {
let f = f32::from(power) / 15.0;
@@ -504,6 +543,53 @@ fn try_spawn_drip(
}
}
}
/// `BeehiveBlock.trySpawnDripParticles`.
fn beehive_drip(
tables: &AnimateTables,
engine: &mut ParticleEngine,
ctx: &AnimateContext,
state: BlockStateId,
pos: [i32; 3],
) {
if ctx.facts.get(state).fluid != Fluid::None || engine.random().next_float() < 0.3 {
return;
}
let Some((bottom, top, bounds)) = ctx.shape_y(pos) else {
return;
};
if top < 1.0
|| tables
.impermeable
.get(state.0 as usize)
.copied()
.unwrap_or(false)
{
return;
}
let y = if bottom > 0.0 {
f64::from(pos[1]) + bottom - 0.05
} else {
let below = [pos[0], pos[1] - 1, pos[2]];
let below_top = ctx.shape_y(below).map_or(1.0, |s| s.1);
// `belowTop < 1 || !isCollisionShapeFullBlock` and no fluid below.
if (below_top < 1.0 || !ctx.sturdy(below))
&& ctx.facts.get(ctx.state(below)).fluid == Fluid::None
{
f64::from(pos[1]) - 0.05
} else {
return;
}
};
let r = engine.random();
let (a, b) = (r.next_double(), r.next_double());
let (fx, fz) = (f64::from(pos[0]), f64::from(pos[2]));
let p = [
fx + bounds[0] + (bounds[1] - bounds[0]) * a,
y,
fz + bounds[2] + (bounds[3] - bounds[2]) * b,
];
add(engine, T::DrippingHoney, p, [0.0; 3]);
}
/// `WaterFluid.animateTick` / `LavaFluid.animateTick`.
fn fluid_animate_tick(
engine: &mut ParticleEngine,
@@ -685,7 +771,7 @@ fn block_animate_tick(
}
}
}
Animate::Leaves(falling) => {
Animate::Leaves(falling, fixed_tint) => {
let below = [pos[0], pos[1] - 1, pos[2]];
// LeavesBlock.makeDrippingWaterParticles.
if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1
@@ -705,7 +791,7 @@ fn block_animate_tick(
let r = engine.random();
let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()];
let options = if ty == T::TintedLeaves {
let c = ctx.foliage(pos);
let c = fixed_tint.unwrap_or_else(|| ctx.foliage(pos));
let f = |s: u32| ((c >> s) & 255) as f32 / 255.0;
ParticleOptions::colored(ty, [f(16), f(8), f(0), 1.0])
} else {
@@ -977,6 +1063,13 @@ fn block_animate_tick(
}
}
}
Animate::Beehive => {
// BeehiveBlock.animateTick: nextInt(1) + 1 attempts.
let attempts = next_int(engine.random(), 1) + 1;
for _ in 0..attempts {
beehive_drip(tables, engine, ctx, state, pos);
}
}
Animate::RedstoneOre => {
for d in [
[0, -1, 0],
@@ -1209,21 +1302,32 @@ fn candle(engine: &mut ParticleEngine, p: [f64; 3]) {
}
add(engine, T::SmallFlame, p, [0.0; 3]);
}
/// `CampfireBlockEntity.particleTick` for every lit campfire (no cooking items).
/// `CampfireBlockEntity.particleTick` for every lit campfire; `cooking` says
/// which of a campfire's four slots hold an item.
pub fn campfire_particles<'a>(
tables: &AnimateTables,
engine: &mut ParticleEngine,
ctx: &AnimateContext,
blocks: impl Iterator<Item = &'a ([i32; 3], u32)>,
cooking: &dyn Fn([i32; 3]) -> [bool; 4],
) {
for &(pos, state) in blocks {
if !tables.is_lit_campfire(state) {
continue;
}
let signal = ctx
let properties = ctx
.registry
.state(BlockStateId(state))
.is_some_and(|s| s.properties.get("signal_fire").map(String::as_str) == Some("true"));
.map(|s| &s.properties);
let prop = |k: &str| properties.and_then(|p| p.get(k)).map(String::as_str);
let signal = prop("signal_fire") == Some("true");
// Direction.get2DDataValue: south, west, north, east.
let rotation = match prop("facing") {
Some("west") => 1,
Some("north") => 2,
Some("east") => 3,
_ => 0,
};
let r = engine.random();
if r.next_float() < 0.11 {
let count = next_int(r, 2) + 2;
@@ -1231,6 +1335,28 @@ pub fn campfire_particles<'a>(
make_campfire_smoke(engine, pos, signal, false);
}
}
// The smoke over each cooking item, at the slot's corner of the fire.
let occupied = cooking(pos);
for (slot, _) in occupied.iter().enumerate().filter(|(_, held)| **held) {
if engine.random().next_float() >= 0.2 {
continue;
}
// Direction.from2DDataValue((slot + rotation) % 4) and its clockwise side.
let (step, clockwise) = match (slot + rotation) % 4 {
0 => ([0.0, 1.0], [-1.0, 0.0]),
1 => ([-1.0, 0.0], [0.0, -1.0]),
2 => ([0.0, -1.0], [1.0, 0.0]),
_ => ([1.0, 0.0], [0.0, 1.0]),
};
let at = [
f64::from(pos[0]) + 0.5 - step[0] * 0.3125 + clockwise[0] * 0.3125,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5 - step[1] * 0.3125 + clockwise[1] * 0.3125,
];
for _ in 0..4 {
add(engine, T::Smoke, at, [0.0, 5.0e-4, 0.0]);
}
}
}
}
/// `CampfireBlock.makeParticles` (always visible, overriding the limiter);
+47 -4
View File
@@ -9,7 +9,7 @@ use crate::{
collisions::SceneCollisions,
mobs::Who,
motion::{FluidResources, LAVA, WATER},
projectiles::{Hit, Projectile},
projectiles::{Hit, Projectile, ProjectileKind},
world::World,
};
use horizon_core::{
@@ -132,6 +132,10 @@ pub enum ArrowSound {
HitGround,
/// `entity.generic.extinguish_fire`.
Extinguish,
/// A thrown trident's `getDefaultHitGroundSoundEvent` (`item.trident.hit_ground`).
TridentHitGround,
/// `ThrownTrident.onHitEntity`'s `item.trident.hit`.
TridentHit,
}
/// What a burning arrow does to the block it hits (`onProjectileHit`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -169,6 +173,9 @@ pub struct ArrowState {
pub was_eye_in_water: bool,
pub first_tick: bool,
pub has_been_shot: bool,
/// `ThrownTrident.dealtDamage`: it has hit an entity (or sat in a block
/// for over 4 ticks) and hits no more.
pub dealt_damage: bool,
pub removed: bool,
/// The arrow's own random (`Entity.random`).
pub random: LegacyRandom,
@@ -211,6 +218,7 @@ impl ArrowState {
was_eye_in_water: false,
first_tick: true,
has_been_shot: false,
dealt_damage: false,
removed: false,
random,
events: Vec::new(),
@@ -451,12 +459,14 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity
let Some(mut st) = p.arrow.take() else {
return false;
};
let trident = matches!(p.kind, ProjectileKind::Trident);
let mut ticker = Ticker {
p,
st: &mut st,
scene,
};
match outcome {
EntityHit::Hurt | EntityHit::Refused if trident => ticker.trident_bounce(),
EntityHit::Hurt => {
ticker.hit_sound();
// A piercing arrow flies on (`getPierceLevel() <= 0` discards).
@@ -501,7 +511,16 @@ impl Ticker<'_, '_, '_, '_> {
p.z,
))
}
/// Whether this is a `ThrownTrident` (`AbstractArrow` with its own water
/// inertia, sounds and hit).
fn trident(&self) -> bool {
matches!(self.p.kind, ProjectileKind::Trident)
}
fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit {
// ThrownTrident.tick.
if self.trident() && self.st.in_ground_time > 4 {
self.st.dealt_damage = true;
}
let physics = !self.st.no_physics;
let movement = self.p.velocity;
let block_pos = self.block_position();
@@ -549,8 +568,9 @@ impl Ticker<'_, '_, '_, '_> {
self.st.in_ground_time = 0;
let original = self.position();
if self.st.was_touching_water {
// getWaterInertia, then the bubbles behind it.
self.p.velocity = self.p.velocity.scale(f64::from(0.6f32));
// getWaterInertia (0.99 for a trident), then the bubbles behind it.
let inertia = if self.trident() { 0.99f32 } else { 0.6f32 };
self.p.velocity = self.p.velocity.scale(f64::from(inertia));
let v = self.p.velocity;
for _ in 0..4 {
self.st.events.push(ArrowEvent::Particle {
@@ -687,6 +707,8 @@ impl Ticker<'_, '_, '_, '_> {
.expand_towards(self.p.velocity)
.inflate(Vec3::new(1.0, 1.0, 1.0));
let mut best: Option<(Who, Vec3, f64)> = None;
// ThrownTrident.findHitEntity: none once it has dealt damage.
let targets = if self.st.dealt_damage { &[] } else { targets };
for (who, b) in targets {
if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) {
continue;
@@ -757,12 +779,33 @@ impl Ticker<'_, '_, '_, '_> {
/// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`.
fn hit_sound(&mut self) {
let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9);
let sound = if self.trident() {
ArrowSound::TridentHitGround
} else {
ArrowSound::HitGround
};
self.st.events.push(ArrowEvent::Sound {
sound: ArrowSound::HitGround,
sound,
volume: 1.0,
pitch,
});
}
/// `ThrownTrident.onHitEntity` after the hurt, whether it landed or not:
/// the hit sound, then `deflect(REVERSE, ..., (0.02, 0.2, 0.02))`. The
/// trident keeps flying (it has dealt its damage) and falls.
fn trident_bounce(&mut self) {
self.st.dealt_damage = true;
self.st.events.push(ArrowEvent::Sound {
sound: ArrowSound::TridentHit,
volume: 1.0,
pitch: 1.0,
});
// ProjectileDeflection.REVERSE.
let rotation = 170.0 + self.st.random.next_float() * 20.0;
let v = self.p.velocity;
self.p.velocity = Vec3::new(v.x * (-0.02 * 0.5), v.y * (-0.2 * 0.5), v.z * (-0.02 * 0.5));
self.p.yaw += rotation;
}
/// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`,
/// a half turn give or take ten degrees at a tenth of the speed; one
/// left almost still drops its pickup (ALLOWED) and is discarded.
+1 -1
View File
@@ -90,7 +90,7 @@ pub const MAP_COLORS: [u32; 62] = [
14200723, 8365974,
];
/// The 12 edges of the unit cube (outline data predating the export).
fn cube_edges() -> Vec<[f64; 6]> {
pub fn cube_edges() -> Vec<[f64; 6]> {
let mut edges = Vec::new();
for a in 0..3 {
for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] {
+48 -8
View File
@@ -1,6 +1,7 @@
//! `BundleContents.Mutable`: what a bundle takes in and gives back, by
//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click
//! overrides on it.
use crate::item_data::BundleSelected;
use crate::items::{ItemStack, Items};
use horizon_world::nbt::Tag;
@@ -97,6 +98,8 @@ pub fn can_be_in_bundle(stack: &ItemStack) -> bool {
pub struct Contents {
items: Vec<ItemStack>,
weight: Weight,
/// `selectedItem`: an index into `items`, -1 for none.
selected: i32,
}
impl Contents {
@@ -104,9 +107,11 @@ impl Contents {
pub fn of(items: &Items, stack: &ItemStack) -> Option<Self> {
let inside = contents_of(items, stack)?.to_vec();
let weight = contents_weight(items, &inside);
let selected = stack.data().map_or(-1, |d| d.bundle_selected.0);
Some(Self {
items: inside,
weight,
selected,
})
}
@@ -154,18 +159,26 @@ impl Contents {
amount
}
/// `removeOne`: the first stack (Horizon keeps no selected item).
/// `removeOne`: the selected stack, else the first; nothing is selected after.
pub fn remove_one(&mut self, items: &Items) -> Option<ItemStack> {
if self.items.is_empty() {
return None;
}
let stack = self.items.remove(0);
let at =
usize::try_from(self.selected).map_or(0, |i| if i < self.items.len() { i } else { 0 });
let stack = self.items.remove(at);
self.weight = self
.weight
.sub(item_weight(items, &stack).times(stack.count));
self.selected = -1;
Some(stack)
}
/// `getSelectedItemIndex`.
pub fn selected(&self) -> i32 {
self.selected
}
/// The stacks inside, in display order (the first is the next out).
pub fn items(&self) -> &[ItemStack] {
&self.items
@@ -200,11 +213,28 @@ impl Contents {
/// `toImmutable`, written back into the bundle's component.
pub fn store(self, bundle: &mut ItemStack) {
bundle.data_mut().bundle_contents = self.items;
let data = bundle.data_mut();
data.bundle_contents = self.items;
data.bundle_selected = BundleSelected(self.selected);
bundle.tidy();
}
}
/// `BundleItem.toggleSelectedItem`: select `index`, or nothing when it is the
/// selected one already or outside the contents.
pub fn toggle_selected(bundle: &mut ItemStack, index: i32) {
let Some(data) = bundle.extra.as_deref_mut() else {
return;
};
let inside = (0..data.bundle_contents.len() as i32).contains(&index);
let selected = if data.bundle_selected.0 != index && inside {
index
} else {
-1
};
data.bundle_selected = BundleSelected(selected);
}
#[cfg(test)]
mod tests {
use super::Weight;
@@ -232,8 +262,10 @@ pub struct TooltipLayout {
/// The component's own width (96) and height, the text's excluded.
pub width: f32,
pub height: f32,
/// Each slot's top-left and the stack in it, in reading order.
/// Each slot's top-left and the stack in it, in drawing order.
pub slots: Vec<([f32; 2], ItemStack)>,
/// The position in `slots` of the selected item, which is drawn highlighted.
pub selected: Option<usize>,
/// The `+N` of the items past the grid: its top-left and the count.
pub overflow: Option<([f32; 2], u32)>,
/// The progress bar's top-left, its fill's width out of 94, and whether
@@ -266,6 +298,7 @@ pub fn tooltip_layout(
width: 96.0,
height: description_height + 13.0 + 8.0,
slots: Vec::new(),
selected: None,
overflow: None,
bar: [x + offset, y + description_height + 4.0],
fill: 0.0,
@@ -282,6 +315,7 @@ pub fn tooltip_layout(
let x_start = x + offset + 96.0;
let y_start = y + grid_height;
let mut slots = Vec::with_capacity(shown.len());
let mut selected = None;
let mut overflow = None;
// Rows fill bottom-up and columns right-to-left, as vanilla draws them.
let mut slot = 0;
@@ -290,8 +324,13 @@ pub fn tooltip_layout(
let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
if hidden > 0 && row == 1 && column == 1 {
overflow = Some((at, hidden));
} else if let Some(stack) = shown.get(slot) {
slots.push((at, stack.clone()));
} else if slot < shown.len() {
// `extractSlot`: the cell of slot number n holds item `size - n`.
let index = shown.len() - 1 - slot;
if usize::try_from(contents.selected()) == Ok(index) {
selected = Some(slots.len());
}
slots.push((at, shown[index].clone()));
slot += 1;
}
}
@@ -301,6 +340,7 @@ pub fn tooltip_layout(
width: 96.0,
height: grid_height + 13.0 + 8.0,
slots,
selected,
overflow,
bar: [x + offset, y + grid_height + 4.0],
// `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
@@ -349,8 +389,8 @@ mod tooltip_tests {
assert_eq!(layout.slots.len(), 12);
assert_eq!(layout.overflow, None);
assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
// Rows fill bottom-up and columns right-to-left: the first item is in
// the bottom-right cell, the twelfth in the top-left.
// Rows fill bottom-up and columns right-to-left: the twelfth item is in
// the bottom-right cell, the first in the top-left.
assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
assert_eq!(layout.slots[11].0, [0.0, 0.0]);
+26
View File
@@ -545,6 +545,32 @@ impl Enchantments {
}
out
}
/// `EnchantmentHelper.forEachModifier` as an item's tooltip lists them: the
/// `minecraft:attributes` effects of `stack`'s enchantments as rows of
/// (attribute, id, amount, operation, slot group), one per slot group the
/// enchantment lists.
pub fn modifier_rows(&self, stack: &ItemStack) -> Vec<(String, String, f64, String, String)> {
let mut rows = Vec::new();
for (id, level) in stack.enchantments() {
let Some(e) = self.get(id) else { continue };
for a in e.effects["minecraft:attributes"]
.as_array()
.into_iter()
.flatten()
{
for slot in &e.slots {
rows.push((
a["attribute"].as_str().unwrap_or("").to_owned(),
a["id"].as_str().unwrap_or("").to_owned(),
f64::from(level_value(&a["amount"], *level)),
a["operation"].as_str().unwrap_or("add_value").to_owned(),
slot.clone(),
));
}
}
}
rows
}
/// Sum of `add_value` amounts of one attribute from enchantments on `stack`.
pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 {
stack.map_or(0.0, |s| {
+148 -6
View File
@@ -180,7 +180,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
("Silent", m.silent),
("NoGravity", m.no_gravity),
("Glowing", m.glowing),
("Invulnerable", m.invulnerable_flag),
] {
if on {
map.insert(key.into(), Tag::Byte(1));
@@ -188,6 +187,26 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&horizon_world::nbt::JavaString::from(key));
}
}
map.insert(
"Invulnerable".into(),
Tag::Byte(i8::from(m.invulnerable_flag)),
);
map.insert(
"LeftHanded".into(),
Tag::Byte(i8::from(m.extra.left_handed)),
);
// Keys of older formats that structure templates still carry.
for key in [
"HandItems",
"ArmorItems",
"HandDropChances",
"ArmorDropChances",
"Dimension",
"HurtByTimestamp",
"Leashed",
] {
map.remove(&horizon_world::nbt::JavaString::from(key));
}
if m.ticks_frozen > 0 {
map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen));
} else {
@@ -197,7 +216,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))),
("LeftHanded", Tag::Byte(0)),
("current_impulse_context_reset_grace_time", Tag::Int(0)),
(
"Brain",
Tag::compound([("memories", Tag::Compound(Compound::new()))]),
@@ -209,7 +228,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
// Only breedable animals have an age; a loaded creature that was saved without
// one (a frog) stays without.
let aged = raw.is_none_or(|r| r.get("Age").is_some());
if m.kind.category == "creature" && aged {
if (m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin) && aged {
map.insert("Age".into(), Tag::Int(m.extra.age));
map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked)));
map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age));
@@ -260,6 +279,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
.or_insert_with(|| string("minecraft:classic"));
}
"minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => {
// Only Piglin.addAdditionalSaveData writes CannotHunt.
if id == "minecraft:piglin_brute" {
map.remove(&"CannotHunt".into());
}
map.insert(
"IsImmuneToZombification".into(),
Tag::Byte(i8::from(m.extra.flag2)),
@@ -498,8 +521,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
)])
});
}
"minecraft:zombie" => {
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
"minecraft:zombie" | "minecraft:husk" | "minecraft:drowned" => {
for (key, value) in [
("DrownedConversionTime", Tag::Int(-1)),
("InWaterTime", Tag::Int(-1)),
@@ -532,6 +554,21 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Tag::Byte(i8::from(m.extra.can_break_doors)),
);
}
if matches!(
id,
"minecraft:zombie"
| "minecraft:husk"
| "minecraft:drowned"
| "minecraft:zombie_villager"
| "minecraft:zombified_piglin"
| "minecraft:piglin"
| "minecraft:zoglin"
) {
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
}
if let Some(a) = m.extra.attributes.as_deref() {
put_attributes(map, m, a);
}
crate::mobs::raider::write_nbt(m, map);
crate::mobs::riders::write_nbt(m, map);
// LivingEntity equipment: what the mob holds now.
@@ -614,6 +651,89 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
tag
}
/// `AttributeMap.pack` for the attributes with a base or permanent modifier
/// finalizeSpawn set, over the saved list.
fn put_attributes(map: &mut Compound, m: &Mob, a: &crate::mobs::finalize::Attributes) {
use crate::mobs::finalize::{self, Attr, Op};
let mut list = match map.get(&"attributes".into()) {
Some(Tag::List(l)) => l.clone(),
_ => Vec::new(),
};
for attr in Attr::ALL {
let modifiers: Vec<Tag> = a
.modifiers
.iter()
.filter(|x| x.attr == attr)
.map(|x| {
let op = match x.op {
Op::AddValue => "add_value",
Op::AddMultipliedBase => "add_multiplied_base",
Op::AddMultipliedTotal => "add_multiplied_total",
};
Tag::compound([
("id", string(x.id)),
("amount", Tag::Double(x.amount.to_bits())),
("operation", string(op)),
])
})
.collect();
if modifiers.is_empty() && !a.bases.iter().any(|(b, _)| *b == attr) {
continue;
}
let id = format!("minecraft:{}", attr.name());
let mut entry = vec![
("id", string(&id)),
("base", Tag::Double(finalize::base_value(m, attr).to_bits())),
];
if !modifiers.is_empty() {
entry.push(("modifiers", Tag::List(modifiers)));
}
let entry = Tag::compound(entry);
match list
.iter_mut()
.find(|t| text(t.get("id")).as_deref() == Some(id.as_str()))
{
Some(t) => *t = entry,
None => list.push(entry),
}
}
map.insert("attributes".into(), Tag::List(list));
}
/// `Brain.Packed`: the memories finalizeSpawn set, over the saved ones.
pub fn put_brain(map: &mut Compound, m: &Mob, dimension: &str) {
if m.extra.memories.is_empty() {
return;
}
let mut memories = match map.get(&"Brain".into()).and_then(|b| b.get("memories")) {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
};
for &(name, value, ttl) in &m.extra.memories {
let value = match name {
"hunted_recently" => Tag::Byte(value as i8),
"home" => match m.extra.home {
Some(p) => Tag::compound([
("dimension", string(dimension)),
("pos", Tag::IntArray(p.to_vec())),
]),
None => continue,
},
_ => Tag::Int(value as i32),
};
let mut memory = vec![("value", value)];
if ttl != i64::MAX {
memory.push(("ttl", Tag::Long(ttl)));
}
memories.insert(
format!("minecraft:{name}").as_str().into(),
Tag::compound(memory),
);
}
map.insert(
"Brain".into(),
Tag::compound([("memories", Tag::Compound(memories))]),
);
}
/// `CustomName`: a text component saved as a string or a `{text: ..}` compound.
fn custom_name(tag: &Tag) -> Option<String> {
match tag.get("CustomName")? {
@@ -633,6 +753,22 @@ pub fn name_text(tag: &Tag) -> Text {
t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)),
}
}
/// Mob.finalizeSpawn's follow range bonus in the saved attributes.
pub(crate) fn spawn_bonus(tag: &Tag) -> Option<f64> {
let Some(Tag::List(attrs)) = tag.get("attributes") else {
return None;
};
let range = attrs
.iter()
.find(|a| text(a.get("id")).as_deref() == Some("minecraft:follow_range"))?;
let Some(Tag::List(modifiers)) = range.get("modifiers") else {
return None;
};
let bonus = modifiers
.iter()
.find(|x| text(x.get("id")).as_deref() == Some("minecraft:random_spawn_bonus"))?;
float(bonus.get("amount"))
}
pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -> Option<Mob> {
let kind = types.get(&self::kind(tag)?)?.clone();
let position = position(tag)?;
@@ -658,6 +794,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
}
}
}
if let Some(bonus) = spawn_bonus(tag) {
use crate::mobs::finalize::{Attr, Op, add_modifier};
let id = "minecraft:random_spawn_bonus";
add_modifier(&mut m, Attr::FollowRange, id, bonus, Op::AddMultipliedBase);
}
m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32);
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
// What it holds (equipment.mainhand / offhand), when saved.
@@ -699,7 +840,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
m.custom_name = custom_name(tag);
m.custom_name_text = tag.get("CustomName").map(name_text);
if m.kind.category == "creature" {
m.extra.left_handed = flag(tag, "LeftHanded");
if m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin {
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32;
m.extra.age_locked = flag(tag, "AgeLocked");
@@ -35,6 +35,18 @@ impl Damage {
..Self::default()
}
}
/// A block that starts to fall: anvils hurt, and a brushable block
/// breaks where it lands (BrushableBlock.tick: disableDrop).
pub fn falling(block: &str) -> Self {
if block.ends_with("anvil") {
Self::anvil()
} else {
Self {
cancel_drop: block.starts_with("minecraft:suspicious_"),
..Self::default()
}
}
}
pub fn from_nbt(tag: &Tag, anvil: bool) -> Self {
Self {
hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0),
@@ -181,6 +193,14 @@ pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_brushable_blocks_break_where_they_land() {
assert!(Damage::falling("minecraft:suspicious_gravel").cancel_drop);
assert!(Damage::falling("minecraft:suspicious_sand").cancel_drop);
assert!(!Damage::falling("minecraft:gravel").cancel_drop);
assert!(Damage::falling("minecraft:chipped_anvil").hurt_entities);
}
#[test]
fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() {
let damage = Damage::anvil();
+222 -18
View File
@@ -18,6 +18,7 @@ mod boats;
mod books;
mod bossbars;
mod breezes;
mod bundles;
mod campfire;
mod campfire_douse;
mod cartography;
@@ -1275,6 +1276,8 @@ struct Game<'a> {
inv_clicks: horizon_client::container_screen::Clicks,
/// The Mouse Tweaks extra's drag and wheel (`tweaks`).
tweaks: tweaks::Tweaks,
/// The wheel and hovered slot of `BundleMouseActions`.
bundle_mouse: bundles::BundleMouse,
/// The last inventory click, for the double click that gathers a stack.
last_inv_click: Option<(std::time::Instant, usize, bool)>,
/// `lastQuickMoved`: what the last Shift click moved, which a Shift
@@ -1442,6 +1445,10 @@ struct Game<'a> {
titles: titles::Titles,
/// `Hud.toolHighlightTimer`: the selected item name.
tool_highlight: horizon_client::hud_overlays::ToolHighlight,
/// `Hud.autosaveIndicatorValue`.
saving_indicator: horizon_client::hud_overlays::SavingIndicator,
/// This game's world is autosaving this tick (`MinecraftServer.isSaving`).
autosaving: bool,
applied_modifiers: Vec<(String, String)>,
experience: Experience,
orbs: Vec<ExperienceOrb>,
@@ -1673,7 +1680,7 @@ struct Game<'a> {
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
/// Successful crits (attacking guest, hit entity), queued while the hub is taken.
lan_critical_hits: Vec<(Option<u32>, i32)>,
lan_critical_hits: Vec<(Option<u32>, i32, bool)>,
/// Global level events for every guest (`ServerLevel.globalLevelEvent`).
lan_global_events: Vec<(i32, [i32; 3], i32)>,
/// `ContainerOpenersCounter`: how many players (the host and the guests)
@@ -1691,6 +1698,9 @@ struct Game<'a> {
/// The acting guest's cooldowns, as (item, ticks): their packet needs the
/// hub's item registry, which the guest's turn does not hold.
guest_cooldowns: Vec<(Arc<str>, i32)>,
/// The acting guest's own entity events (`ServerPlayer.connection.send`),
/// sent with their entity id, which the guest's turn does not hold.
guest_entity_events: Vec<i8>,
/// `broadcastToAdmins` lines a guest's command queued, sent once it
/// returns: the line, whether operators get it and whether the console
/// logs it.
@@ -1821,9 +1831,46 @@ impl Game<'_> {
fn reach(&self) -> f64 {
if self.creative { 5.0 } else { 4.5 }
}
/// Outline shapes that depend on more than the block state, as one box
/// in block space: `LightBlock` and `ScaffoldingBlock.getShape` are a full
/// block while the main hand holds the block's own item
/// (`CollisionContext.isHoldingItem`), and `ShulkerBoxBlock.getShape`
/// grows with the lid (`ShulkerBoxBlockEntity.getBoundingBox`).
fn context_outline(&self, pos: [i32; 3], state: BlockStateId) -> Option<[f64; 6]> {
let name = &self.res.facts().get(state).name;
if matches!(&**name, "minecraft:light" | "minecraft:scaffolding") {
return self
.held()
.is_some_and(|s| *s.item == **name)
.then_some([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]);
}
if !name.ends_with("shulker_box") {
return None;
}
let progress = self.be_anims.shulkers.get(&pos).map_or(0.0, |s| s.progress);
let facing = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing").cloned());
let d = facing_offset(facing.as_deref().unwrap_or("up"));
let mut b = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
for a in 0..3 {
match d[a] {
1 => b[a + 3] += 0.5 * f64::from(progress),
-1 => b[a] -= 0.5 * f64::from(progress),
_ => {}
}
}
Some(b)
}
/// A block's outline boxes in world space (`getShape` plus the random offset).
fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if let Some(b) = self.context_outline(pos, state) {
return vec![std::array::from_fn(|i| f64::from(pos[i % 3]) + b[i])];
}
let f = self.res.facts().get(state);
let o = if f.outline_offset {
self.pack
@@ -2118,6 +2165,33 @@ impl Game<'_> {
}
/// `TerrainParticle` at `pos`: the model's particle sprite and tint source
/// 0's `colorAsTerrainParticle` (white when the block has none).
/// `HoneyBlock.showSlideParticles` (entity event 53): five honey block
/// particles at the entity.
fn honey_slide_particles(&mut self, at: [f64; 3]) {
use horizon_client::particles::{ParticleOptions, ParticleType};
let Some(honey) = self
.pack
.assets
.registry
.default_state("minecraft:honey_block")
else {
return;
};
let block = [
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
];
if let Some((sprite, tint)) = self.particle_sprite(honey, block) {
for _ in 0..5 {
self.particles.add(
&ParticleOptions::block(ParticleType::Block, sprite.clone(), tint),
at,
[0.0; 3],
);
}
}
}
fn particle_sprite(&self, state: BlockStateId, pos: [i32; 3]) -> Option<(String, u32)> {
let sprite = Self::block_particle_sprite(&self.pack, state)?;
let chunks = &self.world.chunks;
@@ -2335,11 +2409,18 @@ impl Game<'_> {
yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength,
];
self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40);
if thrown_from_hand && self.lan_acting.is_none() {
let uuid = self.level.ensure_player_uuid();
if thrown_from_hand {
let uuid = self.acting_player_uuid();
self.dropped.last_mut().unwrap().thrower = Some(uuid);
}
}
/// The UUID of the player acting: the guest whose turn it is, else the host.
pub(super) fn acting_player_uuid(&mut self) -> [i32; 4] {
match self.lan_acting_uuid {
Some(guest) => horizon_client::lan::playerdata::uuid_ints(guest),
None => self.level.ensure_player_uuid(),
}
}
fn tick_items(&mut self) {
let mut items = std::mem::take(&mut self.dropped);
// ServerLevel.tick: only entities in entity-ticking chunks tick.
@@ -2944,6 +3025,17 @@ impl Game<'_> {
pos,
data,
} => self.smash_dust(pos, data),
// LevelEventHandler 2002 and 2007: a potion's splash.
LevelEvent::LevelEvent {
id: 2002,
pos,
data,
} => self.potion_splash_particles(pos, data, false),
LevelEvent::LevelEvent {
id: 2007,
pos,
data,
} => self.potion_splash_particles(pos, data, true),
LevelEvent::LevelEvent {
id: id @ 3002..=3005,
pos,
@@ -2979,6 +3071,8 @@ impl Game<'_> {
1044 => Some(("minecraft:block.smithing_table.use", 1.0)),
// LevelEvent.SOUND_PAGE_TURN (a lectern's page).
1043 => Some(("minecraft:item.book.page_turn", 1.0)),
// LevelEvent.SOUND_SPLASH_POTION and its instant twin.
1053 | 1054 => Some(("minecraft:entity.splash_potion.break", 1.0)),
_ => None,
};
if let Some((name, volume)) = sound {
@@ -2988,7 +3082,7 @@ impl Game<'_> {
- self.world.random.next_float())
* 0.8
}
1029 | 1030 | 1042 | 1043 | 1044 => {
1029 | 1030 | 1042 | 1043 | 1044 | 1053 | 1054 => {
self.world.random.next_float() * 0.1 + 0.9
}
1019 | 1021 => {
@@ -2998,7 +3092,7 @@ impl Game<'_> {
}
_ => 1.0,
};
if matches!(id, 1019 | 1021 | 1029 | 1030) {
if matches!(id, 1019 | 1021 | 1029 | 1030 | 1053 | 1054) {
// Clients play the anvil sound from its level event;
// capturing it also sends a duplicate sound packet.
self.audio.play_unshared(name, c, volume, pitch);
@@ -3047,11 +3141,9 @@ impl Game<'_> {
drop_item: true,
fall_distance: 0.0,
stuck: Vec3::ZERO,
damage: if self.res.facts().get(state).name.ends_with("anvil") {
horizon_client::falling_block::Damage::anvil()
} else {
Default::default()
},
damage: horizon_client::falling_block::Damage::falling(
&self.res.facts().get(state).name,
),
saved: None,
});
}
@@ -3154,6 +3246,31 @@ impl Game<'_> {
LevelEvent::BlockEntityEvent { pos, a, b, .. } => {
self.block_entity_event([pos.x, pos.y, pos.z], a, b)
}
// NoteBlock.triggerEvent: a NOTE particle above, coloured by
// the note (`note / 24.0` in the x speed).
LevelEvent::BlockEvent {
pos,
state,
kind: "note_particle",
} => {
use horizon_client::particles::{ParticleOptions, ParticleType};
let note = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("note")?.parse::<f64>().ok())
.unwrap_or(0.0);
self.particles.add(
&ParticleOptions::simple(ParticleType::Note),
[
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.2,
f64::from(pos.z) + 0.5,
],
[note / 24.0, 0.0, 0.0],
);
}
LevelEvent::GrowTree { .. }
| LevelEvent::PlaceFeature { .. }
| LevelEvent::BlockEvent { .. } => {}
@@ -3529,7 +3646,7 @@ impl Game<'_> {
} else if let Some(tag) = spill::saved_entity(&self.world, pos) {
self.pending.record_saved(pos, &tag);
}
self.creaking_heart_broken(pos);
self.creaking_heart_broken(pos, true);
let hive = match self.world.block_entities.get(&key) {
Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)),
_ => None,
@@ -4088,6 +4205,7 @@ impl Game<'_> {
if &*stack.item == "minecraft:spyglass" {
// SpyglassItem.USE_DURATION, then finishUsingItem.
if ticks + 1 >= 1200 {
self.send_use_item_complete();
self.stop_spyglass();
self.using = None;
} else {
@@ -4109,6 +4227,7 @@ impl Game<'_> {
}
if ticks >= duration {
self.using = None;
self.send_use_item_complete();
// ItemStack.finishUsingItem's applyAfterUseComponentSideEffects.
self.apply_use_cooldown(&stack);
self.finish_consuming(&info, consumable, &stack);
@@ -4321,6 +4440,12 @@ impl Game<'_> {
// The world's spawn from the start, not only once saved: a bed set
// before the first save must not become it.
self.level.world_spawn.get_or_insert([x, y, z]);
// The "Bonus Chest" create-world option, placed once with the spawn.
if horizon_client::save::WorldGen::read(&self.world_root)
.is_some_and(|g| g.bonus_chest)
{
self.place_bonus_chest([x, y, z])?;
}
}
let s = self
.level
@@ -4424,7 +4549,11 @@ impl Game<'_> {
self.world.weather.tick_levels();
self.tick_weather_effects();
}
if self.ticks.is_multiple_of(6000) {
self.autosaving = self.ticks.is_multiple_of(6000);
if let Some(serving) = &self.serving {
serving.set_saving(self.autosaving);
}
if self.autosaving {
self.save_game_with(false)?;
}
if running {
@@ -4635,9 +4764,32 @@ impl Game<'_> {
};
self.audio.play(name, Some(feet), volume, pitch);
}
// LivingEntity.checkFallDamage: the block's crumbs where the fall landed.
MotionEvent::Fall(horizon_client::landing::FallEvent::Particles {
state,
position,
count,
speed,
}) => self.landing_dust(None, state, position, count, speed),
MotionEvent::Fall(event) => self.landing_block_updates(&event),
MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
MotionEvent::HoneySlide {
sound, particles, ..
} => {
if sound {
self.audio
.play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0);
}
if particles {
self.honey_slide_particles(feet);
// The server's event 53 reaches the guests too.
let id = self.lan.as_ref().map(|h| h.host_entity);
if let Some(id) = id {
self.lan_entity_event(id, 53, feet);
}
}
}
MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
MotionEvent::CauldronExtinguish { pos } => self.cauldron_extinguish(pos),
MotionEvent::InsideWitherRose => self.wither_rose_contact(),
@@ -4740,6 +4892,7 @@ impl Game<'_> {
/// What the tick runs after the local player's own update: effects, the
/// world's entities and blocks, and the network hub.
fn tick_world(&mut self, running: bool) -> Result<()> {
self.share_spawn_conditions();
self.update_chunk_tickets();
horizon_client::spans::time("tick_effects", || self.tick_effects(running));
// Player.tick's ItemCooldowns.tick for the window's player (a
@@ -4747,6 +4900,7 @@ impl Game<'_> {
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
self.cooldowns.tick();
horizon_client::spans::time("tick_using", || self.tick_using());
self.tick_bundle_hover();
horizon_client::spans::time("tick_hud", || self.tick_hud());
// The player's digging comes in with its packets, before the level
// ticks; ServerLevel.tick then runs the scheduled and random block
@@ -5444,6 +5598,7 @@ impl Game<'_> {
Screen::Mod => self.draw_mod_screen(&mut batch),
Screen::Playing | Screen::Options | Screen::Win => {}
}
self.draw_saving_indicator(&mut batch);
self.draw_toasts(&mut batch);
self.draw_pack_toasts(&mut batch);
self.remote_hud(&mut batch);
@@ -5944,6 +6099,12 @@ impl Game<'_> {
/// Several clicks on one menu instance (a quick craft drag is three).
fn menu_ops(&mut self, ops: &[(Option<usize>, i32, horizon_client::menu::Input)]) -> bool {
use horizon_client::menu::Input;
// BundleMouseActions.onSlotClicked: a Shift click or a swap clears the bundle's selection.
for &(slot, _, input) in ops {
if let (Some(slot), Input::QuickMove | Input::Swap) = (slot, input) {
self.unselect_bundle(slot);
}
}
if self.remote.is_some() && self.screen == Screen::Inventory {
// On a server the clicks are the server's: predicted and sent.
return self.remote_menu_ops(ops);
@@ -7269,7 +7430,12 @@ impl Game<'_> {
self.see_through_vertices = see_through;
// Entity shadows (EntityRenderer.extractShadow).
self.mark_translucent_entity(out.len(), "minecraft:entity_shadow");
if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() {
let shadow_sprite = self
.settings
.entity_shadows
.then(|| self.gui.atlas.sprites.get("misc/shadow").copied())
.flatten();
if let Some(sprite) = shadow_sprite {
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
let darken = self.sky_darken();
let a = alpha;
@@ -7668,7 +7834,7 @@ impl Game<'_> {
/// strength and whether it is a critical hit): the weapon and effects
/// scaled by the attack strength, a mace's smash, the critical hit, then
/// enchantments.
pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) {
pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool, bool) {
let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage);
// Riptide's spin replaces the attack damage attribute.
let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg);
@@ -7696,8 +7862,9 @@ impl Game<'_> {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
amount += self.enchant_damage_bonus(target_kind) * scale;
(amount, scale, crit)
let magic_boost = self.enchant_damage_bonus(target_kind) * scale;
amount += magic_boost;
(amount, scale, crit, magic_boost > 0.0)
}
/// `Player.getAttackStrengthScale(0.5)`.
fn attack_strength_scale(&self) -> f32 {
@@ -7884,7 +8051,7 @@ impl Game<'_> {
pub(super) fn attack_mob(&mut self, index: usize) {
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
let (amount, scale, crit) = self.melee_damage(&target_kind);
let (amount, scale, crit, magic) = self.melee_damage(&target_kind);
let sweep = self.sweep_attack_position(scale, crit);
let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale);
self.attack_ticks = 0;
@@ -7947,6 +8114,18 @@ impl Game<'_> {
feet,
width,
height,
false,
);
}
// Player.attackVisualEffects: magicCrit when the enchantments added damage.
if magic {
self.critical_hit(
self.lan_acting,
self.mobs[index].id as i32,
feet,
width,
height,
true,
);
}
if actual > 2.0 {
@@ -8175,6 +8354,7 @@ impl Game<'_> {
);
self.session_lock = Some(session_lock);
self.end.set_locator(locator);
self.share_spawn_conditions();
self.score = Default::default();
self.fns = Default::default();
self.bosses = Default::default();
@@ -8313,6 +8493,7 @@ impl Game<'_> {
seed,
)?;
self.end.set_locator(locator);
self.share_spawn_conditions();
Ok((streaming, save))
}
/// Change dimension through a portal (Entity.changeDimension with
@@ -10797,6 +10978,17 @@ impl Game<'_> {
[0.0; 3]
};
let p = h.pos.map(f64::from);
if let Some(b) = self.context_outline(h.pos, state) {
return horizon_client::blocks::cube_edges()
.iter()
.map(|e| {
std::array::from_fn(|i| {
let k = i % 3;
p[k] + b[k] + e[i] * (b[k + 3] - b[k])
})
})
.collect();
}
f.outline_edges
.iter()
.map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + e[i]))
@@ -11859,6 +12051,7 @@ impl ApplicationHandler for Game<'_> {
}
if self.screen == Screen::Inventory
&& d != 0.0
&& !self.bundle_scroll(scaled(raw_x), scaled(raw_y))
&& !self.tweak_scroll(d, self.inventory_target().0)
{
self.station_scroll(d);
@@ -12648,6 +12841,7 @@ impl<'a> Game<'a> {
craft_table: None,
inv_drag: None,
tweaks: Default::default(),
bundle_mouse: Default::default(),
inv_clicks: Default::default(),
last_inv_click: None,
last_quick_moved: None,
@@ -12709,7 +12903,14 @@ impl<'a> Game<'a> {
level,
session_lock: None,
audio,
music: Default::default(),
music: {
// The manager starts with the saved option (MusicManager's constructor).
let mut music = horizon_client::music::MusicManager::default();
music.frequency = horizon_client::music::MusicFrequency::parse(
&settings.file.name("musicFrequency"),
);
music
},
ambience: Default::default(),
sound_paused: false,
cart_sounds: HashSet::new(),
@@ -12753,6 +12954,8 @@ impl<'a> Game<'a> {
command_source: None,
titles: Default::default(),
tool_highlight: Default::default(),
saving_indicator: Default::default(),
autosaving: false,
applied_modifiers: Vec::new(),
experience: Experience::default(),
orbs: Vec::new(),
@@ -12905,6 +13108,7 @@ impl<'a> Game<'a> {
lan_acting: None,
guest_packets: Vec::new(),
guest_cooldowns: Vec::new(),
guest_entity_events: Vec::new(),
lan_acting_name: None,
lan_acting_uuid: None,
chat_capture: None,
+103
View File
@@ -0,0 +1,103 @@
//! `BundleMouseActions`: the wheel over a bundle in a container screen selects
//! one of the items it shows, which a click that takes one out of it then takes
//! (`BundleContents.Mutable.removeOne`). Moving off the bundle clears the
//! selection. On a server the selection is sent to it (`ServerboundSelectBundleItemPacket`).
use super::{Game, Screen};
use horizon_client::{
bundle::{Contents, toggle_selected},
mouse::ScrollWheelHandler,
};
use horizon_protocol::packets::play::{self, Serverbound as S};
#[derive(Default)]
pub(super) struct BundleMouse {
wheel: ScrollWheelHandler,
/// The slot under the cursor at the last tick (`AbstractContainerScreen.hoveredSlot`).
hovered: Option<usize>,
}
impl Game<'_> {
/// A slot a bundle can be selected in: the player's inventory, the off hand and a
/// container's own slots. A server only knows these in the inventory and chest-like menus.
fn bundle_slot(&mut self, slot: usize) -> bool {
(slot < 36 || slot == 504 || (300..500).contains(&slot))
&& (self.remote.is_none() || self.remote_storage_open())
&& (slot < 36 || slot == 504 || self.slots().contains(&slot))
}
/// `BundleMouseActions.onMouseScrolled`: the wheel over a bundle moves the selection
/// through the items its tooltip shows. True when the bundle took the wheel.
pub(super) fn bundle_scroll(&mut self, x: f64, y: f64) -> bool {
let Some(slot) = self.inventory_target().0 else {
return false;
};
if !self.bundle_slot(slot) {
return false;
}
let stack = self.slot_mut(slot).clone();
let items = self.res.items();
let Some(bundle) = stack.filter(|s| items.get(&s.item).is_some_and(|i| i.bundle)) else {
return false;
};
let shown = Contents::of(items, &bundle).map_or(0, |c| c.shown_count());
if shown == 0 {
return false;
}
let (wheel_x, wheel_y) = self.bundle_mouse.wheel.on_mouse_scroll(x, y);
let wheel = if wheel_y == 0 { -wheel_x } else { wheel_y };
if wheel != 0 {
let selected = bundle.data().map_or(-1, |d| d.bundle_selected.0);
let next = ScrollWheelHandler::next_selection(f64::from(wheel), selected, shown as i32);
if next != selected {
self.select_bundle(slot, next);
}
}
true
}
/// `BundleMouseActions.toggleSelectedBundleItem`: the stack here and, on a server, there.
fn select_bundle(&mut self, slot: usize, index: i32) {
if let Some(stack) = self.slot_mut(slot) {
toggle_selected(stack, index);
}
if self.remote.is_some() {
let (_, menu) = self.remote_menu();
if let Some(menu_slot) = Self::menu_slot_index(&menu, slot) {
self.send(S::SelectBundleItem(play::SelectBundleItem {
slot: menu_slot as i32,
index,
}));
}
}
}
/// `BundleMouseActions.unselectedBundleItem` for the bundle in `slot`, if it has a selection.
pub(super) fn unselect_bundle(&mut self, slot: usize) {
if !self.bundle_slot(slot) {
return;
}
let selected = self
.slot_mut(slot)
.as_ref()
.and_then(|s| s.data())
.is_some_and(|d| d.bundle_selected.0 >= 0);
if selected {
self.select_bundle(slot, -1);
}
}
/// `AbstractContainerScreen.onStopHovering` (and `onClose`): leaving a slot, or the
/// screen, clears the bundle's selection.
pub(super) fn tick_bundle_hover(&mut self) {
let now = if self.screen == Screen::Inventory {
self.inventory_target().0
} else {
None
};
if let Some(left) = std::mem::replace(&mut self.bundle_mouse.hovered, now)
&& Some(left) != now
{
self.unselect_bundle(left);
}
}
}
@@ -4,8 +4,12 @@
//! on the game that has the window, in-frame or following a server, never on
//! a server: nothing of them goes over the network.
use super::Game;
use horizon_client::blocks::RenderShape;
use horizon_client::mobs::{MobEvent, ambient};
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_client::motion::{LAVA, WATER};
use horizon_client::particles::{ParticleEngine, ParticleOptions, ParticleType};
use horizon_client::pose::Pose;
use horizon_core::{geometry::Vec3, random::RandomSource};
impl Game<'_> {
pub(super) fn tick_client_ambient(&mut self) {
@@ -33,5 +37,209 @@ impl Game<'_> {
}
}
self.eye_particles();
self.sprint_dust();
self.effect_swirls();
}
/// `Entity.baseTick`'s `spawnSprintParticle` on a client: dust of the
/// block under a sprinting player's feet streams back from them every
/// tick, for the window's own player and for the other players it sees.
fn sprint_dust(&mut self) {
// Each runner's feet, movement and supporting block.
let mut runners: Vec<(Vec3, Vec3, Option<[i32; 3]>)> = Vec::new();
// Entity.canSpawnSprintParticle.
if let Some(p) = self.player.as_ref()
&& p.sprinting
&& !p.spectator
&& p.pose != Pose::Crouching
&& !p.health.dead_or_dying()
&& !p.fluids.was_touching_water
&& !p.is_in_lava()
&& p.fluid_height(WATER) <= 0.0
&& p.fluid_height(LAVA) <= 0.0
{
let support = p.ground.supporting_block.map(|b| [b.x, b.y, b.z]);
runners.push((p.position, p.velocity, support));
}
let guests = self.lan.iter().flat_map(|host| host.models.values());
for m in self.mobs.iter().chain(guests) {
// Another player's fluids aren't known here: none where they stand.
let feet = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
if m.extra.sprinting
&& !m.extra.crouching
&& m.alive()
&& &*m.kind.id == "minecraft:player"
&& self
.res
.facts()
.get(self.world.block(feet[0], feet[1], feet[2]))
.fluid_level
== 0
{
runners.push((m.position, m.position.subtract(m.previous), None));
}
}
for (position, movement, support) in runners {
// Entity.getOnPosLegacy: getOnPos(0.2).
let below = (position.y - f64::from(0.2f32)).floor() as i32;
let tall = |game: &Self, s: [i32; 3]| {
let name = game.block_name(s);
[
"minecraft:fences",
"minecraft:walls",
"minecraft:fence_gates",
]
.iter()
.any(|tag| game.block_in_tag(tag, &name))
};
let at = match support {
Some(s) if tall(self, s) => s,
Some(s) => [s[0], below, s[2]],
None => [position.x.floor() as i32, below, position.z.floor() as i32],
};
let state = self.world.block(at[0], at[1], at[2]);
if self.res.facts().get(state).render_shape == RenderShape::Invisible {
continue;
}
let Some((sprite, tint)) = self.particle_sprite(state, at) else {
continue;
};
let width = f64::from(0.6f32);
let r = self.particles.random();
let mut x = position.x + (r.next_double() - 0.5) * width;
let mut z = position.z + (r.next_double() - 0.5) * width;
// Clamped into the block when the feet are in another column.
if position.x.floor() as i32 != at[0] {
x = x.clamp(f64::from(at[0]), f64::from(at[0]) + 1.0);
}
if position.z.floor() as i32 != at[2] {
z = z.clamp(f64::from(at[2]), f64::from(at[2]) + 1.0);
}
self.particles.add(
&ParticleOptions::block(ParticleType::Block, sprite, tint),
[x, position.y + 0.1, z],
[movement.x * -4.0, 1.5, movement.z * -4.0],
);
}
}
/// `LivingEntity.tickEffects` on a client: the swirls around an entity
/// with visible effects, from the particles its synched data lists. The
/// window's player has its own effects, a server's mobs and players the
/// list the server sent, and the mobs and guests of a game in the frame
/// theirs.
fn effect_swirls(&mut self) {
if let Some(p) = self.player.as_ref() {
let effects = &self.potions.effects.list;
let list: Vec<_> = effects
.iter()
.filter(|e| e.visible)
.filter_map(|e| effect_particle(e.id, e.ambient))
.collect();
let ambient = effects.iter().filter(|e| e.visible).all(|e| e.ambient);
let invisible = effects.iter().any(|e| e.id == "invisibility");
let size = (
f64::from(p.dimensions.width),
f64::from(p.dimensions.height),
);
swirl(
&mut self.particles,
p.position,
size,
&list,
ambient,
invisible,
);
}
let guests = self.lan.iter().flat_map(|host| host.models.values());
for m in self.mobs.iter().chain(guests) {
if !m.alive() {
continue;
}
let size = (f64::from(m.width()), f64::from(m.height()));
let invisible = m.invisible || m.has_effect("minecraft:invisibility");
if m.extra.effect_particles.is_empty() {
// A mob of this game: its own effects, visible and not ambient.
if m.extra.effects.is_empty() {
continue;
}
let list: Vec<_> = m
.extra
.effects
.iter()
.filter(|e| !m.extra.hidden_effects.contains(&e.0))
.filter_map(|e| effect_particle(e.0, false))
.collect();
swirl(
&mut self.particles,
m.position,
size,
&list,
false,
invisible,
);
} else {
let list = &m.extra.effect_particles;
let ambient = m.extra.effect_ambient;
swirl(
&mut self.particles,
m.position,
size,
list,
ambient,
invisible,
);
}
}
}
}
/// `MobEffect.particleFactory`: the omens have particles of their own, any
/// other effect an entity effect in its colour, faint when ambient.
pub(super) fn effect_particle(effect: &str, ambient: bool) -> Option<ParticleOptions> {
Some(match effect.trim_start_matches("minecraft:") {
"trial_omen" => ParticleOptions::simple(ParticleType::TrialOmen),
"raid_omen" => ParticleOptions::simple(ParticleType::RaidOmen),
other => {
let color = horizon_client::brewing::effect(other)?.color;
let channel = |shift: u32| ((color >> shift) & 255) as f32 / 255.0;
// MobEffect.AMBIENT_ALPHA is 38 of 255.
let alpha = if ambient { 38.0 / 255.0 } else { 1.0 };
ParticleOptions::colored(
ParticleType::EntityEffect,
[channel(16), channel(8), channel(0), alpha],
)
}
})
}
/// One tick of `LivingEntity.tickEffects`' client branch: a one in four
/// chance (one in fifteen while invisible, a fifth of either when all the
/// effects are ambient) of one of the particles at a random spot of the box.
fn swirl(
particles: &mut ParticleEngine,
feet: Vec3,
size: (f64, f64),
list: &[ParticleOptions],
ambient: bool,
invisible: bool,
) {
if list.is_empty() {
return;
}
let bound = if invisible { 15 } else { 4 } * if ambient { 5 } else { 1 };
let r = particles.random();
let Ok(0) = r.next_int_bound(bound) else {
return;
};
// Util.getRandom, then getRandomX(0.5), getRandomY and getRandomZ.
let pick = r.next_int_bound(list.len() as i32).unwrap_or_default() as usize;
let x = feet.x + size.0 * (2.0 * r.next_double() - 1.0) * 0.5;
let y = feet.y + size.1 * r.next_double();
let z = feet.z + size.0 * (2.0 * r.next_double() - 1.0) * 0.5;
particles.add(&list[pick], [x, y, z], [1.0; 3]);
}
+32
View File
@@ -10,6 +10,9 @@ struct Entry {
fall_distance: f32,
/// The causing entity: its id (for comparisons) and display name.
attacker: Option<(u32, Text)>,
/// The direct entity's display name when no entity caused the damage
/// (`DamageSource.directEntity`: a potion with no thrower, a cloud).
direct: Option<Text>,
}
#[derive(Default)]
pub(super) struct CombatTracker {
@@ -19,6 +22,8 @@ pub(super) struct CombatTracker {
/// Attackers of damage dealt this tick, claimed by the matching
/// `RecordedDamage` event.
pending: Vec<(String, (u32, Text))>,
/// `pending` for a direct entity with no causing entity: only its name.
pending_direct: Vec<(String, Text)>,
/// `LivingEntity.lastHurtByMob` and its timestamp (the kill credit).
last_hurt_by: Option<((u32, Text), i64)>,
/// The mob the player last hurt (`getLastHurtMob`) and when.
@@ -66,6 +71,14 @@ impl Game<'_> {
.pending
.push((damage_type.to_owned(), (id, name)));
}
/// The `DamageSource.directEntity` of the next `damage_type` damage when
/// nothing caused it (a splash potion nobody threw): the death message
/// names it instead (`getLocalizedDeathMessage`). It is no kill credit.
pub(super) fn note_direct_entity(&mut self, damage_type: &str, name: Text) {
self.combat
.pending_direct
.push((damage_type.to_owned(), name));
}
/// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the
/// source's `DamageEffects` (`Player.getHurtSound`).
pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) {
@@ -94,6 +107,15 @@ impl Game<'_> {
.iter()
.position(|(t, _)| *t == name)
.map(|i| self.combat.pending.remove(i).1);
let direct = match attacker {
Some(_) => None,
None => self
.combat
.pending_direct
.iter()
.position(|(t, _)| *t == name)
.map(|i| self.combat.pending_direct.remove(i).1),
};
let (fall_location, fall_distance) = self.fall_location();
let now = self.world.game_time;
if let Some(a) = &attacker {
@@ -111,10 +133,12 @@ impl Game<'_> {
fall_location,
fall_distance,
attacker,
direct,
});
self.combat.last_damage = now;
}
self.combat.pending.clear();
self.combat.pending_direct.clear();
self.combat.fall_before = self.player.as_ref().map_or(0.0, |p| p.fall_distance);
}
/// `FallLocation.getCurrentFallLocation` and the fall distance so far.
@@ -224,6 +248,7 @@ impl Game<'_> {
let entries = std::mem::take(&mut self.combat.entries);
let killing = entries.last().expect("checked above");
let killer = killing.attacker.clone();
let direct = killing.direct.clone();
if def.1 == "fall_variants"
&& let Some(knock) = knock.and_then(|i| entries.get(i))
{
@@ -248,15 +273,22 @@ impl Game<'_> {
.append(Text::literal("]"));
return Text::translate(&format!("{key}.message"), &[me, link]);
}
// `getLocalizedDeathMessage`: the causing entity's name, or the
// direct entity's when nothing caused the damage.
if let Some((_, name)) = killer {
return Text::translate(&key, &[me, name]);
}
if let Some(name) = direct {
return Text::translate(&key, &[me, name]);
}
// getKillCredit: the last mob that hurt the player in the past 100 ticks.
if let Some(((_, name), at)) = &self.combat.last_hurt_by
&& self.world.game_time - at <= 100
{
return Text::translate(&format!("{key}.player"), &[me, name.clone()]);
}
// No entity at all: the one-argument message, as vanilla sends it (a
// template that names a killer then shows as written).
Text::translate(&key, &[me])
}
}
+1 -2
View File
@@ -541,8 +541,7 @@ impl Game<'_> {
.enumerate()
// The kinds /data can write (entity_nbt).
.filter(|(_, p)| {
p.arrow.is_some()
|| matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
})
.map(|(i, _)| Target::Projectile(i)),
);
@@ -91,7 +91,12 @@ impl Game<'_> {
}
Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) {
Some(m) => {
m.add_effect(namespaced(effect.id), duration, amplifier);
let name = namespaced(effect.id);
m.add_effect(name, duration, amplifier);
m.extra.hidden_effects.retain(|h| *h != name);
if !particles {
m.extra.hidden_effects.push(name);
}
true
}
None => false,
@@ -154,6 +159,10 @@ impl Game<'_> {
m.extra
.effects
.retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id)));
let left = &m.extra.effects;
m.extra
.hidden_effects
.retain(|h| left.iter().any(|x| x.0 == *h));
m.extra.effects.len() != before
}
None => false,
@@ -145,9 +145,42 @@ impl Game<'_> {
.iter()
.find(|m| m.id == id)
.map_or(0.0, |m| m.eye_y() - m.position.y),
_ => 0.0,
// ArmorStand.getDefaultDimensions: a marker's are empty, a small
// stand's are BABY_DIMENSIONS, whose eye height is 0.9875F.
Target::Stand(id) => match self.armor_stands.iter().find(|a| a.id == id) {
Some(a) if a.marker => 0.0,
Some(a) if a.small => f64::from(0.9875f32),
_ => self.type_eye_height(&self.target_type(t)),
},
// Entity.getEyeHeight: the type's dimensions.
_ => self.type_eye_height(&self.target_type(t)),
}
}
/// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`,
/// read once: a float, widened as `Entity.getEyeY` does.
fn type_eye_height(&self, ty: &str) -> f64 {
static EYE_HEIGHTS: std::sync::OnceLock<std::collections::HashMap<String, f64>> =
std::sync::OnceLock::new();
EYE_HEIGHTS
.get_or_init(|| {
std::fs::read(self.options.resources.join("entity-types.json"))
.ok()
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
.and_then(|v| {
v.as_object().map(|o| {
o.iter()
.filter_map(|(k, t)| {
Some((k.clone(), f64::from(t["eye_height"].as_f64()? as f32)))
})
.collect()
})
})
.unwrap_or_default()
})
.get(ty)
.copied()
.unwrap_or(0.0)
}
/// EntityAnchorArgument.Anchor.apply.
pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] {
match s.entity {
@@ -467,9 +500,10 @@ impl Game<'_> {
"positioned" if c.has("as") => targets(self)?
.into_iter()
.filter_map(|t| {
// withPosition keeps the anchor (only `positioned <pos>`
// resets it to the feet).
Some(Source {
pos: self.target_position(t)?,
eyes: false,
..s
})
})
@@ -606,6 +640,72 @@ impl Game<'_> {
.collect(),
_ => Vec::new(),
},
// Leashable.getLeashHolder: a fence knot is not an entity here.
Some("leasher") => match entity {
Target::Mob(id) => self
.mobs
.iter()
.find(|m| m.id == id)
.and_then(|m| m.extra.leash.map(|holder| (holder, m.extra.leash_player)))
.and_then(|(holder, player)| match holder {
// The player who tied it (the host's when unrecorded).
horizon_client::mobs::leash::Holder::Player => {
let uuid = player.or(self.level.player_uuid)?;
self.target_by_uuid(horizon_client::lan::playerdata::ints_uuid(uuid))
}
horizon_client::mobs::leash::Holder::Mob(i) => Some(Target::Mob(i)),
horizon_client::mobs::leash::Holder::Knot(_) => None,
})
.into_iter()
.collect(),
_ => Vec::new(),
},
// TraceableEntity.getOwner: who shot a projectile, who threw an
// item, who summoned a vex.
Some("origin") => match entity {
Target::Projectile(i) => self
.creatures
.projectiles
.get(i)
.and_then(|p| match (p.owner?, p.guest) {
// A guest's shot: `Who::Player` is them.
(horizon_client::mobs::Who::Player, Some(conn))
if self.lan_acting == Some(conn) =>
{
Some(Target::Player)
}
(horizon_client::mobs::Who::Player, Some(conn)) => {
Some(Target::Guest(conn))
}
(horizon_client::mobs::Who::Player, None) => Some(Target::Player),
(horizon_client::mobs::Who::Mob(id), _) => Some(Target::Mob(id)),
})
.into_iter()
.collect(),
Target::Item(id) => self
.dropped
.iter()
.find(|d| d.id == id)
.and_then(|d| d.thrower)
.and_then(|words| {
let uuid = words
.iter()
.fold(0u128, |all, w| all << 32 | u128::from(*w as u32));
self.target_by_uuid(uuid)
})
.into_iter()
.collect(),
Target::Mob(id) => self
.mobs
.iter()
.find(|m| m.id == id && m.kind.id == "minecraft:vex")
.map(|m| m.extra.counter2 as u32)
.filter(|owner| *owner != 0)
.map(Target::Mob)
.into_iter()
.collect(),
_ => Vec::new(),
},
Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(),
Some("controller") | Some("passengers") => match entity {
Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => {
@@ -244,7 +244,11 @@ impl Game<'_> {
/// hand them the next jobs as soon as each one is done, rather than once
/// a tick.
pub(in crate::game) fn pump_pregen(&mut self, until: Instant) {
while self.pregen_runs_here() {
// Force-loaded chunks too: decorating in vanilla's order, a chunk
// waits for its neighbours far more often than once a tick allows.
while self.pregen_runs_here()
|| (!self.streaming.forced.is_empty() && self.streaming.busy())
{
let now = Instant::now();
if now >= until {
break;
@@ -120,6 +120,9 @@ impl Game<'_> {
tracker.track(&holder(chunk_text(x, z)), i32::from(changed));
}
}
if add {
self.streaming.rank_forced(cx0, cz0, cx1, cz1);
}
let (lo, hi) = (chunk_text(cx0, cz0), chunk_text(cx1, cz1));
let verb = if add { "added" } else { "removed" };
let (message, total) = tracker.message(
@@ -14,10 +14,11 @@ impl Game<'_> {
serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?;
// NbtContents.resolve: the path's values in the entity, block or
// storage data, rich-styled (or plain, or interpreted), ", "-joined.
// ScoreContents.resolve: the holder's score in the objective.
let nbt_values = std::cell::RefCell::new(Vec::new());
{
let mut collect = |o: &serde_json::Map<String, serde_json::Value>| {
if o.contains_key("nbt") {
if o.contains_key("nbt") || o.contains_key("score") {
nbt_values.borrow_mut().push(o.clone());
}
};
@@ -40,7 +41,11 @@ impl Game<'_> {
}
let mut resolved: Vec<(serde_json::Map<String, serde_json::Value>, Text)> = Vec::new();
for o in nbt_values.into_inner() {
let t = self.resolve_nbt_component(&o);
let t = if o.contains_key("score") {
self.resolve_score_component(&o)?
} else {
self.resolve_nbt_component(&o)
};
resolved.push((o, t));
}
let mut resolve = |raw: &str| -> Text {
@@ -73,6 +78,54 @@ impl Game<'_> {
},
))
}
/// The text of a `score` component (ScoreContents.resolve): the named
/// holder's score, `*` being the player the command runs for.
fn resolve_score_component(
&mut self,
o: &serde_json::Map<String, serde_json::Value>,
) -> R<Text> {
let score = o.get("score");
let field = |k: &str| score.and_then(|s| s.get(k)).and_then(|v| v.as_str());
let (name, objective) = (
field("name").unwrap_or(""),
field("objective").unwrap_or(""),
);
// findTargetName: a selector that matches one entity is that entity,
// one that matches none is just the name.
let mut reader = horizon_client::command::Reader::new(name);
let ty = horizon_client::command::args::ArgType::Entity {
single: false,
players: false,
};
let mut holder = name.to_owned();
if let Ok(Arg::Entity(sel)) = ty.parse(&mut reader, &self.ui.registries)
&& !reader.can_read()
{
let found = self.select(&sel);
if found.len() > 1 {
return Err(err("argument.entity.toomany", &[]));
}
if let Some(t) = found.first().and_then(|t| self.holder_name(*t)) {
holder = t;
}
}
if holder == "*" {
holder = self.acting_player_name().to_owned();
}
let board = &self.score.board;
let (Some(objective), Some(score)) =
(board.objective(objective), board.score(&holder, objective))
else {
return Ok(Text::empty());
};
// numberFormatOrDefault(StyledFormat.NO_STYLE).
let format = (score.number_format.clone())
.or_else(|| objective.number_format.clone())
.unwrap_or(horizon_client::scoreboard::NumberFormat::Styled(
serde_json::json!({}),
));
Ok(format.format(score.value))
}
/// The text of an `nbt` component.
fn resolve_nbt_component(&mut self, o: &serde_json::Map<String, serde_json::Value>) -> Text {
use horizon_world::nbt::Tag;
@@ -136,28 +189,40 @@ impl Game<'_> {
}
out
}
fn player_targets(&mut self, ctx: &Context) -> R<usize> {
// Only the local player can receive messages and titles.
/// The players the command reaches: the window's own and the LAN guests.
fn player_targets(&mut self, ctx: &Context) -> R<Vec<Target>> {
let targets = self.entities(ctx, "targets", true)?;
Ok(targets.iter().filter(|t| **t == Target::Player).count())
Ok(targets
.into_iter()
.filter(|t| matches!(t, Target::Player | Target::Guest(_)))
.collect())
}
pub(super) fn cmd_tellraw(&mut self, ctx: &Context) -> R<i32> {
let n = self.player_targets(ctx)?;
let players = self.player_targets(ctx)?;
let message = self.component_arg(ctx, "message")?;
if n > 0 {
self.system_message(message);
// Each player's chat (a guest's through the connection).
for &t in &players {
self.for_player(t, |g| g.system_message(message.clone()));
}
Ok(n as i32)
Ok(players.len() as i32)
}
pub(super) fn cmd_title(&mut self, ctx: &Context) -> R<i32> {
let n = self.player_targets(ctx)?;
let name = self.target_name(Target::Player);
let players = self.player_targets(ctx)?;
let n = players.len();
let name = players
.first()
.map_or_else(Text::empty, |t| self.target_name(*t));
let single = n == 1;
let key = if ctx.has("clear") {
self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false }));
self.titles_or_packet(
&players,
Titles::clear,
C::ClearTitles(play::Bool1 { value: false }),
);
"cleared"
} else if ctx.has("reset") {
self.titles_or_packet(
&players,
|t| {
t.clear();
t.reset_times();
@@ -172,6 +237,7 @@ impl Game<'_> {
};
let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut"));
self.titles_or_packet(
&players,
|t| t.set_times(fade_in, stay, fade_out),
C::SetTitlesAnimation(play::TitlesAnimation {
fade_in,
@@ -186,13 +252,17 @@ impl Game<'_> {
text: component_nbt(&text.component()),
};
if ctx.has("subtitle") {
self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent));
self.titles_or_packet(&players, |t| t.set_subtitle(text), C::SetSubtitleText(sent));
"show.subtitle"
} else if ctx.has("actionbar") {
self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent));
self.titles_or_packet(
&players,
|t| t.set_overlay(text, false),
C::SetActionBarText(sent),
);
"show.actionbar"
} else {
self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent));
self.titles_or_packet(&players, |t| t.set_title(text), C::SetTitleText(sent));
"show.title"
}
};
@@ -207,13 +277,27 @@ impl Game<'_> {
self.feedback(message);
Ok(n as i32)
}
/// The player the title is for: the guest acting now is sent the packet
/// (TitleCommand's `connection.send`), the window's own player shows it.
fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) {
if self.lan_acting.is_some() {
self.guest_packets.push(packet);
} else {
local(&mut self.titles);
/// TitleCommand's `connection.send` for each player: a guest is sent the
/// packet, the window's own player shows it.
fn titles_or_packet(&mut self, players: &[Target], local: impl FnOnce(&mut Titles), packet: C) {
let mut local = Some(local);
for &t in players {
match t {
Target::Player if self.lan_acting.is_some() => {
self.guest_packets.push(packet.clone());
}
Target::Player => {
if let Some(local) = local.take() {
local(&mut self.titles);
}
}
Target::Guest(conn) => {
if let Some(host) = self.lan.as_ref() {
host.hub.send_to(conn, &packet);
}
}
_ => {}
}
}
}
}
@@ -141,27 +141,37 @@ impl Game<'_> {
Some(Arg::Entity(_)) => self.entities(ctx, "entity", false)?.first().copied(),
_ => None,
};
let cause = match ctx.get("cause") {
Some(Arg::Entity(_)) => self.entities(ctx, "cause", false)?.first().copied(),
_ => None,
};
let from = match ctx.get("location") {
Some(Arg::Coords(_)) => self.position_arg(ctx, "location"),
_ => by.and_then(|t| self.target_position(t)),
};
let hurt = match target {
// The causing mob is the one the hit is credited to and thorns
// answer; the source position gives the knockback its direction.
Target::Player => {
if self.creative || self.spectator() {
// `DamageSource(type, cause, by)`: the death message names the
// causing entity, else the direct one. A mob is noted by
// `hurt_player_from`, a player here.
if let Some(t @ (Target::Player | Target::Guest(_))) = cause.or(by) {
let name = self.target_name(t);
self.note_direct_entity(&ty, name);
}
if self.spectator() {
false
} else if let Some(player) = self.player.as_mut() {
match self.motion.health.damage.id(&ty) {
Some(id) => player
.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false),
None => false,
}
} else {
false
let attacker = match cause.or(by) {
Some(Target::Mob(i)) => Some(Some(i)),
_ => Some(None),
};
self.hurt_player_from(amount, from, &ty, attacker)
}
}
Target::Mob(id) => {
let attacker = by.and_then(|t| match t {
let attacker = cause.or(by).and_then(|t| match t {
Target::Player => Some(Who::Player),
Target::Mob(i) => Some(Who::Mob(i)),
_ => None,
@@ -302,9 +312,18 @@ impl Game<'_> {
float("minVolume", 0.0),
);
let range = if volume > 1.0 { 16.0 * volume } else { 16.0 };
// PlaySoundCommand: one seed for every player.
let seed = self.world.random.next_long();
let here = self.dim.id();
let mut tracker = Tracker::default();
for t in targets {
if t != Target::Player {
if !matches!(t, Target::Player | Target::Guest(_)) {
continue;
}
// Only players in the source's level hear it.
if let Target::Guest(conn) = t
&& self.command_guest(conn).is_none_or(|g| g.dimension != here)
{
continue;
}
let Some(p) = self.target_position(t) else {
@@ -328,8 +347,26 @@ impl Game<'_> {
} else {
(pos, volume)
};
self.audio.play_on(source, &sound, Some(at), v, pitch);
tracker.mark(&holder(Text::literal(self.acting_player_name())));
// The connection is sent the sound; the window's own player
// plays it.
let guest = match t {
Target::Guest(conn) => Some(conn),
_ => self.lan_acting,
};
match guest.and_then(|conn| Some((conn, self.lan.as_ref()?))) {
Some((conn, host)) => {
let packet = host
.hub
.sound_packet(&sound, at, v, pitch, source as i32, seed);
if t == Target::Player {
self.guest_packets.push(packet);
} else {
host.hub.send_to(conn, &packet);
}
}
None => self.audio.play_on(source, &sound, Some(at), v, pitch),
}
tracker.mark(&holder(self.target_name(t)));
}
let name = Text::literal(sound.clone());
let (message, total) = tracker.message(
@@ -606,8 +643,10 @@ impl Game<'_> {
let reached = reached.len() as i32;
if !local {
} else if count <= 0 {
// No count: one particle with the delta as velocity.
self.particles.create(&options, pos, delta);
// handleParticleEvent, count 0: one particle, the speed times
// the delta as velocity (both sent as floats, multiplied as floats).
self.particles
.create(&options, pos, delta.map(|d| f64::from(speed * d as f32)));
} else {
for _ in 0..count {
let r = self.particles.random();
+10
View File
@@ -19,7 +19,17 @@ use std::convert::Infallible;
type ItemConsumable = Consumable<String, ConsumeEffect>;
/// `EntityEvent.USE_ITEM_COMPLETE`: the server finished the player's use.
pub(super) const USE_ITEM_COMPLETE_EVENT: i8 = 9;
impl Game<'_> {
/// `ServerPlayer.completeUsingItem`: the player's own client is told
/// first, and completes the use itself (eating the food there too).
pub(super) fn send_use_item_complete(&mut self) {
if self.lan_acting.is_some() {
self.guest_entity_events.push(USE_ITEM_COMPLETE_EVENT);
}
}
/// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`.
pub(super) fn emit_consume(
&mut self,
@@ -1083,6 +1083,9 @@ impl Game<'_> {
"flashes": self.lightning_seen[1], "flash": self.flash});
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
status["projectiles"] = json!(self.projectiles_status());
let mut fangs_vertices = Vec::new();
self.fangs_geometry(glam::DVec3::ZERO, 0.5, &mut fangs_vertices);
status["fangs_vertices"] = json!(fangs_vertices.len());
status["maps"] = json!(self.maps_status());
// The particles made so far, by type.
status["particles"] = json!(self.particles.made());
+4 -3
View File
@@ -218,8 +218,9 @@ impl Game<'_> {
);
}
/// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to
/// death and a natural heart drops experience.
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
/// death and a natural heart drops experience. `onExplosionHit` does the
/// same for the creaking (`by_player` false), without the experience.
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3], by_player: bool) {
let key = (pos[0], pos[1], pos[2]);
if !matches!(
self.world.block_entities.get(&key),
@@ -242,7 +243,7 @@ impl Game<'_> {
.state(state)
.and_then(|s| s.properties.get("natural").cloned())
.is_some_and(|v| v == "true");
if natural && !self.creative && !self.spectator() {
if by_player && natural && !self.creative && !self.spectator() {
let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32;
self.spawn_orbs(
[
+203 -32
View File
@@ -18,6 +18,7 @@ use horizon_client::{
spawning::{self, BiomeFacts},
},
projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld},
text::Text,
};
use horizon_core::{
geometry::{Aabb, Vec3, traverse_blocks},
@@ -430,6 +431,12 @@ impl Game<'_> {
),
}
}
/// What the generator finalizes this level's structure mobs with.
pub(super) fn share_spawn_conditions(&self) {
if let Some(terrain) = self.end.locator() {
terrain.set_spawn_conditions(self.difficulty_id() as u8, self.world.day_time);
}
}
/// `ServerLevel.getCurrentDifficultyAt`.
pub(super) fn local_difficulty(&self, at: [f64; 3]) -> spawning::LocalDifficulty {
use horizon_world::food::Difficulty;
@@ -526,6 +533,8 @@ impl Game<'_> {
_ => Vec::new(),
};
let mut guest_events = Vec::new();
// The mobs whose bodies go this tick: (id, feet, width, height).
let mut gone = Vec::new();
let level_random;
{
// The level random, lent to the mobs (brain behaviours draw from
@@ -598,6 +607,11 @@ impl Game<'_> {
let from = events.len();
let kept = m.tick(&w, &mut scratch, &mut events);
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
// LivingEntity.tickDeath: after twenty ticks the body is removed.
if !kept && !m.removed && !m.alive() && m.death_time >= 20 {
let (width, height) = (f64::from(m.width()), f64::from(m.height()));
gone.push((m.id, m.position, width, height));
}
if let Some(conn) = seen_guest {
// ShulkerBullet.finalTarget is the guest's entity: the
// bullet homes on it while the projectiles tick, where
@@ -656,6 +670,12 @@ impl Game<'_> {
}
self.mobs.append(&mut mobs);
self.died = died;
// ... and entity event 60 goes out as it is: the poof.
for (id, at, width, height) in gone {
let at = [at.x, at.y, at.z];
self.lan_entity_event(id as i32, 60, at);
self.death_poof(at, width, height);
}
self.sync_riders();
self.tick_skeleton_traps();
self.tick_apparition();
@@ -682,6 +702,22 @@ impl Game<'_> {
self.handle_mob_events(queued)?;
Ok(())
}
/// `LivingEntity.makePoofParticles` (entity event 60) about a mob's box.
pub(super) fn death_poof(&mut self, at: [f64; 3], width: f64, height: f64) {
let options = horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::Poof,
);
for _ in 0..20 {
let r = self.particles.level_random();
let xa = r.next_gaussian() * 0.02;
let ya = r.next_gaussian() * 0.02;
let za = r.next_gaussian() * 0.02;
let x = at[0] + width * (2.0 * r.next_double() - 1.0) - xa * 10.0;
let y = at[1] + height * r.next_double() - ya * 10.0;
let z = at[2] + width * (2.0 * r.next_double() - 1.0) - za * 10.0;
self.particles.add(&options, [x, y, z], [xa, ya, za]);
}
}
/// LivingEntity.die / dropAllDeathLoot.
fn mob_died(&mut self, m: &Mob) {
let killer = self.last_hurt_by_player.remove(&m.id);
@@ -1078,6 +1114,11 @@ impl Game<'_> {
self.next_entity += 1;
p.id = self.next_entity;
let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]);
// LlamaSpit.recreateFromPacket: the spit's burst on the client.
if p.kind == ProjectileKind::LlamaSpit {
let v = p.velocity;
self.particles.llama_spit_burst(at, [v.x, v.y, v.z]);
}
self.creatures.projectiles.push(p);
self.projectile_event("minecraft:projectile_shoot", owner, at);
}
@@ -1640,11 +1681,34 @@ impl Game<'_> {
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
self.mob_hits_player(amount, from, kind);
}
/// Damage whose causing mob is known (`cause`, or none): not guessed
/// from the mob nearest to `from`.
pub(super) fn mob_hits_player_caused(
&mut self,
amount: f32,
from: [f64; 3],
kind: &str,
cause: Option<u32>,
) {
self.hurt_player_from(amount, Some(from), kind, Some(cause));
}
pub(super) fn mob_hits_player(
&mut self,
amount: f32,
from: [f64; 3],
damage_type: &str,
) -> bool {
self.hurt_player_from(amount, Some(from), damage_type, None)
}
/// `hurtServer` on the player. `from` is the source's position (none: no
/// direction), `known`: the causing mob when it is given (`/damage`),
/// else the melee attacker is the mob nearest to `from`.
pub(super) fn hurt_player_from(
&mut self,
amount: f32,
from: Option<[f64; 3]>,
damage_type: &str,
known: Option<Option<u32>>,
) -> bool {
// ServerPlayer.canHarmPlayer refused another player's projectile.
if self.creative || self.combat.refuse_player_hit {
@@ -1657,23 +1721,26 @@ impl Game<'_> {
.damage_tags
.get("minecraft:is_projectile")
.is_some_and(|t| t.contains(damage_type));
let blocking = self.player_blocking(Some(from), damage_type, false);
let blocking = self.player_blocking(from, damage_type, false);
let raised = blocking.is_some();
// Melee: the attacker stands at `from` (another player's hit has no mob behind it).
let attacker = (!projectile && damage_type != "minecraft:player_attack")
.then(|| {
self.mobs
.iter()
.filter(|m| m.alive())
.min_by(|a, b| {
let d = |m: &horizon_client::mobs::Mob| {
(m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2)
};
d(a).total_cmp(&d(b))
})
.map(|m| m.id)
})
.flatten();
let attacker = match known {
Some(known) => known,
None => from
.filter(|_| !projectile && damage_type != "minecraft:player_attack")
.and_then(|from| {
self.mobs
.iter()
.filter(|m| m.alive())
.min_by(|a, b| {
let d = |m: &horizon_client::mobs::Mob| {
(m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2)
};
d(a).total_cmp(&d(b))
})
.map(|m| m.id)
}),
};
// The causing entity for the death message.
let owner = self.combat.projectile_owner.take();
if let Some(a) = attacker.or(owner) {
@@ -1701,7 +1768,10 @@ impl Game<'_> {
// LivingEntity.hurtServer's dealDefaultKnockback: not inside the
// hurt cooldown (a stronger hit there only adds its difference).
if o.knockback {
let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z);
// No source position: a random direction.
let (xd, zd) = from.map_or((0.0, 0.0), |from| {
(from[0] - player.position.x, from[2] - player.position.z)
});
self.knock_back_player(f64::from(0.4_f32), xd, zd);
if let Some(p) = self.player.as_mut()
&& let Some(r) = p.hurt_log.last_mut()
@@ -2039,6 +2109,33 @@ impl Game<'_> {
None => self.projectile_hit(p, hit),
}
}
/// What an arrow or a thrown trident hits an entity of type `victim`
/// for (`AbstractArrow.onHitEntity`, `ThrownTrident.onHitEntity`): a
/// trident's 8 through `EnchantmentHelper.modifyDamage` of the trident
/// (Impaling's `minecraft:damage` on `#sensitive_to_impaling`).
fn shot_damage(&mut self, shot: &mut Projectile, victim: Option<&str>) -> f32 {
if !matches!(shot.kind, ProjectileKind::Trident) {
return arrow_damage(shot, &mut self.world.random) + shot.bonus.damage;
}
let Some(trident) = shot.arrow.as_ref().map(|a| a.pickup_item.clone()) else {
return 8.0;
};
let ctx = horizon_client::enchant::EffectContext {
this: victim,
attacker: (shot.owner == Some(Who::Player)).then_some("minecraft:player"),
direct_attacker: Some("minecraft:trident"),
damage_type: Some("minecraft:trident"),
items: Some(self.res.items()),
..Default::default()
};
self.res.stations().enchantments.modify_value(
Some(&trident),
"minecraft:damage",
&ctx,
&mut self.world.random,
8.0,
)
}
/// What an arrow's tick asked for: its particles and sounds.
fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) {
use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction};
@@ -2067,6 +2164,8 @@ impl Game<'_> {
ArrowSound::Splash => "minecraft:entity.generic.splash",
ArrowSound::HitGround => "minecraft:entity.arrow.hit",
ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire",
ArrowSound::TridentHitGround => "minecraft:item.trident.hit_ground",
ArrowSound::TridentHit => "minecraft:item.trident.hit",
};
self.audio
.play(name, Some([at.x, at.y, at.z]), volume, pitch);
@@ -2216,11 +2315,11 @@ impl Game<'_> {
&& id >= super::dragon::SPECIAL
{
let by_player = p.owner == Some(Who::Player);
if let ProjectileKind::Arrow { .. } = p.kind {
if p.arrow.is_some() {
// AbstractArrow.onHitEntity: spent if the part or crystal took
// it, else turned back (a perched dragon sets it alight first).
let mut arrow = p.clone();
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
let amount = self.shot_damage(&mut arrow, None);
let outcome = match self.hit_special(id, amount, by_player, true) {
super::dragon::Hurt::Landed { .. } => EntityHit::Hurt,
super::dragon::Hurt::Refused => EntityHit::Refused,
@@ -2241,17 +2340,15 @@ impl Game<'_> {
self.hit_special(id, amount, by_player, false);
return Ok(());
}
if let (
ProjectileKind::Arrow { .. },
Hit::Entity {
if p.arrow.is_some()
&& let Hit::Entity {
who: Who::Mob(id), ..
},
) = (&p.kind, hit)
} = hit
&& let Some(i) = self.carts.iter().position(|c| c.id == id)
{
// AbstractArrow.onHitEntity on a minecart.
let mut arrow = p.clone();
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
let amount = self.shot_damage(&mut arrow, None);
let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire());
let creative = p.owner == Some(Who::Player) && self.creative;
self.arrow_hits_cart(i, amount, p.velocity, burning, creative);
@@ -2262,7 +2359,7 @@ impl Game<'_> {
// Projectile.onHit: the landing is heard.
self.projectile_event("minecraft:projectile_land", p.owner, atp);
let source_kind = match p.kind {
ProjectileKind::Arrow { .. } => DamageKind::Arrow,
ProjectileKind::Arrow { .. } | ProjectileKind::Trident => DamageKind::Arrow,
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => {
DamageKind::Fireball
}
@@ -2274,6 +2371,40 @@ impl Game<'_> {
from: Some([p.previous.x, p.previous.y, p.previous.z]),
};
match (&p.kind, hit) {
// ThrownTrident.onHitEntity: 8 damage (Impaling on aquatic mobs),
// dealt whether or not the hurt lands, then it bounces off.
(ProjectileKind::Trident, Hit::Entity { who, .. }) => {
let mut trident = p.clone();
let victim = match who {
Who::Mob(id) => self
.mobs
.iter()
.find(|m| m.id == id)
.map(|m| m.kind.id.clone()),
Who::Player => Some("minecraft:player".to_owned()),
};
let amount = self.shot_damage(&mut trident, victim.as_deref());
let hurt = match who {
Who::Player => self.mob_hits_player(
amount,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:trident",
),
Who::Mob(id) => self
.mobs
.iter_mut()
.find(|m| m.id == id)
.is_some_and(|m| m.damage(amount, source)),
};
let outcome = if hurt {
EntityHit::Hurt
} else {
EntityHit::Refused
};
self.finish_arrow_hit(trident, outcome);
}
// AbstractArrow.onHitBlock plays its sound itself (ArrowEvent).
(ProjectileKind::Trident, Hit::Block { .. }) => {}
(ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => {
let mut arrow = p.clone();
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
@@ -2495,14 +2626,30 @@ impl Game<'_> {
if d2 < 16.0 && !self.creative {
let scale = 1.0 - d2.sqrt() / 4.0;
let t = (f64::from(*ticks) * scale + 0.5) as i32;
if let Some(owner) = self.combat.projectile_owner {
self.note_attacker("minecraft:indirect_magic", owner);
}
match *effect {
"minecraft:instant_damage" => self.hurt_player_by(
"minecraft:indirect_magic",
6.0 * (1 << *amplifier) as f32 * scale as f32,
),
"minecraft:instant_damage" => {
// indirectMagic(potion, owner), built where the
// hurt happens: the thrower, or the potion
// itself when it has none. A status effect
// deals no damage, so it records no source.
let owner = self
.combat
.projectile_owner
.filter(|id| self.mob_display_name(*id).is_some());
match owner {
Some(owner) => {
self.note_attacker("minecraft:indirect_magic", owner)
}
None => self.note_direct_entity(
"minecraft:indirect_magic",
Text::translate("entity.minecraft.splash_potion", &[]),
),
}
self.hurt_player_by(
"minecraft:indirect_magic",
6.0 * (1 << *amplifier) as f32 * scale as f32,
)
}
e if t > 20 => self.give_player_effect(e, t, *amplifier),
_ => {}
}
@@ -3411,6 +3558,30 @@ impl Game<'_> {
}
continue;
}
// ThrownTridentRenderer.
if matches!(a.kind, ProjectileKind::Trident) {
let Some(model) = self.trident_model.as_ref() else {
continue;
};
let Some(r) = atlas.sprites.get("entity/trident/trident").copied() else {
continue;
};
let m = glam::Mat4::from_translation(c)
* glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians())
* glam::Mat4::from_rotation_z((a.pitch + 90.0).to_radians());
let poses = horizon_client::mobs::anim::Poses::new(model);
horizon_client::mobs::render::draw(
model,
m,
&poses,
[r.u0, r.v0, r.u1, r.v1],
0xFFFF_FFFF,
packed,
0,
out,
);
continue;
}
// WindChargeRenderer.
if matches!(
a.kind,
@@ -654,6 +654,9 @@ impl Game<'_> {
// DedicatedServer.initServer ends with saveEverything(false, true, true).
self.save_game()?;
self.log_saved_levels();
if let Some(host) = self.lan.as_mut() {
host.hub.entity_range_percent = props.entity_broadcast_range_percentage;
}
let mut state = ServerState {
lists,
console,
+1 -1
View File
@@ -982,7 +982,7 @@ impl Game<'_> {
| "minecraft:lingering_potion" => {
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
shot.shoot(&mut own, dir, power, uncertainty);
self.launch_thrown(one, at, shot.velocity);
self.launch_thrown(one, at, shot.velocity, None);
}
"minecraft:firework_rocket" => {
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
+7 -2
View File
@@ -2157,11 +2157,14 @@ impl Game<'_> {
}
/// Damage from the dragon, which is its causing entity
/// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the
/// death message names it.
/// death message names it, or the cloud once the dragon is gone.
fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) {
if let Some(id) = self.dragon.as_ref().map(|d| d.id) {
let name = Text::translate("entity.minecraft.ender_dragon", &[]);
self.note_named_attacker(damage_type, id, name);
} else if damage_type == "minecraft:indirect_magic" {
let name = Text::translate("entity.minecraft.area_effect_cloud", &[]);
self.note_direct_entity(damage_type, name);
}
self.hurt_player_by(damage_type, amount);
}
@@ -2598,7 +2601,9 @@ impl Game<'_> {
}
pub(super) fn fight_ready(&mut self) -> bool {
self.load_fight();
self.fight.loaded
// spawnExitPortal runs from scanState and the dragon's death, both
// only with players in the fight.
self.fight.loaded && self.fight.players
}
pub(super) fn exit_portal(&self) -> Option<[i32; 3]> {
self.fight.exit_portal
+14 -9
View File
@@ -572,16 +572,16 @@ impl Game<'_> {
let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7;
self.audio
.play("minecraft:entity.generic.explode", Some(center), 4.0, pitch);
let block_count = if interaction == BlockInteraction::Keep {
0
} else {
targets.len()
};
// ServerLevel.explode sends toBlow.size() whatever the interaction, and
// `ServerExplosion.isSmall` also covers an explosion that keeps blocks.
let block_count = targets.len();
let small = radius < 2.0 || interaction == BlockInteraction::Keep;
let (world, facts) = (&self.world, self.res.facts());
self.particles.explosion(center, radius, block_count, &|b| {
facts.is_air(world.block(b[0], b[1], b[2]))
});
self.lan_explode(center, radius, block_count);
self.particles
.explosion(center, small, block_count, radius, &|b| {
facts.is_air(world.block(b[0], b[1], b[2]))
});
self.lan_explode(center, small, radius, block_count);
Ok(())
}
/// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse).
@@ -598,6 +598,11 @@ impl Game<'_> {
}
let name = self.res.facts().get(state).name.clone();
let is_tnt = &*name == "minecraft:tnt";
// CreakingHeartBlock.onExplosionHit: its creaking dies (no
// experience, as Horizon does not track a TNT's owner).
if &*name == "minecraft:creaking_heart" {
self.creaking_heart_broken(pos, false);
}
// Block.onExplosionHit: the drops copy from the block entity, which
// then spills its contents as the block turns to air.
let key = (pos[0], pos[1], pos[2]);
@@ -64,6 +64,25 @@ impl Game<'_> {
pos: BlockPos::new(pos[0], pos[1], pos[2]),
data: 0,
});
} else if self
.res
.facts()
.get(block.state)
.name
.starts_with("minecraft:suspicious_")
{
// BrushableBlock.onBrokenAfterFall.
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.level_events.push(LevelEvent::LevelEvent {
id: 2001,
pos: at,
data: block.state.0 as i32,
});
self.level_events.push(LevelEvent::GameEvent {
pos: at,
event: "minecraft:block_destroy",
state: None,
});
}
return;
}
+49 -6
View File
@@ -7,12 +7,13 @@ use std::sync::Arc;
#[derive(Clone, Debug)]
pub(super) struct Fangs {
pos: [f64; 3],
yaw: f32,
pub id: u32,
pub pos: [f64; 3],
pub yaw: f32,
warmup: i32,
life: i32,
pub life: i32,
owner: u32,
started: bool,
pub started: bool,
}
#[derive(Default)]
pub(super) struct FangState {
@@ -21,6 +22,11 @@ pub(super) struct FangState {
}
impl Game<'_> {
pub(super) fn add_fangs(&mut self, at: [f64; 3], yaw: f32, delay: i32, owner: u32) {
self.next_entity += 1;
self.insert_fangs(self.next_entity, at, yaw, delay, owner);
}
pub(super) fn insert_fangs(&mut self, id: u32, at: [f64; 3], yaw: f32, delay: i32, owner: u32) {
if self.fangs.model.is_none() {
self.fangs.model = horizon_client::mobs::load_model(
&self.options.resources,
@@ -29,6 +35,7 @@ impl Game<'_> {
.map(Arc::new);
}
self.fangs.list.push(Fangs {
id,
pos: at,
yaw,
warmup: delay,
@@ -37,6 +44,30 @@ impl Game<'_> {
started: false,
});
}
/// `EvokerFangs.handleEntityEvent`: only event 4 starts a client attack.
pub(super) fn remote_fangs_event(&mut self, id: u32, event: i8) {
if event == 4
&& let Some(f) = self.fangs.list.iter_mut().find(|f| f.id == id)
{
f.started = true;
self.audio.play_unshared(
"minecraft:entity.evoker_fangs.attack",
Some(f.pos),
1.0,
1.0,
);
}
}
/// `EvokerFangs.tick`: clients only advance animation, never damage or discard.
pub(super) fn tick_remote_fangs(&mut self) {
for f in &mut self.fangs.list {
if f.started {
f.life -= 1;
}
}
}
/// `EvokerFangs.tick`.
pub(super) fn tick_fangs(&mut self) {
let mut list = std::mem::take(&mut self.fangs.list);
@@ -50,7 +81,8 @@ impl Game<'_> {
}
if !f.started {
f.started = true;
self.audio.play(
self.lan_entity_event(f.id as i32, 4, f.pos);
self.audio.play_unshared(
"minecraft:entity.evoker_fangs.attack",
Some(f.pos),
1.0,
@@ -71,12 +103,23 @@ impl Game<'_> {
let b = horizon_core::geometry::Aabb::new(lo, hi);
// Every player in the box, the server's players too.
let pos = f.pos;
// `EvokerFangs.dealDamageTo`: indirectMagic(fangs, owner) while the
// owner lives, plain magic (nobody to name) once it is gone.
let owner = self
.mobs
.iter()
.any(|m| m.id == f.owner && m.alive())
.then_some(f.owner);
let bite = move |g: &mut Self| {
if let Some(p) = g.player_view()
&& p.alive
&& p.bounds.intersects(b)
{
g.mob_hits_player_kind(6.0, pos, "minecraft:indirect_magic");
let kind = match owner {
Some(_) => "minecraft:indirect_magic",
None => "minecraft:magic",
};
g.mob_hits_player_caused(6.0, pos, kind, owner);
}
};
bite(self);
@@ -20,7 +20,8 @@ use horizon_core::{
};
use horizon_world::{
block_collision::BlockCollisionRegistry, collision_context::CollisionContext,
heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates,
heightmap::HeightmapType, level::flags::UPDATE_CLIENTS, registry::BlockStateId,
worldgen::terrain::TerrainBlockStates,
};
/// The loaded world as the spawn searches query it.
@@ -121,6 +122,96 @@ impl Game<'_> {
}
Ok(Some([ox * 16 + 8, height, oz * 16 + 8]))
}
/// MinecraftServer.setInitialSpawn's bonus chest: BonusChestFeature.place
/// in the spawn chunk, a chest with the spawn bonus loot and a torch on
/// each side that can hold one, on the first free column of a shuffled
/// walk over the chunk. Skipped while the chunk is not loaded.
pub(super) fn place_bonus_chest(&mut self, origin: [i32; 3]) -> Result<()> {
use horizon_client::containers::BlockEntity;
let (cx, cz) = (origin[0] >> 4, origin[2] >> 4);
let registry = &self.pack.assets.registry;
let (Some(chest), Some(torch)) = (
registry.default_state("minecraft:chest"),
registry.default_state("minecraft:torch"),
) else {
return Ok(());
};
if !self.streaming.is_lit(cx, cz) {
return Ok(());
}
// `level.getRandom()`. Util.toShuffledList of the chunk's x and z.
let random = &mut self.world.random;
let mut shuffled = |min: i32| -> [i32; 16] {
let mut values: [i32; 16] = std::array::from_fn(|i| min + i as i32);
for end in (2..=16usize).rev() {
let other = random.next_int_bound(end as i32).unwrap_or(0) as usize;
values.swap(end - 1, other);
}
values
};
let (xs, zs) = (shuffled(cx * 16), shuffled(cz * 16));
for x in xs {
for z in zs {
let y = self
.spawn_columns()
.height(HeightmapType::MotionBlockingNoLeaves, x, z);
if self.world.block(x, y, z) != self.world.air && !self.collision_empty([x, y, z]) {
continue;
}
self.set_block_clients([x, y, z], chest)?;
let seed = self.world.random.next_long();
self.world
.block_entities
.insert((x, y, z), BlockEntity::Chest(Vec::new()));
self.load_block_entity_nbt(
[x, y, z],
&format!(
"{{LootTable:\"minecraft:chests/spawn_bonus_chest\",LootTableSeed:{seed}L}}"
),
);
for [dx, dz] in [[0, -1], [1, 0], [0, 1], [-1, 0]] {
let at = [x + dx, y, z + dz];
let survives = self.with_level(|b, level, ticks| {
b.can_survive(level, ticks, BlockPos::new(at[0], at[1], at[2]), torch)
});
if survives {
self.set_block_clients(at, torch)?;
}
}
return Ok(());
}
}
Ok(())
}
/// `Level.setBlock(pos, state, UPDATE_CLIENTS)`: no neighbour updates.
fn set_block_clients(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> {
self.with_level(|b, level, ticks| {
b.set_block(
level,
ticks,
BlockPos::new(pos[0], pos[1], pos[2]),
state,
UPDATE_CLIENTS,
);
});
self.process_level_events()
}
/// The block at `pos` has no collision shape.
fn collision_empty(&self, pos: [i32; 3]) -> bool {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
self.collision
.collision_shape_with_context(
&mut scene,
self.world.block(pos[0], pos[1], pos[2]),
BlockPos::new(pos[0], pos[1], pos[2]),
&CollisionContext::empty(false),
)
.is_ok_and(|shape| shape.is_empty())
}
/// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a
/// player who has no position yet. None while a candidate's chunk loads.
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
@@ -52,6 +52,8 @@ struct Flags {
/// server follows while it runs (IntegratedServer.tickServer).
render_distance: AtomicI32,
simulation_distance: AtomicI32,
/// `MinecraftServer.isCurrentlySaving`: the server is autosaving.
saving: AtomicBool,
}
/// Work the window hands its server thread (`MinecraftServer.execute`).
@@ -69,6 +71,10 @@ impl Integrated {
pub fn smoothed_tick_ms(&self) -> f32 {
f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed))
}
/// `MinecraftServer.isCurrentlySaving`.
pub fn is_saving(&self) -> bool {
self.flags.saving.load(Ordering::Relaxed)
}
/// `IntegratedServer.tickServer` skips the world while the game is paused.
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
@@ -148,6 +154,12 @@ pub(super) struct Serving {
/// is out of its place: applied after the tick.
pending: Option<Publish>,
}
impl Serving {
/// The window reads this as `MinecraftServer.isCurrentlySaving`.
pub(super) fn set_saving(&self, saving: bool) {
self.flags.saving.store(saving, Ordering::Relaxed);
}
}
enum Publish {
Open(TcpListener, LanSettings),
Close,
+82 -12
View File
@@ -11,7 +11,7 @@ use horizon_client::{
chunks::ChunkEncoder,
data::SyncData,
entity::{EntityState, States},
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
hub::{BodyFlags, HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
mobs::{Mob, Who, leash::Holder},
@@ -191,6 +191,17 @@ fn mob_meta(
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
defaults.push((9, serializer::FLOAT, Value::Float(1.0)));
// LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: the
// swirls of its effects (the ones a mob has are visible, not ambient).
meta.extend(
hub.effect_meta(
(m.extra.effects.iter())
.filter(|e| !m.extra.hidden_effects.contains(&e.0))
.map(|e| (e.0, false)),
),
);
defaults.push((10, serializer::PARTICLES, Value::Particles(Vec::new())));
defaults.push((11, serializer::BOOLEAN, Value::Bool(false)));
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what
// draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised
// weapon).
@@ -236,6 +247,27 @@ fn mob_meta(
}
defaults.push((16, serializer::BYTE, Value::Byte(0)));
}
// SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on (the default).
"minecraft:snow_golem" => {
if e.sheared {
meta.push((16, serializer::BYTE, Value::Byte(0)));
}
defaults.push((16, serializer::BYTE, Value::Byte(16)));
}
// MushroomCow.DATA_TYPE: 0 red, 1 brown.
"minecraft:mooshroom" => {
if e.variant == 1 {
meta.push((17, serializer::INT, Value::Int(1)));
}
defaults.push((17, serializer::INT, Value::Int(0)));
}
// Piglin.DATA_IS_DANCING (after the baby flag and the crossbow charge).
"minecraft:piglin" => {
if e.scratch[0] > 0 {
meta.push((19, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((19, serializer::BOOLEAN, Value::Bool(false)));
}
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared.
"minecraft:sheep" => {
let value = (e.color & 15) | if e.sheared { 16 } else { 0 };
@@ -350,6 +382,14 @@ fn mob_meta(
}
defaults.push((17, serializer::BOOLEAN, Value::Bool(false)));
}
// PolarBear.DATA_STANDING_ID (after AgeableMob's two): the bear
// rears up; the client animates it.
"minecraft:polar_bear" => {
if e.flag {
meta.push((18, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((18, serializer::BOOLEAN, Value::Bool(false)));
}
// SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose.
"minecraft:evoker" | "minecraft:illusioner" => {
if e.variant2 != 0 {
@@ -845,6 +885,16 @@ impl Game<'_> {
living_flags: living_flags(self.using)
| if p.auto_spin_attack_ticks > 0 { 4 } else { 0 },
bed: self.sleeping,
body: BodyFlags {
gliding: p.fall_flying,
swimming: p.swimming,
crawling: p.pose == horizon_client::pose::Pose::Swimming && !p.swimming,
crouching: p.pose == horizon_client::pose::Pose::Crouching,
spin_attack: p.auto_spin_attack_ticks > 0,
on_fire: p.fire_ticks > 0,
invisible: self.potions.effects.get("invisibility").is_some(),
glowing: self.potions.effects.get("glowing").is_some(),
},
})
}
@@ -962,6 +1012,16 @@ impl Game<'_> {
host.hub.block_event(pos, b0, b1, state);
}
let entities = states.as_slice();
// An entity that left the level since the last tick (a snowball
// that hit) is dropped by the tracker below: its event goes out
// first, as `Level.broadcastEntityEvent` precedes the discard.
let (gone, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.lan_entity_events)
.into_iter()
.partition(|(id, ..)| !entities.iter().any(|e| e.id == *id));
self.lan_entity_events = later;
for (id, event, at) in gone {
host.hub.entity_event(id, event, at);
}
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
let clock_rate = self.network_clock_rate();
@@ -1243,8 +1303,9 @@ impl Game<'_> {
self.lan_entity_events.push((id, event, at));
}
}
/// `ServerPlayer.crit`: this window's emitter, and an animation for the
/// attacker's client and observers once the hub is back in place.
/// `ServerPlayer.crit` (or `magicCrit` when `magic`): this window's
/// emitter, and an animation for the attacker's client and observers once
/// the hub is back in place.
pub(super) fn critical_hit(
&mut self,
attacker: Option<u32>,
@@ -1252,16 +1313,18 @@ impl Game<'_> {
feet: [f64; 3],
width: f64,
height: f64,
magic: bool,
) {
use horizon_client::particles::{ParticleOptions, ParticleType};
self.particles.tracking_emitter(
ParticleOptions::simple(ParticleType::Crit),
feet,
width,
height,
);
let particle = if magic {
ParticleType::EnchantedHit
} else {
ParticleType::Crit
};
self.particles
.tracking_emitter(ParticleOptions::simple(particle), feet, width, height);
if self.audio.capture.is_some() {
self.lan_critical_hits.push((attacker, id));
self.lan_critical_hits.push((attacker, id, magic));
}
}
/// Send the tick's level events, sounds and mob animations.
@@ -1339,13 +1402,13 @@ impl Game<'_> {
seen.insert(m.id, (m.hurt_time, dead, swing));
}
host.mob_state.insert(self.dim, seen);
for (attacker, target) in critical_hits {
for (attacker, target, magic) in critical_hits {
let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| {
host.hub.guest(conn).map(|g| g.entity_id)
}) else {
continue;
};
host.hub.critical_hit(attacker, target);
host.hub.critical_hit(attacker, target, magic);
}
}
@@ -1428,6 +1491,13 @@ impl Game<'_> {
.each_ref()
.map(|s| s.as_ref().map(|s| s.item.clone()));
m.extra.crouching = g.sneaking;
m.extra.sprinting = g.sprinting;
// LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects.
let visible = || g.effects.list.iter().filter(|e| e.visible);
m.extra.effect_particles = visible()
.filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient))
.collect();
m.extra.effect_ambient = visible().all(|e| e.ambient);
// 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.
+69 -14
View File
@@ -165,6 +165,8 @@ pub(super) struct GuestSwap {
acting: (Option<u32>, Option<String>, Option<u128>),
/// The packets queued for that guest.
packets: Vec<play::Clientbound>,
/// The entity events queued for that guest.
entity_events: Vec<i8>,
/// The host's count of swings started, kept while the guest acts.
swings: u32,
/// How many projectiles there were: those added since are the guest's.
@@ -389,6 +391,7 @@ impl Game<'_> {
self.lan_acting_uuid.replace(g.uuid),
);
let packets = std::mem::take(&mut self.guest_packets);
let entity_events = std::mem::take(&mut self.guest_entity_events);
let swings = self.swings_started;
let projectiles = self.creatures.projectiles.len();
let modifiers = std::mem::replace(
@@ -449,6 +452,7 @@ impl Game<'_> {
death_cause,
acting,
packets,
entity_events,
swings,
projectiles,
modifiers,
@@ -508,6 +512,7 @@ impl Game<'_> {
combat,
acting,
packets,
entity_events,
swings,
projectiles,
modifiers,
@@ -529,6 +534,17 @@ impl Game<'_> {
for packet in std::mem::replace(&mut self.guest_packets, packets) {
host.hub.send_to(conn, &packet);
}
// ServerPlayer.connection.send: the guest's own entity events.
let entity_id = host.hub.guests[i].entity_id;
for event in std::mem::replace(&mut self.guest_entity_events, entity_events) {
host.hub.send_to(
conn,
&C::EntityEvent(play::EntityEvent {
id: entity_id,
event,
}),
);
}
// ServerItemCooldowns.onCooldownStarted: the guest's own cooldown.
for (group, duration) in std::mem::take(&mut self.guest_cooldowns) {
host.hub.send_to(
@@ -1216,6 +1232,12 @@ impl Game<'_> {
{
self.guest_carried_back(host, gi);
}
S::SelectBundleItem(p) => {
if !spectator && let Ok(slot) = usize::try_from(p.slot) {
host.hub
.select_bundle_item(conn, slot, p.index, &mut self.world);
}
}
S::ContainerClick(p) => {
let rules = ItemRules(self.res.items());
let slots = host.hub.guests[gi]
@@ -1910,21 +1932,8 @@ impl Game<'_> {
continue;
}
let play = host.play.entry(conn).or_default();
// Player.tick's ItemCooldowns.tick, once a tick for each player
// (the shield an axe disabled, a thrown pearl).
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
// ServerGamePacketListenerImpl.tick's dropSpamThrottler.
play.creative_drops = play.creative_drops.saturating_sub(1);
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
// the guest (a duration of 0 removes it).
for group in play.cooldowns.tick() {
host.hub.send_to(
conn,
&C::Cooldown(play::Cooldown {
group: group.to_string(),
duration: 0,
}),
);
}
let digging = play.digging;
let using = play.using.is_some();
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
@@ -1961,6 +1970,24 @@ impl Game<'_> {
play.digging = None;
}
}
// Player.tick's ItemCooldowns.tick, once a tick for each player
// (the shield an axe disabled, a thrown pearl), after
// LivingEntity.tick's use: an entry a finished use starts has 20
// ticks left when the next tick's packets are handled, as the
// guest's own client counts.
let play = host.play.entry(conn).or_default();
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
// the guest (a duration of 0 removes it).
for group in play.cooldowns.tick() {
host.hub.send_to(
conn,
&C::Cooldown(play::Cooldown {
group: group.to_string(),
duration: 0,
}),
);
}
// Player.tick: a different main-hand item resets the attack
// strength, and detectEquipmentUpdates gives the guest its modifiers.
let g = &host.hub.guests[gi];
@@ -2319,7 +2346,35 @@ impl Game<'_> {
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at),
// LivingEntity.checkFallDamage: the crumbs reach every player.
MotionEvent::Fall(horizon_client::landing::FallEvent::Particles {
state,
position,
count,
speed,
}) => self.landing_dust(Some(host), state, position, count, speed),
MotionEvent::Fall(event) => self.landing_block_updates(&event),
// HoneyBlock.maybeDoSlideEffects: the sound reaches the
// others (Player.playSound excludes the player, whose client
// plays it), the entity event 53 everyone around.
MotionEvent::HoneySlide {
sound, particles, ..
} => {
let Some((id, at)) = host.hub.guest(conn).map(|g| (g.entity_id, g.position))
else {
continue;
};
if sound {
let name = "minecraft:block.honey_block.slide";
let source = horizon_client::settings::sound_source(name) as i32;
self.audio.play_unshared(name, Some(at), 1.0, 1.0);
host.hub.sound(name, at, 1.0, 1.0, source, Some(conn));
}
if particles {
self.honey_slide_particles(at);
host.hub.entity_event(id, 53, at);
}
}
_ => {}
}
}
@@ -304,6 +304,9 @@ impl Game<'_> {
None => 0,
};
let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z];
for f in &self.fangs.list {
out.push(state(f.id, "minecraft:evoker_fangs", f.pos, f.yaw, false));
}
// LightningBolt: each client draws and flashes its own.
for b in self.bolts.iter().filter(|b| b.id != 0) {
out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false));
@@ -354,6 +357,20 @@ impl Game<'_> {
a.is_some_and(|a| a.in_ground) || p.stuck,
));
}
// ThrownTrident.ID_LOYALTY (none for a mob's) and ID_FOIL, on
// AbstractArrow's flags.
K::Trident => {
let a = p.arrow.as_deref();
e.meta.extend(arrow_meta(
false,
a.is_some_and(|a| a.no_physics),
0,
a.is_some_and(|a| a.in_ground) || p.stuck,
));
if a.is_some_and(|a| a.pickup_item.has_any_enchantments()) {
e.meta.push((12, serializer::BOOLEAN, Value::Bool(true)));
}
}
// WitherSkull.DATA_DANGEROUS.
K::WitherSkull { dangerous: true } => {
e.meta.push((8, serializer::BOOLEAN, Value::Bool(true)));
@@ -1,7 +1,8 @@
//! Particles a server sends its players and its clients draw:
//! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which
//! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`).
use super::Game;
use super::{Game, lan::LanHost};
use horizon_client::lan::hub::Hub;
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_protocol::{
@@ -81,6 +82,66 @@ impl Game<'_> {
}
}
/// `LivingEntity.checkFallDamage`'s `ServerLevel.sendParticles` of the
/// landing block's crumbs: drawn in this window, when it has one, and
/// sent to each player within 32 blocks. `host` is the hub of a guest's
/// turn, which is out of `self.lan` meanwhile.
pub(super) fn landing_dust(
&mut self,
host: Option<&LanHost>,
state: BlockStateId,
at: Vec3,
count: i32,
speed: f64,
) {
let at = [at.x, at.y, at.z];
if self.serving.is_none() && self.options.dedicated.is_none() {
let block = [
at[0].floor() as i32,
(at[1] - 0.2).floor() as i32,
at[2].floor() as i32,
];
if let Some((sprite, tint)) = self.particle_sprite(state, block) {
self.particles.send_particles(
&ParticleOptions::block(ParticleType::Block, sprite, tint),
at,
[0.0; 3],
speed,
count as u32,
);
}
}
let Some(hub) = host.or(self.lan.as_ref()).map(|h| &h.hub) else {
return;
};
let Some(particle) = Self::hub_particle(
hub,
&ParticleOptions::simple(ParticleType::Block),
Some(state),
) else {
return;
};
let packet = C::LevelParticles(play::LevelParticles {
particle,
override_limiter: false,
always_show: false,
pos: at,
dist: [0.0; 3],
max_speed: [speed as f32; 3],
count,
randomization: 0,
});
for g in hub.guests.iter().filter(|g| hub.here(g)) {
// ServerLevel compares the player's block centre, strictly within 32.
let distance: f64 = (0..3)
.map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
.sum();
if distance < 32.0 * 32.0 {
g.send(&packet);
}
}
}
/// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's
/// network id and the data it carries (`state` for the block particles).
/// None while not serving, or for a particle whose data isn't sent from
@@ -89,13 +150,19 @@ impl Game<'_> {
&self,
options: &ParticleOptions,
state: Option<BlockStateId>,
) -> Option<Particle> {
Self::hub_particle(&self.lan.as_ref()?.hub, options, state)
}
/// `network_particle` for a hub that is out of `self.lan` meanwhile (a
/// guest's turn).
fn hub_particle(
hub: &Hub,
options: &ParticleOptions,
state: Option<BlockStateId>,
) -> Option<Particle> {
let name = format!("minecraft:{}", options.ty.name());
let id = self
.lan
.as_ref()?
.hub
.registry_id("minecraft:particle_type", &name)?;
let id = hub.registry_id("minecraft:particle_type", &name)?;
use ParticleType as T;
let c = options.color;
let data = match options.ty {
@@ -254,8 +321,14 @@ impl Game<'_> {
/// `ServerLevel.explode`'s packet to each player within 64 blocks. The
/// sound and the push reach them on their own (the level's sounds, the
/// motion a hurt player is sent), so the packet carries neither.
pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) {
let emitter = if radius < 2.0 {
pub(super) fn lan_explode(
&self,
center: [f64; 3],
small: bool,
radius: f32,
block_count: usize,
) {
let emitter = if small {
"minecraft:explosion"
} else {
"minecraft:explosion_emitter"
+12 -5
View File
@@ -37,6 +37,8 @@ pub(super) struct Strike {
amount: f32,
scale: f32,
crit: bool,
/// `Player.attack`'s `magicBoost > 0`: the enchantments added damage.
magic: bool,
from: [f64; 3],
sweep: Option<[f64; 3]>,
/// `causeExtraKnockback`: its strength and direction (the attacker's
@@ -109,7 +111,7 @@ impl Game<'_> {
pub(super) fn pvp_strike(&mut self) -> Option<Strike> {
let p = self.player.as_ref()?;
let from = [p.position.x, p.position.y, p.position.z];
let (amount, scale, crit) = self.melee_damage("minecraft:player");
let (amount, scale, crit, magic) = self.melee_damage("minecraft:player");
let sweep = self.sweep_attack_position(scale, crit);
let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale);
let (xd, zd) = self.extra_knockback_direction();
@@ -125,6 +127,7 @@ impl Game<'_> {
amount,
scale,
crit,
magic,
from,
sweep,
knockback: (strength, xd, zd),
@@ -257,7 +260,7 @@ impl Game<'_> {
} else {
Default::default()
};
if hurt && s.crit {
if hurt && (s.crit || s.magic) {
let target = match victim {
Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)),
Victim::Guest(conn) => host
@@ -267,13 +270,17 @@ impl Game<'_> {
};
if let Some((id, p)) = target {
let d = p.dimensions;
self.critical_hit(
s.attacker,
id,
let (feet, width, height) = (
[p.position.x, p.position.y, p.position.z],
f64::from(d.width),
f64::from(d.height),
);
if s.crit {
self.critical_hit(s.attacker, id, feet, width, height, false);
}
if s.magic {
self.critical_hit(s.attacker, id, feet, width, height, true);
}
}
}
// `Enchantment.doPostAttack`: thorns hurt the attacking player.
+5
View File
@@ -104,6 +104,9 @@ impl Game<'_> {
};
let m = &mut self.mobs[i];
if let Some(h) = holder {
if h == Holder::Player {
m.extra.leash_player = Some(player_uuid);
}
m.extra.leash = Some(h);
m.extra.leash_pending = None;
} else if m.age > 100 {
@@ -201,7 +204,9 @@ impl Game<'_> {
if self.mobs[index].extra.leash.is_some() {
self.break_leash(id, true, false);
}
let holder = self.acting_player_uuid();
self.mobs[index].extra.leash = Some(Holder::Player);
self.mobs[index].extra.leash_player = Some(holder);
self.lead_sound("tied", at);
// The lead is always used up.
if let Some(stack) = self.held_mut().as_mut() {
@@ -3,6 +3,7 @@
//! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax
//! off (3004) and scraping (3005).
use super::Game;
use horizon_client::items::ItemStack;
use horizon_client::particles::{self, ParticleOptions, ParticleType};
use horizon_core::{position::BlockPos, random::RandomSource};
use horizon_world::level::LevelEvent;
@@ -134,6 +135,68 @@ impl Game<'_> {
// Each guest plays it from the global packet.
self.audio.play_unshared(sound, at, volume, 1.0);
}
/// `LevelEventHandler.potionSplashParticles` (2002 with `Effect`, 2007
/// with `InstantEffect`): eight splash potion crumbs, and a hundred
/// spell particles in the potion's colour `data`, flung out in a disc.
pub(super) fn potion_splash_particles(&mut self, pos: BlockPos, data: i32, instant: bool) {
let ty = if instant {
ParticleType::InstantEffect
} else {
ParticleType::Effect
};
// Vec3.atBottomCenterOf.
let at = [
f64::from(pos.x) + 0.5,
f64::from(pos.y),
f64::from(pos.z) + 0.5,
];
let crumb = self.item_particle(&ItemStack::new("minecraft:splash_potion", 1));
let r = self.particles.level_random();
let crumbs: Vec<[f64; 3]> = (0..8)
.map(|_| {
[
r.next_gaussian() * 0.15,
r.next_double() * 0.2,
r.next_gaussian() * 0.15,
]
})
.collect();
for v in crumbs {
self.particles.add(&crumb, at, v);
}
let channel = |shift: i32| ((data >> shift) & 0xFF) as f32 / 255.0;
let color = [channel(16), channel(8), channel(0)];
for _ in 0..100 {
let r = self.particles.level_random();
let dist = r.next_double() * 4.0;
let angle = r.next_double() * std::f64::consts::PI * 2.0;
let velocity = [
angle.cos() * dist,
0.01 + r.next_double() * 0.5,
angle.sin() * dist,
];
let brightness = 0.75 + r.next_float() * 0.25;
let options = ParticleOptions {
color: [
color[0] * brightness,
color[1] * brightness,
color[2] * brightness,
1.0,
],
scale: dist as f32,
..ParticleOptions::simple(ty)
};
self.particles.add(
&options,
[
at[0] + velocity[0] * 0.1,
at[1] + 0.3,
at[2] + velocity[2] * 0.1,
],
velocity,
);
}
}
/// Queue and play level event `id` at `pos` (`Level.levelEvent`).
pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) {
self.level_events.push(LevelEvent::LevelEvent {
+4 -2
View File
@@ -75,7 +75,7 @@ pub(super) struct Parked {
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
lan_critical_hits: Vec<(Option<u32>, i32)>,
lan_critical_hits: Vec<(Option<u32>, i32, bool)>,
/// Only the per-level parts of these are used (`swap_level`).
anims: BlockEntityAnims,
raiding: Raiding,
@@ -192,6 +192,7 @@ impl Game<'_> {
let mut locator = self.end.locator();
swap(&mut locator, &mut p.locator);
self.end.set_locator(locator);
self.share_spawn_conditions();
swap(&mut self.save, &mut p.save);
swap(&mut self.block_ticks, &mut p.block_ticks);
swap(&mut self.tick_chunks, &mut p.tick_chunks);
@@ -399,7 +400,8 @@ impl Game<'_> {
}
*next += self.clock.tick_duration();
if *next > now {
// A `/pregen` task keeps the workers fed until the next tick.
// A `/pregen` task or force-loaded chunks keep the workers fed
// until the next tick.
self.pump_pregen(*next);
let now = Instant::now();
if *next > now {
+73 -1
View File
@@ -1,6 +1,7 @@
//! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the
//! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like
//! dropped block items.
//! dropped block items. Also the block models mobs wear (`SnowGolemHeadLayer`,
//! `MushroomCowMushroomLayer`).
use super::Game;
use horizon_client::{
items::ItemStack,
@@ -218,6 +219,7 @@ impl Game<'_> {
) {
self.captain_banner_geometry(mob, camera, alpha, light, out);
self.held_item_geometry(mob, camera, alpha, light, true, out);
self.worn_block_geometry(mob, camera, alpha, light, out);
if mob.species() == Species::Enderman
&& let Some(state) = mob.extra.carried
&& let Some((sprite, tint)) = self.block_face_sprite(state)
@@ -244,6 +246,76 @@ impl Game<'_> {
);
}
}
/// `SnowGolemHeadLayer` and `MushroomCowMushroomLayer`: the carved pumpkin
/// on a snow golem's head, and the mushrooms on an adult mooshroom's back
/// and head, as baked block models.
fn worn_block_geometry(
&self,
mob: &Mob,
camera: glam::DVec3,
alpha: f64,
light: u32,
out: &mut Vec<Vertex>,
) {
use glam::{Mat4, Vec3};
let species = mob.species();
let on_head = match species {
Species::SnowGolem => !mob.extra.sheared,
Species::Mooshroom => !mob.is_baby(),
_ => false,
};
// The layers draw nothing on an invisible mob (the glow outline is not drawn).
if !on_head || horizon_client::mobs::trader::is_invisible(mob) {
return;
}
let registry = &self.pack.assets.registry;
let block = match species {
Species::SnowGolem => "minecraft:carved_pumpkin",
_ if mob.extra.variant == 1 => "minecraft:brown_mushroom",
_ => "minecraft:red_mushroom",
};
let Some(state) = registry.default_state(block) else {
return;
};
let alpha = alpha as f32;
let Some(head) = render::part_transform(mob, alpha, camera, self.res.mob_data(), "head")
else {
return;
};
let unit = Mat4::from_translation(Vec3::splat(-0.5));
let flip = Mat4::from_scale(Vec3::new(-1.0, -1.0, 1.0));
let at = |x: f32, y: f32, z: f32| Mat4::from_translation(Vec3::new(x, y, z));
let spin = |degrees: f32| Mat4::from_rotation_y(degrees.to_radians());
let transforms = if species == Species::SnowGolem {
vec![
head * at(0.0, -0.34375, 0.0)
* spin(180.0)
* Mat4::from_scale(Vec3::new(0.625, -0.625, -0.625))
* unit,
]
} else {
let base = render::base_transform(mob, alpha, camera);
vec![
base * at(0.2, -0.35, 0.5) * spin(-48.0) * flip * unit,
base * at(0.2, -0.35, 0.5)
* spin(42.0)
* at(0.1, 0.0, -0.6)
* spin(-48.0)
* flip
* unit,
head * at(0.0, -0.7, -0.2) * spin(-78.0) * flip * unit,
]
};
// The hurt tint reaches these blocks as it does the body.
let overlay = horizon_client::overlay::living(0.0, mob.hurt_time > 0 || mob.death_time > 0);
for t in transforms {
let start = out.len();
self.block_model_vertices(state, 0, t, light, true, out);
for vertex in &mut out[start..] {
vertex.layer = overlay;
}
}
}
/// `ItemInHandLayer`: both hands through the item model pipeline; `lit`
/// applies the level's diffuse lighting (off for GUI previews, which
/// light the projected quads themselves).
+4 -1
View File
@@ -371,7 +371,10 @@ impl Game<'_> {
}
/// The chat's tree after the running mods changed.
fn sync_mod_commands(&mut self) {
let mut names = self.mods.mods.commands().peekable();
// In-frame, the window runs server mods too: their names, free text
// here (the server parses their arguments).
let server = self.mods.mods.server_commands().map(|c| c.name.as_str());
let mut names = self.mods.mods.commands().chain(server).peekable();
self.mods.tree = names
.peek()
.is_some()
+6 -1
View File
@@ -3,7 +3,7 @@
use super::Game;
use horizon_client::{
blocks::Fluid,
music::{BackgroundMusic, Music, Situation},
music::{BackgroundMusic, Music, MusicFrequency, Situation},
sound_engine::TickContext,
};
@@ -11,6 +11,11 @@ impl Game<'_> {
/// `Minecraft.tick` -> `MusicManager.tick`, once per client tick.
pub(super) fn tick_music(&mut self) {
let (music, volume) = self.situational_music();
// Options.musicFrequency's listener: MusicManager.setMinutesBetweenSongs.
let frequency = MusicFrequency::parse(&self.settings.file.name("musicFrequency"));
if frequency != self.music.frequency {
self.music.set_frequency(frequency, music.as_ref());
}
// LevelLoadingScreen: no new track before the player is in the world.
let loading = self.title.is_none() && self.player.is_none() && self.win.is_none();
self.music
+10 -2
View File
@@ -357,7 +357,8 @@ impl Game<'_> {
pub(super) fn load_mob(&mut self, tag: Tag, mount: Option<u32>) -> Option<u32> {
self.next_entity += 1;
let uuid = entity_nbt::uuid(&tag);
// Structure entities placed with finalizeEntities.
// Structure mobs that generation left to finish: saves from before
// they were finalized at placement, or a placement that could not.
let mut tag = tag;
let mut finalize = false;
if let Tag::Compound(c) = &mut tag {
@@ -449,7 +450,8 @@ impl Game<'_> {
}
}
/// An entity of a type Horizon does not simulate, kept as its compound.
fn load_other(&mut self, tag: Tag, kind: &str) -> Option<u32> {
fn load_other(&mut self, mut tag: Tag, kind: &str) -> Option<u32> {
strip_finalize(&mut tag);
let position = entity_nbt::position(&tag)?;
let rotation = match tag.get("Rotation") {
Some(Tag::List(l)) => {
@@ -1014,3 +1016,9 @@ impl Game<'_> {
self.save.save_entities(chunks)
}
}
/// Only a mob is finalized; another entity drops the request.
fn strip_finalize(tag: &mut Tag) {
if let Tag::Compound(c) = tag {
c.remove(&"horizon:finalize".into());
}
}
+58 -52
View File
@@ -12,6 +12,7 @@ use horizon_client::{
hud_layout, hud_overlays, inventory_effects,
items::ItemStack,
mesher::Vertex,
text::Text,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
@@ -26,6 +27,9 @@ pub(super) struct ThrownPotion {
position: Vec3,
velocity: Vec3,
age: u32,
/// `Projectile.getOwner`'s display name: the player who threw it (none
/// for a dispenser's).
owner: Option<Text>,
}
/// A mob's effect ids carry the `minecraft:` namespace.
fn mob_effect_id(id: &str) -> Option<&'static str> {
@@ -47,7 +51,13 @@ fn mob_effect_id(id: &str) -> Option<&'static str> {
impl Game<'_> {
/// A splash potion, lingering potion or experience bottle in flight (the
/// player's throws and dispensers both end up here).
pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) {
pub(super) fn launch_thrown(
&mut self,
stack: ItemStack,
position: Vec3,
velocity: Vec3,
owner: Option<Text>,
) {
self.potions.thrown.push(ThrownPotion {
id: 0,
stack,
@@ -55,6 +65,7 @@ impl Game<'_> {
position,
velocity,
age: 0,
owner,
});
}
}
@@ -135,6 +146,7 @@ impl PotionState {
position: at,
velocity,
age: 0,
owner: None,
});
}
/// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows.
@@ -237,6 +249,7 @@ impl Game<'_> {
},
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
v,
Some(self.player_display_text()),
);
self.swing_arm();
self.consume_held();
@@ -300,6 +313,7 @@ impl Game<'_> {
return true;
}
self.using = None;
self.send_use_item_complete();
self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player);
if ominous {
self.drink_ominous_bottle(slot, stack);
@@ -548,15 +562,15 @@ impl Game<'_> {
}
}
if let Some(p) = hit {
landed.push((t.stack.clone(), p));
landed.push((t.stack.clone(), p, t.owner.clone()));
return false;
}
t.position = next;
t.age < 1200 && t.position.y > -128.0
});
self.potions.thrown = thrown;
for (stack, at) in landed {
self.splash(&stack, at);
for (stack, at, owner) in landed {
self.splash(&stack, at, owner);
}
}
/// `ThrowableProjectile.tick`'s `applyGravity` and `applyInertia`, which
@@ -664,6 +678,7 @@ impl Game<'_> {
effects: &'static [(&'static str, i32, i32)],
at: Vec3,
scale: f64,
source: &Text,
) {
if let Some(p) = self.player.as_ref() {
let center = Vec3::new(
@@ -679,6 +694,18 @@ impl Game<'_> {
let instant = brewing::effect(id).is_some_and(|e| e.instant);
if instant {
if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) {
// HealOrHarmMobEffect.applyInstantaneousEffect with
// a source: indirectMagic, not plain magic.
let a = match a {
EffectAction::Hurt("minecraft:magic", amount) => {
self.note_direct_entity(
"minecraft:indirect_magic",
source.clone(),
);
EffectAction::Hurt("minecraft:indirect_magic", amount)
}
a => a,
};
self.apply_effect_action(a);
}
} else {
@@ -694,68 +721,47 @@ impl Game<'_> {
}
}
/// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash).
fn splash(&mut self, stack: &ItemStack, at: Vec3) {
fn splash(&mut self, stack: &ItemStack, at: Vec3, owner: Option<Text>) {
let block = [at.x, at.y, at.z].map(|v| v.floor() as i32);
if &*stack.item == "minecraft:experience_bottle" {
// ThrownExperienceBottle.onHit: the water-coloured splash (level
// event 2002) and 3 to 11 experience.
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.audio.play(
"minecraft:entity.splash_potion.break",
Some([at.x, at.y, at.z]),
1.0,
pitch,
);
for _ in 0..8 {
let v = [
f64::from(self.world.random.next_float() - 0.5) * 0.3,
0.2,
f64::from(self.world.random.next_float() - 0.5) * 0.3,
];
let p = horizon_client::particles::Particle::terrain(
&mut self.world.random,
[at.x, at.y, at.z],
v,
"item/splash_potion".into(),
0x38_5DC6,
);
self.particles.push(p);
}
// event 2002, its sound 1053) and 3 to 11 experience.
self.level_event_at(2002, block, 0xFF38_5DC6u32 as i32);
self.level_event_at(1053, block, 0);
let r = &mut self.world.random;
let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0);
self.spawn_orbs([at.x, at.y, at.z], value as u32);
return;
}
let lingering = &*stack.item == "minecraft:lingering_potion";
let event = if lingering {
"minecraft:entity.lingering_potion.break"
} else {
"minecraft:entity.splash_potion.break"
};
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch);
// AbstractThrownPotion.onHit: level event 2007 and sound 1054 for a
// potion with instant effects, 2002 and 1053 otherwise.
let potion = stack.potion().and_then(brewing::potion);
let instant = potion.is_some_and(|d| {
d.effects
.iter()
.any(|(id, ..)| brewing::effect(id).is_some_and(|e| e.instant))
});
let color = brewing::potion_color(stack.potion());
for _ in 0..8 {
let v = [
f64::from(self.world.random.next_float() - 0.5) * 0.3,
0.2,
f64::from(self.world.random.next_float() - 0.5) * 0.3,
];
let p = horizon_client::particles::Particle::terrain(
&mut self.world.random,
[at.x, at.y, at.z],
v,
"item/splash_potion".into(),
color,
);
self.particles.push(p);
}
self.level_event_at(if instant { 2007 } else { 2002 }, block, color as i32);
self.level_event_at(if instant { 1054 } else { 1053 }, block, 0);
let scale = if lingering { 0.25 } else { 1.0 };
let Some(def) = stack.potion().and_then(brewing::potion) else {
let Some(def) = potion else {
return;
};
// Every player in range (`ThrownSplashPotion.applySplash` over
// `LivingEntity`s, the players among them).
self.for_each_player(|g| g.splash_on_player(def.effects, at, scale));
// Instant damage is indirectMagic(potion or cloud, owner), which the
// death message names by the owner, else by the potion or cloud.
let source = owner.unwrap_or_else(|| {
let entity = if lingering {
"entity.minecraft.area_effect_cloud"
} else {
"entity.minecraft.splash_potion"
};
Text::translate(entity, &[])
});
self.for_each_player(|g| g.splash_on_player(def.effects, at, scale, &source));
// Mobs take the instant effects (undead invert healing and harming).
let undead = &self.res.stations().enchantments.entity_tags;
let mut hits = Vec::new();
+1 -1
View File
@@ -235,7 +235,7 @@ impl Game<'_> {
}
out
}
fn difficulty_id(&self) -> i32 {
pub(super) fn difficulty_id(&self) -> i32 {
use horizon_world::food::Difficulty;
match self.world.health_rules.difficulty {
Difficulty::Peaceful => 0,
+153 -51
View File
@@ -117,6 +117,8 @@ pub(super) struct Remote {
joined: bool,
status: String,
pub(super) entity_id: i32,
/// The item the player's use began with (`LivingEntity.useItem`).
pub(super) use_item: Option<Arc<str>>,
dimension: DimensionType,
/// What chunk packets decode with (the dimension's height and sky, the
/// biome registry); replaced whenever one of them changes.
@@ -432,6 +434,7 @@ impl Game<'_> {
joined: false,
status: "Connecting to the server...".into(),
entity_id: 0,
use_item: None,
dimension: DimensionType::vanilla("minecraft:overworld"),
chunk_format: Arc::new(ChunkFormat::new(
&DimensionType::vanilla("minecraft:overworld"),
@@ -1565,7 +1568,7 @@ impl Game<'_> {
}
}
/// Find a game slot in the menu's complete, contiguous slot mapping.
fn menu_slot_index(menu: &str, internal: usize) -> Option<usize> {
pub(super) fn menu_slot_index(menu: &str, internal: usize) -> Option<usize> {
(0..)
.map_while(|slot| Self::menu_slot(menu, slot))
.position(|slot| slot == internal)
@@ -1644,8 +1647,10 @@ impl Game<'_> {
self.send(S::ClientInformation(info));
}
C::Respawn(p) => {
// A new player, without effects: the server sends them again.
// A new player, without effects (the server sends them
// again) and with no item in use.
self.potions.effects.clear();
self.using = None;
self.enter_remote_dimension(&p.spawn, true);
self.screen = Screen::Playing;
if let Some(r) = self.remote.as_mut() {
@@ -1746,7 +1751,17 @@ impl Game<'_> {
f64::from(p.y) / 8.0,
f64::from(p.z) / 8.0,
];
self.audio.play(&name, Some(at), p.volume, p.pitch);
// ClientPacketListener.handleSoundEvent plays with packet.getSource().
match usize::try_from(p.source)
.ok()
.filter(|s| *s < horizon_client::settings::SOUND_SOURCES.len())
{
Some(source) => {
self.audio
.play_on(source, &name, Some(at), p.volume, p.pitch)
}
None => self.audio.play(&name, Some(at), p.volume, p.pitch),
}
}
}
C::StopSound(p) => self
@@ -1980,9 +1995,9 @@ impl Game<'_> {
}
}
}
// Entity.DATA_SHARED_FLAGS_ID's crouching bit: another
// player's or a mannequin's crouch (their model and
// Entity.isDiscrete's name tag).
// Entity.DATA_SHARED_FLAGS_ID's crouching and sprinting bits:
// another player's or a mannequin's crouch (their model and
// Entity.isDiscrete's name tag), and the dust a runner raises.
if (mannequin
|| self
.remote
@@ -1993,6 +2008,7 @@ impl Game<'_> {
for (index, _, value) in &p.values {
if let (0, Value::Byte(flags)) = (index, value) {
m.extra.crouching = flags & 2 != 0;
m.extra.sprinting = flags & 8 != 0;
}
}
}
@@ -2116,6 +2132,7 @@ impl Game<'_> {
if p.event == super::fireworks::FIREWORK_EXPLODE_EVENT {
self.remote_firework_explosion(p.id);
}
self.remote_fangs_event(p.id as u32, p.event);
// LocalPlayer.setPermissions also refreshes an open World Options screen.
if (24..=28).contains(&p.event)
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
@@ -2140,9 +2157,38 @@ impl Game<'_> {
{
m.health = 0.0;
}
// LivingEntity.handleEntityEvent 60: the poof as the dead body goes.
if p.event == 60
&& let Some(m) = self.mobs.iter().find(|m| m.id == p.id as u32)
{
let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height()));
self.death_poof([at.x, at.y, at.z], w, h);
}
if p.event == super::totem::TOTEM_EVENT {
self.remote_totem(p.id);
}
// Entity event 53: the honey slide particles of a player
// sliding down a honey block (HoneyBlock.showSlideParticles).
if p.event == 53 {
let at = if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) {
self.player
.as_ref()
.map(|q| [q.position.x, q.position.y, q.position.z])
} else {
self.mobs
.iter()
.find(|m| m.id == p.id as u32)
.map(|m| [m.position.x, m.position.y, m.position.z])
};
if let Some(at) = at {
self.honey_slide_particles(at);
}
}
if p.event == super::consume::USE_ITEM_COMPLETE_EVENT
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
{
self.remote_complete_using();
}
}
C::Animate(p) => self.remote_animate(p.id, p.action),
// ClientPacketListener.handleSwingAnimation: the entity swings
@@ -3140,12 +3186,8 @@ impl Game<'_> {
fn tick_remote_level(&mut self) -> Result<()> {
self.ticks += 1;
self.track_experience_display();
// Player.tick's ItemCooldowns.tick: this path replaces `tick_world`'s
// for a server's client (multiplayer and the default single player),
// so the entries advance here or the slot stays shaded until the
// server says the entry ended. `onCooldownEnded` is the plain
// ItemCooldowns' no-op on a client.
self.cooldowns.tick();
// Leaving a slot clears its bundle's selection here and on the server.
self.tick_bundle_hover();
// Options.broadcastOptions: a changed render distance or Chat option
// is sent again.
let view = client_view_distance(self.settings.render_distance);
@@ -3179,6 +3221,14 @@ impl Game<'_> {
// Window callbacks only queue clicks, so an interaction cannot leak
// between CLIENT_TICK_END and a later pong.
self.remote_handle_input();
// Player.tick's ItemCooldowns.tick, in ClientLevel.tickEntities after
// handleKeybinds: this path replaces `tick_world`'s for a server's
// client (multiplayer and the default single player), so the entries
// advance here or the slot stays shaded until the server says the
// entry ended. `onCooldownEnded` is the plain ItemCooldowns' no-op on
// 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();
// ClientLevel.tick: the border's size change.
self.border.tick();
self.player_border();
@@ -3336,6 +3386,13 @@ impl Game<'_> {
horizon_client::motion::MotionEvent::InsidePortal { .. } => {
self.client_inside_nether_portal();
}
// HoneyBlock.maybeDoSlideEffects on the client's own level:
// the slide sound, heard here (LocalPlayer.playSound); the
// particles come from the server's event 53.
horizon_client::motion::MotionEvent::HoneySlide { sound: true, .. } => {
self.audio
.play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0);
}
_ => {}
}
}
@@ -3512,6 +3569,16 @@ impl Game<'_> {
if m.species() == horizon_client::mobs::Species::Rabbit {
horizon_client::mobs::rabbit::base_tick(m);
}
if matches!(
m.species(),
horizon_client::mobs::Species::Horse
| horizon_client::mobs::Species::Donkey
| horizon_client::mobs::Species::Mule
| horizon_client::mobs::Species::SkeletonHorse
| horizon_client::mobs::Species::ZombieHorse
) {
horizon_client::mobs::equine::tail_tick(m);
}
if m.species() == horizon_client::mobs::Species::Creeper {
horizon_client::mobs::hostile::creeper_client_tick(m);
}
@@ -3522,6 +3589,10 @@ impl Game<'_> {
) {
horizon_client::mobs::guardian::client_tick(m);
}
// PolarBear.tick: the stand animation follows the synched flag.
if m.species() == horizon_client::mobs::Species::PolarBear {
horizon_client::mobs::polar_bear::client_tick(m);
}
if m.hurt_time > 0 {
m.hurt_time -= 1;
}
@@ -4300,6 +4371,12 @@ impl Game<'_> {
let Some(info) = self.res.items().get(&held.item).cloned() else {
return false;
};
// MultiPlayerGameMode.useItem's prediction: an item cooling down
// passes (its packet still goes).
let group = horizon_client::cooldowns::group(&held, info.use_cooldown.as_ref());
if self.cooldowns.is_on_cooldown(&group) {
return false;
}
// Food starts being eaten (Consumable.startConsuming). A food that
// can't be eaten (full and not always-edible) fails the use
// (InteractionResult.FAIL): startUseItem tries the other hand, and
@@ -4308,10 +4385,13 @@ impl Game<'_> {
if info.food.is_some() && !eating {
return false;
}
// MultiPlayerGameMode.useItem runs the use here too (inside
// startPrediction): the `use_cooldown` component starts its entry, and
// the server's ClientboundCooldownPacket confirms it.
self.apply_use_cooldown(&held);
// It runs the use here too: ItemStack.use starts the `use_cooldown`
// of an item with no use time, and the server's
// ClientboundCooldownPacket confirms it; one held in use starts it at
// finishUsingItem (remote_complete_using).
if !info.consumable.as_ref().is_some_and(|c| c.ticks() > 0) {
self.apply_use_cooldown(&held);
}
if self.with_hand(hand, |g| g.remote_use_book(&held)) {
return true;
}
@@ -4383,14 +4463,25 @@ impl Game<'_> {
self.remote_use_item(Hand::Off);
}
/// `LivingEntity.updatingUsingItem` on a server client: an item held in
/// use (`held_until_released`), and a
/// consumable's eating animation and its crumbs. The server eats it and
/// sends the stack, the hunger and the sounds.
/// use (`held_until_released`), and a consumable's eating animation and
/// its crumbs until the server's USE_ITEM_COMPLETE. The server sends the
/// stack, its hunger and the sounds.
fn remote_tick_using(&mut self) {
let Some((slot, ticks)) = self.using else {
return;
};
let stack = self.stack_in(slot).cloned();
// The use stops when the hand no longer holds the item it began with
// (ItemStack.isSameItem).
let item = stack.as_ref().map(|s| Arc::clone(&s.item));
if let Some(r) = self.remote.as_mut() {
if ticks == 0 {
r.use_item = item;
} else if r.use_item != item {
self.using = None;
return;
}
}
// Another hotbar slot picked: LivingEntity.updatingUsingItem sees a
// different stack in the hand. The off hand keeps its item.
let in_hand = slot == self.selected || slot == super::shield::OFFHAND_SLOT;
@@ -4415,20 +4506,51 @@ impl Game<'_> {
self.using = None;
return;
}
// Consumable.shouldEmitParticlesAndSounds, as in tick_used_item.
let duration = consumable.ticks().max(0) as u32;
let remaining = duration - ticks.min(duration);
if consumable.particles && consumable.should_emit(remaining as i32) {
// Consumable.startConsuming eats one with no use time at once, without
// a use (nor a USE_ITEM_COMPLETE).
if consumable.ticks() <= 0 {
self.using = None;
return;
}
// Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. The
// countdown goes on past zero (LivingEntity.updateUsingItem completes
// only on the server) until the server's USE_ITEM_COMPLETE.
let remaining = consumable.ticks() - ticks as i32;
if consumable.particles && consumable.should_emit(remaining) {
self.eat_particles(&stack, 5);
}
if ticks + 1 >= duration {
self.using = None;
if consumable.particles {
self.eat_particles(&stack, 16);
}
} else {
self.using = Some((slot, ticks + 1));
self.using = Some((slot, ticks + 1));
}
/// `Player.handleEntityEvent(9)`: `completeUsingItem` on the client. A consumable's last crumbs, and FoodProperties.onConsume,
/// which runs on the client too (Consumable.onConsume calls its
/// ConsumableListeners on both sides): the client's FoodData eats at once,
/// so a held right click finds `Player.canEat` false instead of starting
/// another bite before the server's ClientboundSetHealth arrives.
fn remote_complete_using(&mut self) {
let Some((slot, _)) = self.using.take() else {
return;
};
let Some(stack) = self.stack_in(slot).cloned() else {
return;
};
let Some(info) = self.res.items().get(&stack.item).cloned() else {
return;
};
if info.consumable.as_ref().is_some_and(|c| c.particles) {
self.eat_particles(&stack, 16);
}
if let Some((nutrition, saturation)) = info.food
&& let Some(r) = self.remote.as_mut()
{
// FoodData.eat(nutrition, saturation), as finish_consuming does;
// the next ClientboundSetHealth replaces it.
let (_, food, sat) = &mut r.health;
*food = (*food + nutrition as i32).clamp(0, 20);
*sat = (*sat + saturation).clamp(0.0, *food as f32);
self.apply_remote_health();
}
// ItemStack.finishUsingItem's applyAfterUseComponentSideEffects.
self.apply_use_cooldown(&stack);
}
/// MouseHandler updates KeyMapping; handleKeybinds sends packets on a tick.
pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
@@ -4735,7 +4857,7 @@ impl Game<'_> {
}
/// The server's open menu: its window id and menu type (0, "inventory"
/// when none is open).
fn remote_menu(&self) -> (i32, String) {
pub(super) fn remote_menu(&self) -> (i32, String) {
match self.remote.as_ref().and_then(|r| r.menu.clone()) {
Some((id, name)) => (id, name),
None => (0, "inventory".to_owned()),
@@ -4825,26 +4947,6 @@ impl Game<'_> {
}));
}
}
/// A `ContainerClick` on game slot `internal` of the server's open menu
/// (`input` is the ContainerInput ordinal). False when the menu has no
/// such slot.
pub(super) fn remote_slot_click(&mut self, internal: usize, button: i8, input: i32) -> bool {
let (container, menu) = self.remote_menu();
let slot = Self::menu_slot_index(&menu, internal);
let Some(slot) = slot else { return false };
let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s));
let state = self.remote.as_ref().map_or(0, |r| r.state_id);
self.send(S::ContainerClick(play::ContainerClick {
container,
state,
slot: slot as i16,
button,
input,
changed: Vec::new(),
carried,
}));
true
}
/// The server's open menu is the inventory or a chest-like container
/// (chests, barrels, ender chests: `generic_9xN`; shulker boxes).
pub(super) fn remote_storage_open(&self) -> bool {
@@ -5,7 +5,8 @@
use super::Game;
use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
use horizon_client::mobs::{Mob, Species, Who, bat, tame};
use horizon_protocol::entity_data::Value;
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_protocol::entity_data::{Particle, ParticleData, Value};
use horizon_protocol::registry::Builtin;
/// The values `apply` takes from one SetEntityData packet, by vanilla's entry
@@ -34,6 +35,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
// LivingEntity.DATA_HEALTH_ID: the boss bars and the death
// animation follow it.
(9, Value::Float(health)) => m.health = *health,
// LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID:
// the swirls of its effects (`tickEffects` draws them).
(10, Value::Particles(list)) => m.extra.effect_particles = swirls(list, builtin),
(11, Value::Bool(ambient)) => m.extra.effect_ambient = *ambient,
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4.
// Mob.isAggressive draws the illagers' and skeletons' attack
// poses and the vindicator's axe.
@@ -59,6 +64,8 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
Who::Mob(*target as u32)
});
}
// 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),
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared.
@@ -66,6 +73,14 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
m.extra.color = (*wool & 15) as u8;
m.extra.sheared = wool & 16 != 0;
}
// SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on.
(Species::SnowGolem, 16, Value::Byte(flags)) => m.extra.sheared = flags & 16 == 0,
// MushroomCow.DATA_TYPE: 0 red, 1 brown.
(Species::Mooshroom, 17, Value::Int(variant)) => {
m.extra.variant = (*variant == 1) as u8
}
// Piglin.DATA_IS_DANCING: the dance pose.
(Species::Piglin, 19, Value::Bool(dancing)) => m.extra.scratch[0] = i32::from(*dancing),
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
(Species::Wolf | Species::Cat | Species::Parrot, 18, Value::Byte(flags)) => {
m.extra.sitting = flags & 1 != 0;
@@ -100,6 +115,30 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
}
}
/// 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> {
let channel = |argb: i32, shift: u32| ((argb >> shift) & 255) as f32 / 255.0;
list.iter()
.filter_map(|p| {
let name = builtin.get("minecraft:particle_type")?.name(p.id)?;
let ty = ParticleType::from_name(name)?;
Some(match p.data {
Some(ParticleData::Color(argb)) => ParticleOptions::colored(
ty,
[
channel(argb, 16),
channel(argb, 8),
channel(argb, 0),
channel(argb, 24),
],
),
_ => ParticleOptions::simple(ty),
})
})
.collect()
}
/// VillagerData as the network sends it: the type and the profession by
/// their built-in registry ids, then the level.
fn villager_data(m: &mut Mob, data: &[i32], builtin: &Builtin) {
@@ -95,6 +95,7 @@ impl Game<'_> {
let (yaw, pitch) = rotation;
self.remove_remote_projectile(id);
match kind {
"minecraft:evoker_fangs" => self.insert_fangs(id, position, yaw, 0, 0),
"minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt {
id,
position: at,
@@ -161,6 +162,10 @@ impl Game<'_> {
let Some(k) = projectile_kind(kind) else {
return false;
};
if k == ProjectileKind::LlamaSpit {
self.particles
.llama_spit_burst(position, [velocity.x, velocity.y, velocity.z]);
}
let mut p = Projectile::new(k, at, None);
p.id = id;
p.velocity = velocity;
@@ -296,6 +301,7 @@ impl Game<'_> {
/// One tick of interpolation, as `tick_remote_objects`.
pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
self.tick_remote_fangs();
// PrimedTnt.tick runs on a client too: it falls, bounces and burns its
// fuse down (the swell and flash follow it) between the server's
// updates (every 10 ticks), and a client discards it when the fuse
@@ -458,6 +464,7 @@ impl Game<'_> {
}
pub(super) fn remove_remote_projectile(&mut self, id: u32) {
self.fangs.list.retain(|f| f.id != id);
self.tnts.retain(|t| t.id != id);
self.falling.retain(|f| f.id != id);
self.creatures.projectiles.retain(|p| p.id != id);
@@ -473,6 +480,7 @@ impl Game<'_> {
/// Every one a server sent (a new connection, level or dimension).
pub(super) fn clear_remote_projectiles(&mut self) {
self.fangs.list.clear();
self.tnts.clear();
self.falling.clear();
self.creatures.projectiles.clear();
@@ -493,6 +501,12 @@ impl Game<'_> {
use serde_json::json;
let at = |p: Vec3| [p.x, p.y, p.z];
let mut out = Vec::new();
for f in &self.fangs.list {
out.push(
json!({"id": f.id, "kind": "minecraft:evoker_fangs", "position": f.pos,
"yaw": f.yaw, "started": f.started, "life": f.life}),
);
}
for t in &self.tnts {
out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse}));
}
@@ -7,6 +7,7 @@ use horizon_client::{
biome::Biomes,
blocks::{BlockFacts, Fluid},
chunk::{HEIGHT, MIN_Y},
containers::BlockEntity,
particles::{ParticleLevel, ParticleOptions, ParticleType},
world::World,
};
@@ -344,6 +345,10 @@ impl Game<'_> {
&mut self.particles,
&ctx,
r.block_entities(),
&|pos| match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) {
Some(BlockEntity::Campfire(c)) => c.items.each_ref().map(Option::is_some),
_ => [false; 4],
},
);
}
let level = ParticleLevel {
+10 -2
View File
@@ -132,8 +132,16 @@ impl Game<'_> {
match t {
Target::Player => Some(self.acting_player_name().to_owned()),
Target::Guest(conn) => self.command_guest(conn).map(|g| g.name.clone()),
Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))),
_ => None,
Target::Mob(id)
| Target::Item(id)
| Target::Stand(id)
| Target::Frame(id)
| Target::Painting(id)
| Target::Boat(id)
| Target::Cart(id)
| Target::Other(id) => Some(uuid_text(self.uuid_for(id))),
// Orbs and projectiles are addressed by index and have no UUID here.
Target::Orb(_) | Target::Projectile(_) => None,
}
}
fn holder_for(&mut self, t: Target) -> Option<Holder> {
+73 -1
View File
@@ -59,9 +59,12 @@ mod run {
lan::data::component_nbt,
text::{self, Text},
};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView};
use horizon_mods::{
ArgumentKind, BlockPos, GameMode, Output, ServerCommand, ServerPlayer, WorldView,
};
use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::{Value, json};
/// Blocks queued for levels that don't tick (another dimension, in-frame)
/// are kept up to this many; the oldest go first.
@@ -98,6 +101,60 @@ mod run {
}
}
/// Server mods' commands as a root of the commands report
/// (`lan::commands`): a literal per command, then its arguments in a
/// chain, each node runnable where only optional arguments follow.
fn command_tree<'a>(commands: impl Iterator<Item = &'a ServerCommand>) -> Value {
let mut root = serde_json::Map::new();
for c in commands {
let mut next: Option<(String, Value)> = None;
for (i, a) in c.arguments.iter().enumerate().rev() {
let executable = c.arguments.get(i + 1).is_none_or(|b| b.optional);
let (parser, properties) = match a.kind {
ArgumentKind::Word => ("brigadier:string", json!({"type": "word"})),
ArgumentKind::Text => ("brigadier:string", json!({"type": "greedy"})),
ArgumentKind::Integer((min, max)) => {
let mut p = serde_json::Map::new();
if let Some(min) = min {
p.insert("min".into(), min.into());
}
if let Some(max) = max {
p.insert("max".into(), max.into());
}
("brigadier:integer", Value::Object(p))
}
ArgumentKind::Number => ("brigadier:double", Value::Null),
ArgumentKind::Boolean => ("brigadier:bool", Value::Null),
ArgumentKind::Player => (
"minecraft:entity",
json!({"amount": "single", "type": "players"}),
),
ArgumentKind::BlockPos => ("minecraft:block_pos", Value::Null),
};
let mut node = json!({
"type": "argument",
"parser": parser,
"properties": properties,
"executable": executable,
});
if let Some((name, child)) = next.take() {
node["children"] = json!({ name: child });
}
next = Some((a.name.clone(), node));
}
let executable = c.arguments.first().is_none_or(|a| a.optional);
let mut literal = json!({"type": "literal", "executable": executable});
if let Some((name, child)) = next {
literal["children"] = json!({ name: child });
}
root.insert(c.name.clone(), literal);
}
if root.is_empty() {
return Value::Null;
}
json!({"type": "root", "children": root})
}
/// `minecraft:oak_log[axis=y]`.
fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String {
let Some(s) = registry.state(state) else {
@@ -191,6 +248,7 @@ mod run {
// A server has no frames to check its dev mods in.
self.reload_dev_mods();
}
self.send_server_mod_commands();
if !self.mods.server {
return;
}
@@ -257,6 +315,20 @@ mod run {
self.apply_mod_block_writes();
}
/// Players' command trees list the running server mods' commands
/// after vanilla's, whenever they change (or a hub opens).
fn send_server_mod_commands(&mut self) {
let key = self.mods.mods.generation();
let Some(host) = self.lan.as_mut() else {
return;
};
if host.hub.mod_commands_key() == Some(key) {
return;
}
let tree = command_tree(self.mods.mods.server_commands());
host.hub.set_mod_commands(key, tree);
}
/// Lends the levels' chunks to capability `world` for the calls up to
/// [`Game::return_world`], when a running server mod has it.
fn lend_world(&mut self) {
+220 -55
View File
@@ -277,6 +277,10 @@ fn argb(c: i32) -> u32 {
)
}
/// A text style's `0xRRGGBB` colour from a HUD colour (`rgba`).
fn rgb_of(rgba: u32) -> u32 {
(rgba & 0xFF) << 16 | (rgba >> 8 & 0xFF) << 8 | (rgba >> 16 & 0xFF)
}
impl Game<'_> {
/// `Component.translatable`: the selected language (which `lang` layers
/// over `en_us`), the caller's English text last.
@@ -1690,20 +1694,34 @@ impl Game<'_> {
&self,
stack: &ItemStack,
) -> Vec<(horizon_client::text::Text, u32)> {
let e: &Enchantments = &self.res.stations().enchantments;
let props = e.props(&stack.item);
self.stack_tooltip_lines(stack, false)
}
/// `ItemStack.getRarity`'s colour for the name line and a `[name]` link.
fn rarity_color(&self, stack: &ItemStack) -> u32 {
let props = self.res.stations().enchantments.props(&stack.item);
let rarity = horizon_client::item_tooltip::rarity(
stack,
props.map_or("common", |p| p.rarity.as_str()),
);
let color = match rarity {
match rarity {
"uncommon" => rgba(255, 255, 85, 255),
"rare" => rgba(85, 255, 255, 255),
"epic" => rgba(255, 85, 255, 255),
_ => u32::MAX,
};
let name = if let Some(n) = stack.custom_name() {
}
}
/// `ItemStack.getHoverName`: the custom name, a written book's title, the
/// item name component, else the item's or potion's name.
fn stack_hover_name(&self, stack: &ItemStack) -> String {
if let Some(n) = stack.custom_name() {
n.to_owned()
} else if let Some(title) = stack
.data()
.and_then(|d| d.written.as_ref())
.map(|w| w.title.as_str())
.filter(|t| !t.trim().is_empty())
{
title.to_owned()
} else if let Some(n) = stack.item_name() {
n
} else if stack.data().is_some_and(|d| d.ominous_banner) {
@@ -1719,16 +1737,47 @@ impl Game<'_> {
.unwrap_or_else(|| self.pack.names.display_item(&stack.item))
} else {
self.pack.names.display_item(&stack.item)
};
}
}
/// `ItemStack.getTooltipLines`. A `nested` stack is a crossbow's
/// projectile: `ChargedProjectiles.addProjectileTooltip` takes its details
/// without the name, the player and the advanced flag.
fn stack_tooltip_lines(
&self,
stack: &ItemStack,
nested: bool,
) -> Vec<(horizon_client::text::Text, u32)> {
let e: &Enchantments = &self.res.stations().enchantments;
let color = self.rarity_color(stack);
let advanced = !nested && self.options_advanced_tooltips();
let display = horizon_client::item_tooltip::TooltipDisplay::for_stack(stack);
let mut lines = Vec::new();
if display.name_visible(self.screen == Screen::Creative) {
lines.push((horizon_client::text::Text::legacy(&name), color));
if !nested && display.name_visible(self.screen == Screen::Creative) {
// `getStyledHoverName`: a custom name is italic.
let name = self.stack_hover_name(stack);
let name = if stack.custom_name().is_some() {
horizon_client::text::Text::literal(name).italic()
} else {
horizon_client::text::Text::legacy(&name)
};
lines.push((name, color));
}
let translate = |k: &str| self.pack.names.display_get(k);
let push = |lines: &mut Vec<(horizon_client::text::Text, u32)>, s: String, c: u32| {
lines.push((horizon_client::text::Text::legacy(&s), c));
};
let gray = rgba(170, 170, 170, 255);
let item_info = self.res.items().get(&stack.item);
// InstrumentComponent.addToTooltip.
if let Some(text) =
horizon_client::item_tooltip::instrument_line(stack, &display, &translate)
{
push(&mut lines, text, gray);
}
// Bees.addToTooltip.
if let Some(text) = horizon_client::item_tooltip::bees_line(stack, &display, &translate) {
push(&mut lines, text, gray);
}
// ItemContainerContents.addToTooltip.
let hover_name = |s: &ItemStack| {
s.custom_name()
@@ -1743,6 +1792,70 @@ impl Game<'_> {
push(&mut lines, text, u32::MAX);
}
}
// BannerPatternLayers.addToTooltip: up to six layer names.
if display.shows("minecraft:banner_patterns") {
for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) {
let key = self.res.stations().banners.layer_key(layer);
push(
&mut lines,
self.translate(&key, &key),
rgba(170, 170, 170, 255),
);
}
}
// WrittenBookContent.addToTooltip.
for text in horizon_client::item_tooltip::written_book_lines(stack, &display, &translate) {
push(&mut lines, text, gray);
}
// ChargedProjectiles.addToTooltip: each run of equal projectiles, then
// the projectile's own details indented under it.
if display.shows("minecraft:charged_projectiles") {
let charged = stack.data().map_or(&[][..], |d| &d.charged[..]);
for run in charged.chunk_by(|a, b| a.same_item_same_components(b)) {
let projectile = &run[0];
let name = self.stack_hover_name(projectile);
let line = if run.len() == 1 {
// `getDisplayName`: `[name]` in the rarity colour.
let mut shown = horizon_client::text::Text::literal(format!("[{name}]"))
.with_color(rgb_of(self.rarity_color(projectile)));
if projectile.custom_name().is_some() {
shown = shown.italic();
}
horizon_client::text::format_translation(
&self.translate(
"item.minecraft.crossbow.projectile.single",
"Projectile: %s",
),
&[shown],
)
} else {
horizon_client::text::format_translation(
&self.translate(
"item.minecraft.crossbow.projectile.multiple",
"Projectile: %s x %s",
),
&[
horizon_client::text::Text::literal(run.len().to_string()),
horizon_client::text::Text::literal(name),
],
)
};
lines.push((line, u32::MAX));
for (text, c) in self.stack_tooltip_lines(projectile, true) {
// `literal(" ").append(line).withStyle(GRAY)`: the line's
// own colours win over the gray.
let rgb = if c == u32::MAX {
horizon_client::text::GRAY
} else {
rgb_of(c)
};
let indented = horizon_client::text::Text::literal(" ")
.append(text)
.with_color(rgb);
lines.push((indented, u32::MAX));
}
}
}
// Fireworks / FireworkExplosion.addToTooltip.
for text in horizon_client::item_tooltip::firework_lines(stack, &translate) {
push(&mut lines, text, rgba(170, 170, 170, 255));
@@ -1765,6 +1878,17 @@ impl Game<'_> {
};
push(&mut lines, text, c);
}
// The attribute modifiers of the effects (`When Applied:`).
for (text, c) in horizon_client::item_tooltip::potion_modifier_lines(stack, &translate)
{
push(&mut lines, text, c);
}
}
// JukeboxPlayable.addToTooltip.
if let Some(text) =
horizon_client::item_tooltip::jukebox_line(stack, item_info, &display, &translate)
{
push(&mut lines, text, gray);
}
if display.shows("minecraft:trim")
&& let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone())
@@ -1812,16 +1936,12 @@ impl Game<'_> {
);
}
}
// BannerPatternLayers.addToTooltip: up to six layer names.
if display.shows("minecraft:banner_patterns") {
for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) {
let key = self.res.stations().banners.layer_key(layer);
push(
&mut lines,
self.translate(&key, &key),
rgba(170, 170, 170, 255),
);
}
// DyedItemColor.addToTooltip.
if let Some((text, italic)) =
horizon_client::item_tooltip::dyed_line(stack, &display, advanced, &translate)
{
let text = horizon_client::text::Text::legacy(&text);
lines.push((if italic { text.italic() } else { text }, gray));
}
// ItemLore.addToTooltip: after the enchantments, before the attributes
// (ItemStack.addDetailsToTooltip).
@@ -1830,6 +1950,50 @@ impl Game<'_> {
lines.push((text, u32::MAX));
}
}
if display.shows("minecraft:attribute_modifiers") {
// The item's own modifiers, then its enchantments' for each slot
// group (`ItemStack.forEachModifier`).
let mut modifiers = item_info.map(|i| i.modifiers.clone()).unwrap_or_default();
modifiers.extend(e.modifier_rows(stack));
let base = |name: &str, default| {
self.player
.as_ref()
.and_then(|player| {
let key = player.attributes.key(name)?;
let handle = player.attributes.lookup(Some(&key))?;
player
.attributes
.instance(&handle)
.ok()
.map(|value| value.base_value())
})
.unwrap_or(default)
};
let player_base = (!nested).then(|| {
[
base("minecraft:attack_damage", 1.0),
base(
"minecraft:attack_speed",
horizon_client::attack_strength::BASE_ATTACK_SPEED,
),
]
});
for (text, c) in
horizon_client::item_tooltip::attribute_lines(&modifiers, player_base, &translate)
{
push(&mut lines, text, c);
}
}
// ItemStack.UNBREAKABLE_TOOLTIP.
if let Some(text) =
horizon_client::item_tooltip::unbreakable_line(stack, &display, &translate)
{
push(&mut lines, text, rgba(85, 85, 255, 255));
}
// BlockItemStateProperties.addToTooltip.
if let Some(text) = horizon_client::item_tooltip::honey_line(stack, &display, &translate) {
push(&mut lines, text, gray);
}
// Spawner.appendHoverText: what a spawner or trial spawner item spawns.
if display.shows("minecraft:block_entity_data")
&& matches!(
@@ -1853,43 +2017,11 @@ impl Game<'_> {
}
}
}
if display.shows("minecraft:attribute_modifiers")
&& let Some(info) = self.res.items().get(&stack.item)
{
let base = |name: &str, default| {
self.player
.as_ref()
.and_then(|player| {
let key = player.attributes.key(name)?;
let handle = player.attributes.lookup(Some(&key))?;
player
.attributes
.instance(&handle)
.ok()
.map(|value| value.base_value())
})
.unwrap_or(default)
};
let player_base = [
base("minecraft:attack_damage", 1.0),
base(
"minecraft:attack_speed",
horizon_client::attack_strength::BASE_ATTACK_SPEED,
),
];
for (text, c) in horizon_client::item_tooltip::attribute_lines(
&info.modifiers,
Some(player_base),
&translate,
) {
push(&mut lines, text, c);
}
}
if display.shows("minecraft:damage")
&& let Some(info) = self.res.items().get(&stack.item)
&& let Some(info) = item_info
&& info.max_damage > 0
&& stack.damage > 0
&& self.options_advanced_tooltips()
&& advanced
{
push(
&mut lines,
@@ -1901,8 +2033,23 @@ impl Game<'_> {
u32::MAX,
);
}
// ItemStack.addDetailsToTooltipTail: with advanced tooltips the item id
// and how many components the stack has.
if advanced {
let dark_gray = rgba(85, 85, 85, 255);
push(&mut lines, stack.item.to_string(), dark_gray);
let count = horizon_client::item_tooltip::component_count(stack, item_info);
if count > 0 {
let text = self.translate("item.components", "%s component(s)");
push(
&mut lines,
text.replacen("%s", &count.to_string(), 1),
dark_gray,
);
}
}
// ItemStack.OP_NBT_WARNING, for a player with game master permission.
if self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) {
if !nested && self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) {
for (key, fallback) in [
("item.op_warning.line1", "Warning:"),
(
@@ -2105,12 +2252,18 @@ impl Game<'_> {
batch: &mut HudBatch,
layout: &horizon_client::bundle::TooltipLayout,
) {
for (at, stack) in &layout.slots {
for (i, (at, stack)) in layout.slots.iter().enumerate() {
let selected = layout.selected == Some(i);
let sprite = |name: &str| format!("gui/sprites/container/bundle/{name}");
// Each draw takes the atlas on its own: the item's needs `&mut self`.
horizon_client::ui::nine_slice(
batch,
&self.gui.atlas,
"gui/sprites/container/bundle/slot_background",
&sprite(if selected {
"slot_highlight_back"
} else {
"slot_background"
}),
at[0],
at[1],
24.0,
@@ -2120,6 +2273,18 @@ impl Game<'_> {
let stack = stack.clone();
let [x, y] = *at;
self.draw_item(batch, &stack, x + 4.0, y + 4.0);
if selected {
horizon_client::ui::nine_slice(
batch,
&self.gui.atlas,
&sprite("slot_highlight_front"),
x,
y,
24.0,
24.0,
u32::MAX,
);
}
}
let atlas = &self.gui.atlas;
if let Some((at, hidden)) = layout.overflow {
+22
View File
@@ -21,6 +21,22 @@ impl Game<'_> {
draws.extend(self.titles.title(w, h, partial, font, background));
hud_layout::paint(batch, &self.gui.atlas, &draws);
}
/// `Hud.extractSavingIndicator`, under the screens: the option, then the
/// fading "Saving world" text.
pub(super) fn draw_saving_indicator(&self, batch: &mut HudBatch) {
if !self.settings.autosave_indicator {
return;
}
let draws = self.saving_indicator.draw(
batch.width as i32,
batch.height as i32,
self.clock.fraction() as f32,
&self.gui.atlas.font,
Text::literal(self.translate("menu.savingLevel", "Saving world")),
self.settings.text_background(0.0),
);
hud_layout::paint(batch, &self.gui.atlas, &draws);
}
/// The selected stack as `Hud.tick` compares it for the name highlight.
fn held_name(&self) -> Option<HeldName> {
let stack = self.inventory.get(self.selected)?.as_ref()?;
@@ -44,6 +60,12 @@ impl Game<'_> {
/// The title, action bar and selected-item parts of `Hud.tick`.
pub(super) fn tick_hud(&mut self) {
self.titles.tick();
// `MinecraftServer.isCurrentlySaving` of single player's server.
let saving = self
.integrated
.as_ref()
.map_or(self.autosaving, |server| server.is_saving());
self.saving_indicator.tick(saving);
let held = self.held_name();
self.tool_highlight
.tick(held, f64::from(self.settings.notification_display_time));
+1 -2
View File
@@ -70,8 +70,7 @@ impl Game<'_> {
/// One ordinary click on a game slot. False when nothing took it.
pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool {
if self.remote.is_some() {
let ordinal = super::remote::input_ordinal(input);
return self.remote_slot_click(slot, button as i8, ordinal);
return self.remote_menu_ops(&[(Some(slot), button, input)]);
}
if !self.menu_click(Some(slot), button, input) {
return false;
+2 -1
View File
@@ -118,8 +118,9 @@ impl Style {
(x, y, w): (f32, f32, f32),
label: &Text,
hover: bool,
active: bool,
) {
ui::button(batch, atlas, x, y, w, 20.0, label, true, hover);
ui::button(batch, atlas, x, y, w, 20.0, label, active, hover);
}
pub fn slider(
&self,
+32 -1
View File
@@ -468,6 +468,10 @@ fn max_workers() -> u32 {
}
impl Item {
/// False for a setting whose system is not in Horizon yet (`Opt::available`).
fn available(self) -> bool {
!matches!(self, Item::Vanilla(o) if !o.available())
}
/// On/off settings and their value.
pub fn switch(self, s: &Settings) -> Option<bool> {
let g = &s.horizon;
@@ -510,6 +514,9 @@ impl Item {
}
}
pub fn set_slider(self, s: &mut Settings, v: f32) {
if !self.available() {
return;
}
match self {
Item::Vanilla(o) => o.set_slider(s, v),
Item::Horizon(h) => h.set_slider(s, v),
@@ -517,6 +524,9 @@ impl Item {
self.touched(s);
}
pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) {
if !self.available() {
return;
}
match self {
Item::Vanilla(o) => o.cycle(s, back, framebuffer),
Item::Horizon(h) => h.cycle(s, back),
@@ -689,6 +699,7 @@ impl GraphicsUi {
})
.collect();
let mut index = 0;
let mut tooltip = None;
for wd in &widgets {
let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, 20.0)
&& (!wd.list || (cursor.1 >= top && cursor.1 < bottom));
@@ -700,6 +711,13 @@ impl GraphicsUi {
continue;
}
let label = item.label(s);
let live = item.available();
if hover && !live {
tooltip = Some(atlas.font.split(
&Text::literal("This feature is not yet available in Horizon."),
170.0,
));
}
match item.slider(s) {
Some(value) => STYLE.slider(
batch,
@@ -709,7 +727,14 @@ impl GraphicsUi {
value,
hover || self.dragging == Some(item),
),
None => STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &label, hover),
None => STYLE.button(
batch,
atlas,
(wd.x, wd.y, wd.w),
&label,
hover && live,
live,
),
}
STYLE.description(
batch,
@@ -732,6 +757,7 @@ impl GraphicsUi {
(wd.x, wd.y, wd.w),
&Text::literal(label),
hover,
true,
);
}
}
@@ -751,6 +777,9 @@ impl GraphicsUi {
Level::Advanced => "Graphics: Advanced",
};
STYLE.title(batch, atlas, &Text::literal(title));
if let Some(lines) = tooltip {
ui::tooltip(batch, atlas, &lines, cursor);
}
}
/// A press (or a drag with `drag`) at `(x, y)`.
pub fn click(
@@ -788,6 +817,8 @@ impl GraphicsUi {
}
return match wd.target {
Target::Button(action) => vec![Action::ButtonClick, action],
// A disabled control does nothing: no sound, no preset change.
Target::Item(item) if !item.available() => Vec::new(),
Target::Item(item) => {
if item.slider(s).is_some() {
self.dragging = Some(item);
+47
View File
@@ -191,6 +191,53 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec<GuiDraw> {
out
}
/// The saving indicator: `Hud.tickAutosaveIndicator` fades a value towards 1
/// while the server is saving and `extractSavingIndicator` draws the text.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SavingIndicator {
last: f32,
value: f32,
}
impl SavingIndicator {
/// `Hud.tickAutosaveIndicator`: `Mth.lerp(0.2F, value, saving ? 1 : 0)`.
pub fn tick(&mut self, saving: bool) {
self.last = self.value;
self.value += (if saving { 1.0 } else { 0.0 } - self.value) * 0.2;
}
/// `Hud.extractSavingIndicator` without the option check: the text in the
/// bottom right corner.
pub fn draw(
&self,
w: i32,
h: i32,
partial: f32,
font: &Font,
label: Text,
background: u32,
) -> Vec<GuiDraw> {
let mut out = Vec::new();
if self.value <= 0.0 && self.last <= 0.0 {
return out;
}
let fade = (self.last + (self.value - self.last) * partial).clamp(0.0, 1.0);
let alpha = (255.0 * fade).floor() as u32;
if alpha > 0 {
let label_width = width(font, &label);
let color = crate::hud_layout::argb(alpha, 255, 255, 255);
text_with_backdrop(
&mut out,
label,
w - label_width - 5,
h - 9 - 5,
label_width,
color,
background,
);
}
out
}
}
/// Titles and the action bar: `Hud.title`, `subtitle`, `titleTime`, the
/// fade times and `overlayMessageString` / `overlayMessageTime`.
#[derive(Clone, Debug, PartialEq)]
+17
View File
@@ -52,6 +52,8 @@ pub struct StackData {
pub pot_decorations: Option<Box<[Option<ItemStack>; 4]>>,
/// `minecraft:bundle_contents`.
pub bundle_contents: Vec<ItemStack>,
/// `BundleContents.selectedItem`: runtime only, never saved or sent.
pub bundle_selected: BundleSelected,
/// `minecraft:suspicious_stew_effects`: (effect id, duration).
pub stew_effects: Vec<(Arc<str>, i32)>,
/// `minecraft:map_post_processing`: 0 lock, 1 scale.
@@ -60,6 +62,20 @@ pub struct StackData {
/// max stack size...), kept as their saved values in key order.
pub other: Vec<(String, Tag)>,
}
/// A bundle's selected item index (-1: none). Like vanilla's
/// `BundleContents.equals` it is left out when stacks are compared.
#[derive(Clone, Copy, Debug)]
pub struct BundleSelected(pub i32);
impl Default for BundleSelected {
fn default() -> Self {
Self(-1)
}
}
impl PartialEq for BundleSelected {
fn eq(&self, _: &Self) -> bool {
true
}
}
/// The components `components_tag` writes from modelled fields.
const MODELLED: &[&str] = &[
"minecraft:banner_patterns",
@@ -791,6 +807,7 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
Arc::from(t.get("pattern").and_then(string)?.as_str()),
))
}),
bundle_selected: BundleSelected::default(),
other: Vec::new(),
};
let mut data = data;
+1
View File
@@ -653,6 +653,7 @@ pub fn tag_json(tag: &Tag) -> Value {
/// The resolver's view of a client stack: its item, count and component patch.
pub fn stack_view(stack: &crate::items::ItemStack) -> StackView {
let mut view = StackView::new(&stack.item, stack.count as i32);
view.bundle_selected = stack.data().map_or(-1, |d| d.bundle_selected.0);
if let Some(Tag::Compound(c)) = crate::item_data::components_tag(stack.damage, stack.data()) {
for (k, v) in &c {
let key = k.to_string_lossy();
+266 -45
View File
@@ -108,6 +108,32 @@ fn modifier_line(
)
}
/// `Attribute.getStyle`: the colour of a line for an attribute whose value
/// rises or falls. Gravity, scale and the waypoint ranges are neutral, burning
/// time and fall damage are negative, every other attribute is positive.
fn attribute_color(attribute: &str, rises: bool) -> u32 {
let (blue, red) = (rgba(85, 85, 255, 255), rgba(255, 85, 85, 255));
match attribute {
"burning_time" | "fall_damage_multiplier" => {
if rises {
red
} else {
blue
}
}
"gravity" | "scale" | "waypoint_transmit_range" | "waypoint_receive_range" => {
rgba(170, 170, 170, 255)
}
_ => {
if rises {
blue
} else {
red
}
}
}
}
/// `ItemStack.addAttributeTooltips`: slot groups, colors and optional player
/// attack damage/speed bases. Recipe search has no player context.
pub fn attribute_lines(
@@ -150,10 +176,8 @@ pub fn attribute_lines(
) {
let (line, color) = if base.is_some() {
(format!(" {line}"), rgba(0, 170, 0, 255))
} else if *amount > 0.0 {
(line, rgba(85, 85, 255, 255))
} else {
(line, rgba(255, 85, 85, 255))
(line, attribute_color(path, *amount > 0.0))
};
lines.push((line, color));
}
@@ -231,6 +255,235 @@ pub fn rarity<'a>(stack: &ItemStack, default: &'a str) -> &'a str {
}
}
fn is_beehive(path: &str) -> bool {
matches!(path, "beehive" | "bee_nest")
}
/// `InstrumentComponent.addToTooltip`: the instrument's description. A goat
/// horn without the component has the item's default, the ponder horn.
pub fn instrument_line(
stack: &ItemStack,
display: &TooltipDisplay,
translate: &dyn Fn(&str) -> Option<String>,
) -> Option<String> {
if !display.shows("minecraft:instrument") {
return None;
}
let id = match stack.data().and_then(|d| d.other("minecraft:instrument")) {
Some(Tag::String(id)) => id.to_string_lossy(),
// An inline instrument carries its own description.
Some(inline) => {
return inline
.get("description")
.map(|d| crate::entity_nbt::name_text(d).plain());
}
None if &*stack.item == "minecraft:goat_horn" => "minecraft:ponder_goat_horn".to_owned(),
None => return None,
};
let key = format!("instrument.{}", id.replacen(':', ".", 1));
Some(translate(&key).unwrap_or(key))
}
/// `Bees.addToTooltip`: how many bees a hive item holds (a hive item without
/// the component has the item's default, none).
pub fn bees_line(
stack: &ItemStack,
display: &TooltipDisplay,
translate: &dyn Fn(&str) -> Option<String>,
) -> Option<String> {
if !display.shows("minecraft:bees") {
return None;
}
let bees = match stack.data().and_then(|d| d.other("minecraft:bees")) {
Some(Tag::List(bees)) => bees.len(),
Some(_) => return None,
None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0,
None => return None,
};
let text =
translate("container.beehive.bees").unwrap_or_else(|| "container.beehive.bees".into());
Some(
text.replacen("%s", &bees.to_string(), 1)
.replacen("%s", "3", 1),
)
}
/// `BlockItemStateProperties.addToTooltip`: a hive item's honey level (a hive
/// item without the component has the item's default, 0).
pub fn honey_line(
stack: &ItemStack,
display: &TooltipDisplay,
translate: &dyn Fn(&str) -> Option<String>,
) -> Option<String> {
if !display.shows("minecraft:block_state") {
return None;
}
let level = match stack.data().and_then(|d| d.other("minecraft:block_state")) {
Some(Tag::Compound(state)) => {
match state.get(&horizon_world::nbt::JavaString::from("honey_level")) {
Some(Tag::String(level)) => level.to_string_lossy().parse::<u32>().ok()?,
_ => return None,
}
}
Some(_) => return None,
None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0,
None => return None,
};
let text =
translate("container.beehive.honey").unwrap_or_else(|| "container.beehive.honey".into());
Some(
text.replacen("%s", &level.to_string(), 1)
.replacen("%s", "5", 1),
)
}
/// `WrittenBookContent.addToTooltip`: "by <author>" and the generation.
pub fn written_book_lines(
stack: &ItemStack,
display: &TooltipDisplay,
translate: &dyn Fn(&str) -> Option<String>,
) -> Vec<String> {
let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned());
let Some(book) = stack
.data()
.and_then(|d| d.written.as_ref())
.filter(|_| display.shows("minecraft:written_book_content"))
else {
return Vec::new();
};
let mut lines = Vec::new();
if !book.author.trim().is_empty() {
lines.push(
crate::text::format_translation(
&text("book.byAuthor"),
&[crate::text::Text::literal(&book.author)],
)
.plain(),
);
}
lines.push(text(&format!("book.generation.{}", book.generation)));
lines
}
/// `JukeboxPlayable.addToTooltip`: the song's description.
pub fn jukebox_line(
stack: &ItemStack,
info: Option<&ItemInfo>,
display: &TooltipDisplay,
translate: &dyn Fn(&str) -> Option<String>,
) -> Option<String> {
if !display.shows("minecraft:jukebox_playable") {
return None;
}
let song = match stack
.data()
.and_then(|d| d.other("minecraft:jukebox_playable"))
{
Some(Tag::String(song)) => song.to_string_lossy(),
// An inline song carries its own description.
Some(inline) => {
return inline
.get("description")
.map(|d| crate::entity_nbt::name_text(d).plain());
}
None => info?.jukebox_song.clone()?,
};
let key = format!("jukebox_song.{}", song.replacen(':', ".", 1));
Some(translate(&key).unwrap_or(key))
}
/// `DyedItemColor.addToTooltip`: "Dyed" (italic, the flag), or with advanced
/// tooltips the colour's hex code.
pub fn dyed_line(
stack: &ItemStack,
display: &TooltipDisplay,
advanced: bool,
translate: &dyn Fn(&str) -> Option<String>,
) -> Option<(String, bool)> {
let rgb = stack.data()?.dyed_color?;
if !display.shows("minecraft:dyed_color") {
return None;
}
let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned());
Some(if advanced {
let hex = format!("#{:06X}", rgb & 0xFF_FFFF);
(text("item.color").replacen("%s", &hex, 1), false)
} else {
(text("item.dyed"), true)
})
}
/// `ItemStack.UNBREAKABLE_TOOLTIP`.
pub fn unbreakable_line(
stack: &ItemStack,
display: &TooltipDisplay,
translate: &dyn Fn(&str) -> Option<String>,
) -> Option<String> {
(stack.data()?.other("minecraft:unbreakable").is_some()
&& display.shows("minecraft:unbreakable"))
.then(|| translate("item.unbreakable").unwrap_or_else(|| "item.unbreakable".into()))
}
/// `PotionContents.addPotionTooltip`'s attribute block: an empty line, "When
/// Applied:" and the modifiers of the potion's effects (blue for a gain, red
/// for a loss); nothing for a potion whose effects add none.
pub fn potion_modifier_lines(
stack: &ItemStack,
translate: &dyn Fn(&str) -> Option<String>,
) -> Vec<(String, u32)> {
if !is_potion_item(&stack.item) {
return Vec::new();
}
let applied: Vec<(String, u32)> = stack
.potion()
.and_then(crate::brewing::potion)
.into_iter()
.flat_map(|p| p.effects.iter())
.filter_map(|(effect, _, amplifier)| {
let (attribute, amount, operation) = effect_modifier(effect)?;
let amount = amount * (*amplifier + 1) as f64;
let line = modifier_line(translate, attribute, amount, operation, false)?;
let color = if amount > 0.0 {
rgba(85, 85, 255, 255)
} else {
rgba(255, 85, 85, 255)
};
Some((line, color))
})
.collect();
if applied.is_empty() {
return applied;
}
let mut lines = vec![
(String::new(), u32::MAX),
(
translate("potion.whenDrank").unwrap_or_else(|| "potion.whenDrank".into()),
rgba(170, 0, 170, 255),
),
];
lines.extend(applied);
lines
}
/// `ItemStack.components.size()`: the item's default components with the
/// stack's own changes applied.
pub fn component_count(stack: &ItemStack, info: Option<&ItemInfo>) -> usize {
let mut keys: std::collections::HashSet<String> = info
.map(|i| i.components.iter().cloned().collect())
.unwrap_or_default();
if let Some(Tag::Compound(patch)) = crate::item_data::components_tag(stack.damage, stack.data())
{
for key in patch.keys() {
let key = key.to_string_lossy();
match key.strip_prefix('!') {
Some(removed) => keys.remove(removed),
None => keys.insert(key),
};
}
}
keys.len()
}
/// The lines of `stack` below its name that its components give, in
/// `ItemStack.addDetailsToTooltip` order.
pub fn detail_lines(
@@ -265,19 +518,9 @@ pub fn detail_lines(
))
));
}
// BeehiveBlock: the block state components of the item.
if path == "beehive" {
lines.push(
text("container.beehive.bees")
.replacen("%s", "0", 1)
.replacen("%s", "3", 1),
);
lines.push(
text("container.beehive.honey")
.replacen("%s", "0", 1)
.replacen("%s", "5", 1),
);
}
let display = TooltipDisplay::for_stack(stack);
lines.extend(bees_line(stack, &display, translate));
lines.extend(honey_line(stack, &display, translate));
let data = stack.data();
// PotDecorations.addToTooltip.
if let Some(sherds) = data
@@ -303,32 +546,13 @@ pub fn detail_lines(
.into_iter()
.map(|l| l.0),
);
let applied: Vec<String> = stack
.potion()
.and_then(crate::brewing::potion)
.into_iter()
.flat_map(|p| p.effects.iter())
.filter_map(|(effect, _, amplifier)| {
let (attribute, amount, operation) = effect_modifier(effect)?;
modifier_line(
translate,
attribute,
amount * (*amplifier + 1) as f64,
operation,
false,
)
})
.collect();
if !applied.is_empty() {
lines.push(String::new());
lines.push(text("potion.whenDrank"));
lines.extend(applied);
}
}
// JukeboxPlayable.addToTooltip: the song's description.
if path.starts_with("music_disc_") {
lines.push(text(&format!("item.minecraft.{path}.desc")));
lines.extend(
potion_modifier_lines(stack, translate)
.into_iter()
.map(|l| l.0),
);
}
lines.extend(jukebox_line(stack, info, &display, translate));
// Trim.addToTooltip.
if let Some((material, pattern)) = data.and_then(|d| d.trim.as_ref()) {
let short = |s: &str| s.trim_start_matches("minecraft:").to_owned();
@@ -342,10 +566,7 @@ pub fn detail_lines(
text(&format!("trim_material.minecraft.{}", short(material)))
));
}
// DyedItemColor.addToTooltip (without advanced tooltips).
if data.is_some_and(|d| d.dyed_color.is_some()) {
lines.push(text("item.dyed"));
}
lines.extend(dyed_line(stack, &display, false, translate).map(|l| l.0));
if let Some(info) = info {
lines.extend(
attribute_lines(&info.modifiers, None, translate)
+6
View File
@@ -131,6 +131,8 @@ pub struct ItemInfo {
pub block_transformer: Option<String>,
/// Has a default `bundle_contents` (the bundles, `BundleItem`).
pub bundle: bool,
/// The ids of the item's default components (its prototype's keys).
pub components: Vec<String>,
}
/// `Item.Properties.craftRemainder` (not a data component, so not in the
/// default-component report): what an item leaves in the grid when crafted with.
@@ -650,6 +652,10 @@ impl Items {
cushion_color: c["minecraft:cushion/color"].as_str().map(str::to_owned),
block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned),
bundle: c.get("minecraft:bundle_contents").is_some(),
components: c
.as_object()
.map(|c| c.keys().cloned().collect())
.unwrap_or_default(),
crafting_remainder: CRAFT_REMAINDERS
.iter()
.find(|(item, _)| *item == name)
+1
View File
@@ -66,6 +66,7 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> {
"sculk_catalyst" => "minecraft:sculk_catalyst",
"sculk_shrieker" => "minecraft:sculk_shrieker",
"crafter" => "minecraft:crafter",
"potent_sulfur" => "minecraft:potent_sulfur",
"chiseled_bookshelf" => "minecraft:chiseled_bookshelf",
"trial_spawner" => "minecraft:trial_spawner",
"vault" => "minecraft:vault",
+53 -10
View File
@@ -86,6 +86,18 @@ impl CommandTree {
/// The ClientboundCommandsPacket for a player with `level` permissions.
pub fn packet(&self, level: u8, dedicated: bool, builtin: &Builtin) -> Commands {
self.packet_with(level, dedicated, builtin, &Value::Null)
}
/// [`CommandTree::packet`] with more commands after vanilla's: `extra`
/// is a root in the report's format (server mods' commands).
pub fn packet_with(
&self,
level: u8,
dedicated: bool,
builtin: &Builtin,
extra: &Value,
) -> Commands {
let mut nodes = vec![Node {
name: String::new(),
kind: 0,
@@ -99,16 +111,18 @@ impl CommandTree {
let suggestions: HashMap<&str, &'static str> = SUGGESTIONS.iter().copied().collect();
let mut paths: HashMap<Vec<String>, usize> = HashMap::new();
paths.insert(Vec::new(), 0);
fill(
&self.root,
0,
&mut Vec::new(),
level,
dedicated,
&suggestions,
&mut nodes,
&mut paths,
);
for root in [&self.root, extra] {
fill(
root,
0,
&mut Vec::new(),
level,
dedicated,
&suggestions,
&mut nodes,
&mut paths,
);
}
// enumerateNodes: breadth first from the root, each node's children
// (in registration order) then its redirect target.
let mut ids = vec![None; nodes.len()];
@@ -365,4 +379,33 @@ mod tests {
);
assert!(op.nodes[3].restricted);
}
#[test]
fn server_mods_commands_follow_vanillas() {
let report: Value = serde_json::from_str(
r#"{"type":"root","children":{"me":{"type":"literal","children":{"action":{"type":"argument","parser":"minecraft:message","executable":true}}}}}"#,
)
.unwrap();
let mods: Value = serde_json::from_str(
r#"{"type":"root","children":{"beacon":{"type":"literal","executable":true,"children":{
"height":{"type":"argument","parser":"brigadier:integer","properties":{"min":1,"max":64},"executable":true}}}}}"#,
)
.unwrap();
let tree = CommandTree { root: report };
let packet = tree.packet_with(0, true, &Builtin::default(), &mods);
let names: Vec<_> = packet.nodes.iter().map(|n| n.name.as_str()).collect();
assert_eq!(names, ["", "me", "beacon", "action", "height"]);
let beacon = &packet.nodes[2];
assert!(beacon.executable && !beacon.restricted);
assert_eq!(beacon.children, [4]);
let height = packet.nodes[4].parser.as_ref().unwrap();
assert_eq!(height.1, vec![3, 0, 0, 0, 1, 0, 0, 0, 64]);
// No mods: vanilla's tree as it is.
assert_eq!(
tree.packet_with(0, true, &Builtin::default(), &Value::Null)
.nodes
.len(),
3
);
}
}
+66 -18
View File
@@ -36,6 +36,30 @@ impl Hub {
/// ClientboundSoundPacket for a sound event name (an inline event when
/// the registry does not know it).
pub fn sound_packet(
&self,
name: &str,
at: [f64; 3],
volume: f32,
pitch: f32,
source: i32,
seed: i64,
) -> C {
let sound = match self.sync.id("minecraft:sound_event", name) {
Some(id) => (id, None),
None => (-1, Some((name.to_owned(), None))),
};
C::Sound(play::Sound {
sound,
source,
x: (at[0] * 8.0) as i32,
y: (at[1] * 8.0) as i32,
z: (at[2] * 8.0) as i32,
volume,
pitch,
seed,
})
}
pub fn sound(
&self,
name: &str,
@@ -45,20 +69,7 @@ impl Hub {
source: i32,
except: Option<u32>,
) {
let sound = match self.sync.id("minecraft:sound_event", name) {
Some(id) => (id, None),
None => (-1, Some((name.to_owned(), None))),
};
let packet = C::Sound(play::Sound {
sound,
source,
x: (at[0] * 8.0) as i32,
y: (at[1] * 8.0) as i32,
z: (at[2] * 8.0) as i32,
volume,
pitch,
seed: self.ticks as i64,
});
let packet = self.sound_packet(name, at, volume, pitch, source, self.ticks as i64);
self.broadcast_near(at, f64::from(volume.max(1.0)) * 16.0, &packet, except);
}
@@ -120,12 +131,13 @@ impl Hub {
);
}
/// `ServerPlayer.crit`: send the victim's animation to the players tracking
/// the attacker and the attacker themselves (`sendToTrackingPlayersAndSelf`).
pub fn critical_hit(&self, attacker: i32, target: i32) {
/// `ServerPlayer.crit` (`magicCrit` when `magic`): send the victim's
/// animation to the players tracking the attacker and the attacker
/// themselves (`sendToTrackingPlayersAndSelf`).
pub fn critical_hit(&self, attacker: i32, target: i32, magic: bool) {
let body = C::Animate(play::Animate {
id: target,
action: 1,
action: if magic { 2 } else { 1 },
})
.encode();
for g in self.guests.iter().filter(|g| {
@@ -421,6 +433,42 @@ impl Hub {
drops
}
/// `AbstractContainerMenu.setSelectedBundleItemIndex` on the guest's open
/// menu: a container's own slots, or the inventory's. A bundle's selection
/// lives on the server's stack until the click that takes from it.
pub fn select_bundle_item(&mut self, conn: u32, slot: usize, index: i32, world: &mut World) {
let Some(g) = self.guests.iter_mut().find(|g| g.conn == conn) else {
return;
};
let open = g.menu.as_ref().map(|m| (m.size, m.slots));
let mut items = match open {
Some((size, source)) if slot < size => source.read(world, g),
_ => None,
};
let stack = match open {
Some((size, _)) if slot < size => items
.as_mut()
.and_then(|items| items.get_mut(slot))
.and_then(Option::as_mut),
Some((size, _)) => g
.inventory
.get_mut(player_slot(slot - size))
.and_then(Option::as_mut),
None => match slot {
9..=35 => g.inventory.get_mut(slot).and_then(Option::as_mut),
36..=44 => g.inventory.get_mut(slot - 36).and_then(Option::as_mut),
45 => g.offhand.as_mut(),
_ => None,
},
};
if let Some(stack) = stack {
crate::bundle::toggle_selected(stack, index);
}
if let (Some((_, source)), Some(items)) = (open, items) {
source.write(world, g, items);
}
}
/// A click on the inventory menu (window 0) the game applied itself
/// (the crafting grid): the client is corrected like after any click.
pub fn inventory_clicked(
+10 -4
View File
@@ -611,8 +611,9 @@ pub struct Viewer<'a> {
}
/// One entity as this tick's range checks read it: where it is
/// horizontally, its id, its type's tracking range in chunks and the chunk
/// it is in (an index into the tick's chunks).
/// horizontally, its id, its tracking range in blocks (scaled by
/// `entity-broadcast-range-percentage`) and the chunk it is in (an index
/// into the tick's chunks).
#[derive(Clone, Copy)]
struct Probe {
x: f64,
@@ -627,7 +628,7 @@ struct Probe {
/// each of the tick's chunks whether the client has it (0: not looked up
/// yet, 1: no, 2: yes), so each chunk is looked up once per client.
fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool {
let range = f64::from(p.range.min(v.view_distance) * 16);
let range = f64::from(p.range.min(v.view_distance * 16));
let (dx, dz) = (v.position[0] - p.x, v.position[2] - p.z);
dx * dx + dz * dz <= range * range && {
let held = &mut held[p.chunk as usize];
@@ -641,6 +642,9 @@ fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool {
/// One level's tracked entities (ChunkMap.entityMap).
#[derive(Default)]
pub struct Entities {
/// `entity-broadcast-range-percentage` (None: 100), which scales every
/// type's tracking range (MinecraftServer.getScaledTrackingDistance).
pub range_percent: Option<i32>,
states: crate::fast_hash::FxHashMap<i32, ServerEntity>,
/// The level tick, stamped on every entity still in the level.
tick: u32,
@@ -732,7 +736,9 @@ impl Entities {
x: e.position[0],
z: e.position[2],
id: e.id,
range: s.range,
range: self
.range_percent
.map_or(s.range * 16, |p| p * (s.range * 16) / 100),
chunk,
});
}
+177 -14
View File
@@ -21,7 +21,7 @@ use crate::{
use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
use horizon_protocol::ids::play::clientbound as ids;
use horizon_protocol::{
entity_data::{Value, serializer},
entity_data::{Particle, ParticleData, Value, serializer},
packets::play::{self, Clientbound as C, Serverbound as S},
text::{literal, translatable},
};
@@ -87,6 +87,29 @@ pub struct HostState {
pub living_flags: i8,
/// The bed the host sleeps in (`LivingEntity.SLEEPING_POS`).
pub bed: Option<[i32; 3]>,
pub body: BodyFlags,
}
/// What the other players see of a player's body besides sneaking and
/// sprinting: the pose and the rest of `Entity.DATA_SHARED_FLAGS_ID`.
#[derive(Clone, Copy, Debug, Default)]
pub struct BodyFlags {
/// `Entity.isFallFlying`: gliding with elytra.
pub gliding: bool,
/// `Entity.isSwimming` (the swimming flag).
pub swimming: bool,
/// The swimming pose of a player crawling under a block.
pub crawling: bool,
/// The crouching pose, held without sneaking under a low ceiling.
pub crouching: bool,
/// `LivingEntity.isAutoSpinAttack`: Riptide's spin.
pub spin_attack: bool,
/// `Entity.isOnFire`.
pub on_fire: bool,
/// `Entity.isInvisible`: the invisibility effect.
pub invisible: bool,
/// The glowing effect.
pub glowing: bool,
}
/// Everything the hub needs from the game for one tick.
@@ -168,6 +191,8 @@ pub struct Hub {
level_sync: std::collections::HashMap<String, LevelSync>,
/// Operators and their permission levels (dedicated servers).
pub ops: std::collections::HashMap<u128, u8>,
/// `entity-broadcast-range-percentage` (dedicated servers).
pub entity_range_percent: i32,
chat_type: i32,
dimension_type: i32,
clock_ids: Vec<i32>,
@@ -177,6 +202,9 @@ pub struct Hub {
entities: std::collections::HashMap<String, Entities>,
/// What one tick of entity tracking sends each guest, kept between ticks.
entity_out: Vec<Vec<Vec<u8>>>,
/// Server mods' commands, a root in the commands report's format, sent
/// after vanilla's; the key the game last set them for.
mod_commands: (serde_json::Value, Option<u64>),
}
fn string(s: &str) -> Tag {
@@ -332,6 +360,7 @@ impl Hub {
ticking: (20.0, false),
stepping: 0,
ops: Default::default(),
entity_range_percent: 100,
weather: (false, 0.0, 0.0),
level_sync: Default::default(),
chat_type,
@@ -341,6 +370,7 @@ impl Hub {
entity_types: Default::default(),
entities: Default::default(),
entity_out: Vec::new(),
mod_commands: (serde_json::Value::Null, None),
teams: Vec::new(),
}
}
@@ -849,13 +879,36 @@ impl Hub {
}
}
/// The key [`Hub::set_mod_commands`] last had: the game compares it
/// with its server mods' each tick.
pub fn mod_commands_key(&self) -> Option<u64> {
self.mod_commands.1
}
/// Server mods' commands changed: every player gets their tree again.
pub fn set_mod_commands(&mut self, key: u64, commands: serde_json::Value) {
let resend = self.mod_commands.0 != commands;
self.mod_commands = (commands, Some(key));
if resend {
for i in 0..self.guests.len() {
if self.guests[i].placed {
self.send_commands(i);
}
}
}
}
/// Commands.sendCommands: the command tree for this player.
fn send_commands(&self, i: usize) {
let g = &self.guests[i];
let packet = match &self.sync.commands {
Some(tree) => {
let dedicated = self.config.dedicated && !self.config.integrated;
tree.packet(g.permission, dedicated, &self.sync.builtin)
tree.packet_with(
g.permission,
dedicated,
&self.sync.builtin,
&self.mod_commands.0,
)
}
None => play::Commands {
nodes: vec![play::CommandNode {
@@ -1500,6 +1553,49 @@ impl Hub {
// ---- entities ------------------------------------------------------
/// `LivingEntity.updateSynchronizedMobEffectParticles`: DATA_EFFECT_PARTICLES
/// (10) and DATA_EFFECT_AMBIENCE_ID (11) for the visible `effects`, as
/// (effect, ambient). The entries are left out when there is nothing to
/// show, which is their default.
pub fn effect_meta<'a>(
&self,
effects: impl IntoIterator<Item = (&'a str, bool)>,
) -> Vec<(u8, i32, Value)> {
let mut particles = Vec::new();
let mut all_ambient = true;
for (effect, ambient) in effects {
let effect = effect.trim_start_matches("minecraft:");
// MobEffect.particleFactory: the omens have their own particles,
// the others an entity effect in their colour (faint if ambient).
let (name, data) = match effect {
"trial_omen" | "raid_omen" => (effect, None),
_ => {
let Some(def) = crate::brewing::effect(effect) else {
continue;
};
let alpha = if ambient { 38 } else { 255 };
let argb = (alpha << 24) | def.color as i32;
("entity_effect", Some(ParticleData::Color(argb)))
}
};
let Some(id) =
self.registry_id("minecraft:particle_type", &format!("minecraft:{name}"))
else {
continue;
};
particles.push(Particle { id, data });
all_ambient &= ambient;
}
if particles.is_empty() {
return Vec::new();
}
let mut meta = vec![(10, serializer::PARTICLES, Value::Particles(particles))];
if all_ambient {
meta.push((11, serializer::BOOLEAN, Value::Bool(true)));
}
meta
}
fn player_state(
&self,
id: i32,
@@ -1507,21 +1603,29 @@ impl Hub {
position: [f64; 3],
rot: (f32, f32, f32),
on_ground: bool,
flags: (bool, bool, bool, bool),
flags: (bool, bool, bool),
body: BodyFlags,
living_flags: i8,
bed: Option<[i32; 3]>,
skin: u8,
health: f32,
equipment: Vec<(u8, Option<horizon_protocol::item::Stack>)>,
attributes: Vec<play::AttributeSnapshot>,
effects: &[EffectInstance],
) -> EntityState {
let (sneaking, sprinting, gliding, sleeping) = flags;
let shared = shared_flags(sneaking, sprinting, gliding);
let (sneaking, sprinting, sleeping) = flags;
let shared = shared_flags(sneaking, sprinting, &body);
// Player.getDesiredPose (and updatePlayerPose's crawl): sleeping,
// swimming, gliding, Riptide's spin, crouching.
let pose = if sleeping {
2
} else if gliding {
} else if body.swimming || body.crawling {
3
} else if body.gliding {
1
} else if sneaking {
} else if body.spin_attack {
4
} else if sneaking || body.crouching {
5
} else {
0
@@ -1547,6 +1651,14 @@ impl Hub {
if skin != 0 {
meta.push((16, serializer::BYTE, Value::Byte(skin as i8)));
}
meta.extend(
self.effect_meta(
effects
.iter()
.filter(|e| e.visible)
.map(|e| (e.id, e.ambient)),
),
);
EntityState {
id,
uuid,
@@ -1559,7 +1671,11 @@ impl Hub {
velocity: [0.0; 3],
data: 0,
meta,
defaults: Vec::new(),
// The effect swirls go back to none.
defaults: vec![
(10, serializer::PARTICLES, Value::Particles(Vec::new())),
(11, serializer::BOOLEAN, Value::Bool(false)),
],
equipment,
attributes,
precise: false,
@@ -1607,13 +1723,15 @@ impl Hub {
h.position,
(h.yaw, h.pitch, h.head_yaw),
h.on_ground,
(h.sneaking, h.sprinting, false, h.bed.is_some()),
(h.sneaking, h.sprinting, h.bed.is_some()),
h.body,
h.living_flags,
h.bed,
0x7F,
h.health,
equipment,
h.attributes.clone(),
&[],
));
}
let placed: Vec<usize> = (0..self.guests.len())
@@ -1639,7 +1757,8 @@ impl Hub {
g.position,
(g.yaw, g.pitch, g.head_yaw),
g.on_ground,
(g.sneaking, g.sprinting, g.fall_flying, g.sleeping),
(g.sneaking, g.sprinting, g.sleeping),
guest_body(g),
g.living_flags,
g.bed,
g.info.model_customisation,
@@ -1649,6 +1768,7 @@ impl Hub {
.as_ref()
.map(|m| super::attributes::syncable(&m.attributes))
.unwrap_or_default(),
&g.effects.list,
)
})
.collect();
@@ -1678,6 +1798,7 @@ impl Hub {
out,
})
.collect();
level.range_percent = Some(self.entity_range_percent);
let (types, sync) = (&mut self.entity_types, &self.sync);
level.tick(&entities, &self.riding, &mut viewers, |kind| {
entity_type(types, sync, kind)
@@ -1798,7 +1919,7 @@ impl Hub {
// too, so the sprint a hit stops (Player.causeExtraKnockback) stops
// on its client.
let g = &mut self.guests[i];
let shared = shared_flags(g.sneaking, g.sprinting, g.fall_flying);
let shared = shared_flags(g.sneaking, g.sprinting, &guest_body(g));
if shared != g.sent_shared {
g.sent_shared = shared;
g.send(&C::SetEntityData(play::SetEntityData {
@@ -2043,6 +2164,20 @@ impl Hub {
S::Chat(c) => self.handle_chat(i, c, events),
S::ChatAck(p) => self.chat_ack(i, p.offset, events),
S::ChatSessionUpdate(p) => self.chat_session_update(i, p, events),
// handlePlayerAction (a dig starting, stopping or finishing) is the
// game's, run after this pass. A move queued behind it is checked
// against the block the player just broke and falls through, so it
// would be sent back; it waits for the next tick, when the block is
// gone, as vanilla handles the two packets in order.
S::PlayerAction(p) if p.action <= 3 => {
events.push(HostEvent::Packet(conn, Box::new(S::PlayerAction(p))));
if matches!(
self.guests[i].inbox.front(),
Some(S::MovePlayerPos(_) | S::MovePlayerPosRot(_))
) {
break;
}
}
other => events.push(HostEvent::Packet(conn, Box::new(other))),
}
}
@@ -2583,16 +2718,44 @@ fn ticking_state(rate: f32, frozen: bool) -> C {
raw(ids::TICKING_STATE, w.data)
}
/// Entity.DATA_SHARED_FLAGS_ID of a player: crouching, sprinting, gliding.
fn shared_flags(sneaking: bool, sprinting: bool, gliding: bool) -> i8 {
/// What the others see of a guest's body, from its server-side state.
fn guest_body(g: &Guest) -> BodyFlags {
let m = g.motion.as_deref();
BodyFlags {
gliding: g.fall_flying,
swimming: m.is_some_and(|m| m.swimming),
crawling: m.is_some_and(|m| m.pose == crate::pose::Pose::Swimming && !m.swimming),
crouching: m.is_some_and(|m| m.pose == crate::pose::Pose::Crouching),
spin_attack: m.is_some_and(|m| m.auto_spin_attack_ticks > 0),
on_fire: m.is_some_and(|m| m.fire_ticks > 0),
invisible: g.effects.get("invisibility").is_some(),
glowing: g.effects.get("glowing").is_some(),
}
}
/// Entity.DATA_SHARED_FLAGS_ID of a player: on fire 0x01, crouching 0x02,
/// sprinting 0x08, swimming 0x10, invisible 0x20, glowing 0x40, gliding 0x80.
fn shared_flags(sneaking: bool, sprinting: bool, body: &BodyFlags) -> i8 {
let mut shared = 0i8;
if body.on_fire {
shared |= 0x01;
}
if sneaking {
shared |= 0x02;
}
if sprinting {
shared |= 0x08;
}
if gliding {
if body.swimming {
shared |= 0x10;
}
if body.invisible {
shared |= 0x20;
}
if body.glowing {
shared |= 0x40;
}
if body.gliding {
shared |= -128;
}
shared
+4 -1
View File
@@ -5,7 +5,7 @@
//! menu are returned for the game to drop.
use super::guest::Guest;
use crate::{
bundle::{Contents, can_be_in_bundle},
bundle::{Contents, can_be_in_bundle, toggle_selected},
items::{ItemStack, Items},
world::World,
};
@@ -514,7 +514,10 @@ fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bo
}
}
(carried, _) => {
// toggleSelectedItem(-1), then the click goes on.
view.guest.carried = carried;
toggle_selected(&mut bundle, -1);
view.set(i, Some(bundle));
return false;
}
}
+5 -2
View File
@@ -1,7 +1,7 @@
//! `BundleItem`'s click overrides in a PICKUP click
//! (`tryItemClickBehaviourOverride`).
use super::{Env, Menu, tidy};
use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle};
use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle, toggle_selected};
impl Menu {
/// The carried stack's `overrideStackedOnOther`, then the clicked
@@ -88,8 +88,11 @@ impl Menu {
}
}
(carried, _) => {
// toggleSelectedItem(-1): Horizon keeps no selected item.
// toggleSelectedItem(-1), then the click goes on.
self.carried = carried;
toggle_selected(&mut bundle, -1);
let slot = self.slots[s];
self.containers[slot.container][slot.index] = Some(bundle);
return false;
}
}
+20 -2
View File
@@ -50,6 +50,7 @@ pub mod nether;
pub mod path;
pub mod phantom;
pub mod piglin;
pub mod polar_bear;
pub mod rabbit;
pub mod raider;
pub mod ravager;
@@ -645,6 +646,8 @@ pub struct Attrs {
pub struct Extra {
/// Players: crouching and riding (HumanoidModel's poses).
pub crouching: bool,
/// Players: sprinting (`Entity.DATA_SHARED_FLAGS_ID`), for the dust they raise.
pub sprinting: bool,
pub passenger: bool,
/// AgeableMob.age: negative while a baby (a tadpole counts up to 24000).
pub age: i32,
@@ -726,6 +729,12 @@ pub struct Extra {
pub vector: [f64; 3],
/// Active status effects: (effect id, ticks left, amplifier).
pub effects: Vec<(&'static str, i32, i32)>,
/// The effects above given with `hideParticles`: no swirls for them.
pub hidden_effects: Vec<&'static str>,
/// `LivingEntity.DATA_EFFECT_PARTICLES` and `DATA_EFFECT_AMBIENCE_ID` as a
/// server gave them: the swirls around it, and whether they are all faint.
pub effect_particles: Vec<crate::particles::ParticleOptions>,
pub effect_ambient: bool,
/// An invisible illusioner's mirror images.
pub illusions: Option<illusioner::Illusions>,
/// A villager's claimed bed head and meeting bell.
@@ -737,6 +746,8 @@ pub struct Extra {
/// the spin the rope's torque gives it.
pub leash: Option<leash::Holder>,
pub leash_pending: Option<leash::Pending>,
/// The UUID of the player behind `Holder::Player` (host or guest).
pub leash_player: Option<[i32; 4]>,
pub leash_spin: f64,
/// More species scratch values.
pub scratch: [i32; 4],
@@ -1959,8 +1970,15 @@ impl Mob {
}
pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) {
if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) {
e.1 = e.1.max(ticks);
e.2 = e.2.max(amplifier);
// MobEffectInstance.update: a stronger effect replaces the old one
// with its own duration, an equal one keeps the longer duration,
// and a weaker one never changes the active effect.
if amplifier > e.2 {
e.1 = ticks;
e.2 = amplifier;
} else if amplifier == e.2 {
e.1 = e.1.max(ticks);
}
} else {
self.extra.effects.push((effect, ticks, amplifier));
}
+62 -1
View File
@@ -106,6 +106,7 @@ pub enum Family {
Strider,
Bat,
Bee,
PolarBear,
}
pub fn family(s: Species) -> Family {
use Species as S;
@@ -167,6 +168,7 @@ pub fn family(s: Species) -> Family {
S::Strider => Family::Strider,
S::Bat => Family::Bat,
S::Bee => Family::Bee,
S::PolarBear => Family::PolarBear,
_ => Family::Generic,
}
}
@@ -227,6 +229,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::PolarBear => super::polar_bear::register(m),
}
// FloatGoal's constructor lets the navigation float, as do the
// constructors of these brain-driven and flying mobs. A floater rises
@@ -416,6 +419,7 @@ pub fn tick(
super::axolotl::tick_animation(m);
m.anim.end_tick(m.ai.swinging);
tick_swing(m);
flower_contact_effects(m, w);
if m.species() == Species::CopperGolem {
// CopperGolem.tick: updateWeathering after the living tick.
super::copper_golem::update_weathering(m, w, level_random, events);
@@ -674,7 +678,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
}
// AbstractHorse.aiStep: the tail swishes now and then (moveTail).
if super::equine::is_equine(m.species()) {
let _ = m.random.next_int_bound(200);
super::equine::tail_tick(m);
}
// Monster.aiStep: updateNoActionTime (Raider: always +2).
if is_monster(m.species())
@@ -701,6 +705,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
// serverAiStep has no goals, so it only falls and is pushed.
let immobile = (m.species() == Species::Ravager && super::ravager::immobile(m))
|| m.species() == Species::Mannequin;
if m.species() == Species::Piglin && m.alive() {
super::piglin::celebrate(m, w);
}
if m.alive() && !immobile {
server_ai_step(m, w, level_random, events);
} else {
@@ -1025,6 +1032,7 @@ fn species_ai_step(
Species::Wither => super::wither::ai_step(m, w, events),
Species::Allay => super::allay::ai_step(m),
Species::Bee => super::bee::ai_step(m, w),
Species::PolarBear => super::polar_bear::ai_step(m, w),
Species::Breeze => super::breeze::ai_step(m),
Species::Sniffer => super::sniffer::ai_step(m, events),
Species::HappyGhast => super::happy_ghast::ai_step(m, w),
@@ -1517,6 +1525,56 @@ pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec<Mo
}
}
/// `Entity.applyEffectsFromBlocks` for the flowers that give an effect:
/// `WitherRoseBlock.entityInside` (wither for 40 ticks on a living mob that
/// can take it, not in peaceful) and `EyeblossomBlock.entityInside` (poison
/// for 25 ticks on a bee, when the open flower attracts bees). The blocks
/// are those the mob's box touches where it started the tick and where it
/// ended.
fn flower_contact_effects(m: &mut Mob, w: &MobWorld) {
if !m.alive() || w.difficulty.effective == 0.0 {
return;
}
let half = f64::from(m.width()) / 2.0 - 1.0e-5;
let height = f64::from(m.height()) - 1.0e-5;
let mut visited: Vec<[i32; 3]> = Vec::new();
for at in [m.previous, m.position] {
let cells = |lo: f64, hi: f64| lo.floor() as i32..=hi.floor() as i32;
for x in cells(at.x - half, at.x + half) {
for y in cells(at.y + 1.0e-5, at.y + height) {
for z in cells(at.z - half, at.z + half) {
let p = [x, y, z];
if visited.contains(&p) {
continue;
}
match w.block_name(x, y, z) {
"minecraft:wither_rose" => {
// isInvulnerableTo(wither): the invulnerable time
// after a hit; WitherBoss and WitherSkeleton
// refuse the effect (`canBeAffected`).
if m.invulnerable <= 0
&& !m.invulnerable_flag
&& !matches!(m.species(), Species::Wither | Species::WitherSkeleton)
{
m.add_effect("minecraft:wither", 40, 0);
}
}
"minecraft:open_eyeblossom"
if m.species() == Species::Bee
&& super::bee::attracts_bees(w, p)
&& !m.has_effect("minecraft:poison") =>
{
m.add_effect("minecraft:poison", 25, 0);
}
_ => continue,
}
visited.push(p);
}
}
}
}
}
/// MobEffect ticking for the effects mobs receive (poison, wither, regeneration).
fn tick_effects(m: &mut Mob) {
let mut effects = std::mem::take(&mut m.extra.effects);
@@ -1541,6 +1599,9 @@ fn tick_effects(m: &mut Mob) {
*ticks -= 1;
}
effects.retain(|e| e.1 > 0);
m.extra
.hidden_effects
.retain(|h| effects.iter().any(|e| e.0 == *h));
m.extra.effects = effects;
}
+29 -13
View File
@@ -197,7 +197,8 @@ pub fn state(m: &Mob, alpha: f32) -> State {
let walking = m.alive() && !m.extra.passenger;
State {
pos: if walking {
m.limb_position - m.limb_speed * (1.0 - alpha)
// WalkAnimationState.position(partial): babies' legs move 3 times as far.
(m.limb_position - m.limb_speed * (1.0 - alpha)) * if m.is_baby() { 3.0 } else { 1.0 }
} else {
0.0
},
@@ -248,18 +249,24 @@ pub enum ArmPose {
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
}
/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm.
pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) {
/// `AnimationUtils.swingWeaponDown`: the main arm swings down, the other
/// one hangs and bobs.
pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32, left_main: bool) {
let attack2 = (swing * PI).msin();
let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
let (main, off) = if left_main {
("left_arm", "right_arm")
} else {
("right_arm", "left_arm")
};
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15);
p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5);
p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4;
p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4;
p.xrot(main, -1.884_955_8 + (age * 0.09).mcos() * 0.15);
p.xrot(off, -0.0 + (age * 0.19).mcos() * 0.5);
p.get(main)[3] += attack2 * 2.2 - attack * 0.4;
p.get(off)[3] += attack2 * 1.2 - attack * 0.4;
bob(p, "right_arm", age, 1.0);
bob(p, "left_arm", age, -1.0);
}
@@ -286,6 +293,8 @@ pub struct Hum {
pub using_item: bool,
/// The arm the current swing moves (`Some(true)` for the right one).
pub swing_right_arm: Option<bool>,
/// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it.
pub left_main: bool,
}
impl Hum {
pub fn new(right: ArmPose, left: ArmPose) -> Self {
@@ -303,6 +312,7 @@ impl Hum {
swim: 0.0,
using_item: false,
swing_right_arm: None,
left_main: false,
}
}
}
@@ -315,7 +325,7 @@ impl ArmPose {
}
}
/// `AnimationUtils.animateCrossbowHold`.
fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
pub(super) fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
let (hold, shoot) = if in_right {
("right_arm", "left_arm")
} else {
@@ -327,7 +337,7 @@ fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
p.xrot(shoot, -1.5 + hx);
}
/// `AnimationUtils.animateCrossbowCharge`.
fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) {
pub(super) fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) {
let (hold, pull) = if in_right {
("right_arm", "left_arm")
} else {
@@ -418,13 +428,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
pose_arm(p, h.right, true, h);
}
}
// setupAttackAnimation (WHACK swing with the right arm).
// setupAttackAnimation (WHACK swing with the arm of the swinging hand).
let hx = p.get("head")[3];
let swing = s.swing;
let swing_left = h.swing_right_arm.map_or(h.left_main, |right| !right);
if swing > 0.0 && h.weapon_swing {
swing_weapon_down(p, swing, s.age);
swing_weapon_down(p, swing, s.age, h.left_main);
} else if swing > 0.0 {
let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2;
let mut body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2;
if swing_left {
body_y = -body_y;
}
p.yrot("body", body_y);
let age_scale = if s.baby { 0.5 } else { 1.0 };
{
@@ -444,7 +458,7 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
let eased = 1.0 - (1.0 - swing).powi(4);
let aa = (eased * PI).msin();
let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75;
let r = p.get("right_arm");
let r = p.get(if swing_left { "left_arm" } else { "right_arm" });
r[3] -= aa * 1.2 + bb;
r[4] += body_y * 2.0;
r[5] += (swing * PI).msin() * -0.4;
@@ -652,6 +666,7 @@ pub fn setup(
} else {
Hum::new(main, ArmPose::Empty)
};
h.left_main = m.main_arm_left();
h.zombie = Some(m.ai.aggressive);
h.holding = m.extra.main_hand.is_some();
h.crouching = m.extra.crouching;
@@ -715,6 +730,7 @@ pub fn setup(
h.swim = m.extra.swim.amount(s.partial);
h.using_item = m.extra.using_item > 0;
h.swing_right_arm = m.extra.swing_right_arm;
h.left_main = m.main_arm_left();
humanoid(p, s, &h);
if m.ai.aggressive && !bow {
// SkeletonModel melee pose.
+1 -1
View File
@@ -959,7 +959,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
let st = &m.anim.states;
match m.species() {
Species::Goat => goat(p, s, &Goat::from_mob(m)),
Species::PolarBear => polar_bear(p, s, 0.0),
Species::PolarBear => polar_bear(p, s, super::polar_bear::standing_scale(m, s.partial)),
Species::Panda => panda(p, s, &Panda::default()),
Species::Llama | Species::TraderLlama => {
llama(p, s, m.extra.chested && !s.baby);
+25 -1
View File
@@ -28,6 +28,8 @@ pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackd
pub const EAT: usize = 0;
pub const STAND: usize = 1;
pub const MOUTH: usize = 2;
/// `AbstractHorse.tailCounter`: client-side, it only drives the model.
pub const TAIL: usize = 3;
/// What a rider asks of its mount this tick.
#[derive(Clone, Copy, Debug, Default)]
@@ -418,6 +420,20 @@ pub fn ridden_step(m: &mut Mob) {
}
}
}
/// `AbstractHorse.aiStep`'s `moveTail` (one in 200 ticks) and the counter's
/// step in `tick` (it runs to 8, then stops). A client runs it on its own
/// random, as vanilla's client-side `aiStep` does.
pub fn tail_tick(m: &mut Mob) {
if m.random.next_int_bound(200).unwrap_or(1) == 0 {
m.anim.v[TAIL] = 1.0;
}
if m.anim.v[TAIL] > 0.0 {
m.anim.v[TAIL] += 1.0;
if m.anim.v[TAIL] > 8.0 {
m.anim.v[TAIL] = 0.0;
}
}
}
/// `AbstractHorse.aiStep` and `tick`: healing, grazing, the rear and the
/// eating/standing/mouth animations.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
@@ -603,7 +619,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
t[1] += speed * age;
t[2] += speed * 2.0 * age;
}
p.yrot("tail", 0.0);
// animateTail: the tail swings while the counter runs.
p.yrot(
"tail",
if m.anim.v[TAIL] > 0.0 {
(s.age * 0.7).mcos()
} else {
0.0
},
);
if baby && donkey {
// BabyDonkeyModel overrides the state's pitch with -30 degrees and
// sets the head parts again.
+39 -2
View File
@@ -1017,6 +1017,8 @@ pub struct MeleeAttack {
pub speed: f64,
pub follow_unseen: bool,
pub zombie: bool,
/// `PolarBear.PolarBearMeleeAttackGoal`: rears up before each strike.
pub polar_bear: bool,
path_target: [f64; 3],
recalc: i32,
pub until_attack: i32,
@@ -1031,6 +1033,7 @@ impl MeleeAttack {
speed,
follow_unseen,
zombie: false,
polar_bear: false,
path_target: [0.0; 3],
recalc: 0,
until_attack: 0,
@@ -1043,6 +1046,10 @@ impl MeleeAttack {
self.zombie = true;
self
}
pub fn polar_bear(mut self) -> Self {
self.polar_bear = true;
self
}
pub fn interval(mut self, ticks: i32) -> Self {
self.interval = ticks;
self
@@ -1098,6 +1105,9 @@ impl Goal for MeleeAttack {
}
m.ai.aggressive = false;
m.nav_stop();
if self.polar_bear {
super::polar_bear::set_standing(m, false);
}
}
fn every_tick(&self) -> bool {
true
@@ -1131,7 +1141,17 @@ impl Goal for MeleeAttack {
self.recalc = adjusted(true, self.recalc);
}
self.until_attack = (self.until_attack - 1).max(0);
if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) {
if self.polar_bear {
let cooldown = adjusted(true, self.interval);
super::polar_bear::check_and_perform_attack(
&mut self.until_attack,
cooldown,
m,
who,
&t,
cx,
);
} else if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) {
self.until_attack = adjusted(true, self.interval);
m.swing();
super::ai::do_hurt_target(m, who, cx);
@@ -1422,6 +1442,9 @@ pub struct HurtByTarget {
/// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others
/// only when the attacker is in sight.
pub bee: bool,
/// `PolarBear.PolarBearHurtByTargetGoal`: a hurt cub only calls the
/// adult bears and drops the target itself.
pub polar_bear: bool,
timestamp: i32,
st: TargetState,
}
@@ -1432,6 +1455,7 @@ impl HurtByTarget {
alert_except: vec![],
ignore: vec![],
bee: false,
polar_bear: false,
timestamp: 0,
st: TargetState {
unseen_memory: 300,
@@ -1451,6 +1475,10 @@ impl HurtByTarget {
self.bee = true;
self
}
pub fn polar_bear(mut self) -> Self {
self.polar_bear = true;
self
}
}
impl Default for HurtByTarget {
fn default() -> Self {
@@ -1462,6 +1490,8 @@ impl Goal for HurtByTarget {
fn name(&self) -> &'static str {
if self.bee {
"BeeHurtByOtherGoal"
} else if self.polar_bear {
"PolarBearHurtByTargetGoal"
} else {
"HurtByTarget"
}
@@ -1500,7 +1530,9 @@ impl Goal for HurtByTarget {
self.timestamp = m.ai.last_hurt_by_time;
self.st.unseen_memory = 300;
self.st.unseen = 0;
if self.alert
// PolarBearHurtByTargetGoal.start: a cub alerts the adults itself.
let cub = self.polar_bear && m.is_baby();
if (self.alert || cub)
&& let Some(by) = m.ai.target
{
let range = m.attrs.follow_range;
@@ -1520,6 +1552,8 @@ impl Goal for HurtByTarget {
&& (s.position.z - pos.z).abs() <= range + 1.0
})
.filter(|s| !self.alert_except.contains(&s.species))
// PolarBearHurtByTargetGoal.alertOther: adults only.
.filter(|s| !(self.polar_bear && s.baby))
.filter(|s| Who::Mob(s.id) != by)
.map(|s| s.id)
.collect();
@@ -1534,6 +1568,9 @@ impl Goal for HurtByTarget {
});
}
}
if cub {
m.ai.target = None;
}
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.ai.target = None;
+8 -3
View File
@@ -681,7 +681,12 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) {
p.xrot("right_arm", x + a * 1.2 - b * 0.4);
p.xrot("left_arm", x + a * 1.2 - b * 0.4);
} else {
// swingWeaponDown (right-handed).
// swingWeaponDown: the main arm swings down.
let (main, off) = if m.main_arm_left() {
("left_arm", "right_arm")
} else {
("right_arm", "left_arm")
};
let swing = s.swing;
let a2 = (swing * PI).msin();
let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
@@ -690,11 +695,11 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) {
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot(
"right_arm",
main,
-1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4),
);
p.xrot(
"left_arm",
off,
-0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4),
);
}
+1 -1
View File
@@ -908,7 +908,7 @@ impl Mob {
(distance * 4.0).min(1.0)
};
self.limb_speed += (target - self.limb_speed) * 0.4;
self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 };
self.limb_position += self.limb_speed;
} else {
self.limb_speed = 0.0;
}
+127 -23
View File
@@ -10,7 +10,7 @@ use super::{
},
};
use horizon_core::geometry::{Vec3, trig::Mth};
use horizon_core::random::RandomSource;
use horizon_core::random::{LegacyRandom, RandomSource};
use std::f32::consts::PI;
/// `PiglinAi.ADMIRE_DURATION`.
@@ -20,6 +20,9 @@ pub const ADMIRE: i32 = 119;
pub const ATE_RECENTLY: i32 = 200;
/// `AbstractPiglin.CONVERSION_TIME` (and the hoglin's).
const CONVERSION: i32 = 300;
/// `PiglinAi.CELEBRATION_TIME`: how long the `CELEBRATE_LOCATION` and
/// `DANCING` memories last.
const CELEBRATION: i32 = 300;
fn hostile_to_player(m: &Mob, w: &MobWorld) -> bool {
if m.is_baby() {
@@ -50,6 +53,7 @@ pub fn register_piglin(m: &mut Mob) {
g.add(3, MeleeAttack::new(1.0, true));
g.add(4, PiglinAvoidRepellent);
g.add(4, GoToWantedItem);
g.add(4, Celebrate);
g.add(5, Stroll::avoiding_water(0.6));
g.add(6, LookAtPlayer::new(8.0));
g.add(7, RandomLookAround::default());
@@ -243,6 +247,45 @@ impl Goal for Admire {
m.nav_stop();
}
}
/// The celebrate activity: `GoToTargetLocation` on the spot a killed target
/// fell (within 2 blocks, or 4 and slower while dancing).
#[derive(Clone, Debug)]
struct Celebrate;
impl Celebrate {
fn walk(m: &mut Mob, cx: &mut Cx) {
let Some(at) = m.extra.home else { return };
let (close, speed) = if m.extra.scratch[0] > 0 {
(4.0, 0.6)
} else {
(2.0, 1.0)
};
let center = Vec3::new(
f64::from(at[0]) + 0.5,
f64::from(at[1]),
f64::from(at[2]) + 0.5,
);
if m.distance_sqr(center) >= close * close {
m.nav_move_to(cx.w, [center.x, center.y, center.z], speed);
}
}
}
impl Goal for Celebrate {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
m.extra.scratch[1] > 0 && m.extra.home.is_some() && m.extra.using_item == 0
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
Self::walk(m, cx);
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if m.ai.nav.is_done() {
Self::walk(m, cx);
}
}
}
/// `GoToWantedItem`: walk to the gold the game spotted.
#[derive(Clone, Debug)]
struct GoToWantedItem;
@@ -294,6 +337,54 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) {
m.ai.target = None;
}
}
/// `StartCelebratingIfTargetDead` for a piglin (`scratch[0]` dancing,
/// `scratch[1]` ticks of celebration left, `scratch[2]` the hit seen, `home`
/// the `CELEBRATE_LOCATION`): a killed target starts a celebration at its
/// spot, and a hoglin's death makes the piglin dance one time in ten.
/// `PiglinAi.wasHurtBy` ends both. Runs before the target goals drop the
/// dead target.
pub fn celebrate(m: &mut Mob, w: &MobWorld) {
if m.extra.scratch[1] > 0 {
m.extra.scratch[1] -= 1;
if m.extra.scratch[1] == 0 {
m.extra.scratch[0] = 0;
m.extra.home = None;
}
}
if let Some(by) = m.ai.last_hurt_by
&& m.ai.last_hurt_by_time != m.extra.scratch[2]
{
m.extra.scratch[2] = m.ai.last_hurt_by_time;
// PiglinAi.wasHurtBy: another piglin's hit ends nothing.
let piglin =
matches!(by, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Piglin));
if !piglin {
m.extra.scratch[0] = 0;
m.extra.scratch[1] = 0;
m.extra.home = None;
}
}
if m.extra.scratch[1] > 0 {
return;
}
let Some(target) = m.ai.target else { return };
let Some(t) = w.target_info(target).filter(|t| !t.alive) else {
return;
};
let hoglin =
matches!(target, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Hoglin));
// PiglinAi.wantsToDance: a fresh random seeded with the game time, not
// the piglin's own.
if hoglin && LegacyRandom::new(w.game_time).next_float() < 0.1 {
m.extra.scratch[0] = 1;
}
m.extra.scratch[1] = CELEBRATION;
m.extra.home = Some([
t.position.x.floor() as i32,
t.position.y.floor() as i32,
t.position.z.floor() as i32,
]);
}
/// Per-tick piglin and hoglin state: admiring, anger, zombification and the
/// hoglin attack animation. Returns a conversion when it happens.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
@@ -420,7 +511,10 @@ pub fn ears(p: &mut Poses, s: &State) {
/// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the
/// arm pose (`PiglinModel`).
pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) {
let pose = if m.extra.using_item > 0 {
// Piglin.getArmPose: dancing comes first.
let pose = if m.extra.scratch[0] > 0 {
PiglinPose::Dancing
} else if m.extra.using_item > 0 {
PiglinPose::AdmiringItem
} else if m.extra.flag {
PiglinPose::CrossbowCharge
@@ -431,7 +525,14 @@ pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) {
} else {
PiglinPose::Default
};
piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32);
piglin_pose(
p,
s,
pose,
25.0,
m.extra.using_item as f32,
m.main_arm_left(),
);
}
/// `PiglinArmPose`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -443,11 +544,19 @@ pub enum PiglinPose {
CrossbowCharge,
AdmiringItem,
}
/// `PiglinModel.setupAnim` for a piglin facing right-handed.
pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) {
use super::anim::{ArmPose, Hum, humanoid};
/// `PiglinModel.setupAnim`; `left` when the piglin's main arm is the left one.
pub fn piglin_pose(
p: &mut Poses,
s: &State,
pose: PiglinPose,
max_charge: f32,
ticks: f32,
left: bool,
) {
use super::anim::{ArmPose, Hum, crossbow_charge, crossbow_hold, humanoid};
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
h.weapon_swing = pose == PiglinPose::MeleeWeapon;
h.left_main = left;
h.charge = (max_charge, ticks);
humanoid(p, s, &h);
ears(p, s);
@@ -474,27 +583,22 @@ pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32,
p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5;
p.get("body")[1] += (dance * 40.0).msin() * 0.35;
}
PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8),
PiglinPose::CrossbowHold => {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
p.xrot("right_arm", -PI / 2.0 + hx + 0.1);
p.xrot("left_arm", -1.5 + hx);
}
PiglinPose::CrossbowCharge => {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
p.xrot("left_arm", -0.970_796_35);
let alpha = ticks.clamp(0.0, max_charge) / max_charge;
p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4));
let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35);
p.xrot("left_arm", x);
// holdWeaponHigh
PiglinPose::MeleeWeapon if s.swing == 0.0 => {
p.xrot(if left { "left_arm" } else { "right_arm" }, -1.8)
}
PiglinPose::CrossbowHold => crossbow_hold(p, hx, hy, !left),
PiglinPose::CrossbowCharge => crossbow_charge(p, max_charge, ticks, !left),
PiglinPose::AdmiringItem => {
p.xrot("head", 0.5);
p.yrot("head", 0.0);
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
if left {
p.yrot("right_arm", -0.5);
p.xrot("right_arm", -0.9);
} else {
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
}
}
_ => {}
}
@@ -0,0 +1,191 @@
//! Polar bears (`PolarBear`): a neutral animal that defends its cubs,
//! fights back when hurt, and rears up before each swing. A cub flees what
//! hurts it and calls the adults.
//!
//! `extra.flag` is `DATA_STANDING_ID`, `extra.counter` the warning sound's
//! delay, `extra.anger` the `NeutralMob` anger left and `extra.flag2` whether
//! the player is who it is angry at. `anim.v[STAND]` is
//! `clientSideStandAnimation`.
use horizon_core::{geometry::Vec3, random::RandomSource};
use super::{
DamageKind, Mob, MobWorld, Species, Who,
goals::{
Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, MOVE, MeleeAttack,
NearestTarget, Panic, RandomLookAround, Stroll, goal_clone,
},
world::TargetInfo,
};
/// `anim.v` slot of `clientSideStandAnimation`.
pub const STAND: usize = 0;
/// `STAND_ANIMATION_TICKS`.
const STAND_TICKS: f32 = 6.0;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, MeleeAttack::new(1.25, true).polar_bear());
g.add(1, PolarBearPanic(Panic::new(2.0)));
g.add(4, FollowParent::new(1.25));
g.add(5, Stroll::new(1.0));
g.add(6, LookAtPlayer::new(6.0));
g.add(7, RandomLookAround::default());
let t = &mut m.ai.targets;
t.add(1, HurtByTarget::new().polar_bear());
// PolarBearAttackPlayersGoal: players near a cub, within half the
// follow range, never for a cub itself.
t.add(
2,
NearestTarget::player(true)
.interval(20)
.follow_scale(0.5)
.reach()
.gate(|m, _| !m.is_baby())
.when(cub_nearby)
.named("PolarBearAttackPlayersGoal"),
);
t.add(
3,
NearestTarget::player(true).when(|m, _| m.extra.anger > 0 && m.extra.flag2),
);
t.add(
4,
NearestTarget::species(&[Species::Fox], true)
.interval(10)
.reach()
.when(|m, _| !m.is_baby()),
);
}
/// `PolarBearAttackPlayersGoal.canUse`: a polar bear cub within 8 blocks
/// (4 up and down).
fn cub_nearby(m: &Mob, w: &MobWorld) -> bool {
let area = m.bounds().inflate(Vec3::new(8.0, 4.0, 8.0));
w.others_near(area)
.any(|s| s.species == Species::PolarBear && s.baby && s.bounds.intersects(area))
}
/// `PanicGoal` with a function of the bear's age for the damage tag: a cub
/// panics at `PANIC_CAUSES`, an adult only at `PANIC_ENVIRONMENTAL_CAUSES`.
#[derive(Clone, Debug)]
struct PolarBearPanic(Panic);
impl Goal for PolarBearPanic {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
(m.is_baby() || environmental_panic(m)) && 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) {
self.0.start(m, cx)
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.stop(m, cx)
}
}
/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES` (fire, lava, cactus), or
/// burning.
fn environmental_panic(m: &Mob) -> bool {
m.fire_ticks > 0 && !m.kind.flags.fire_immune
|| m.last_damage.is_some_and(|(d, t)| {
matches!(
d.kind,
DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Cactus
) && i64::from(m.age) - t <= 40
})
}
/// `PolarBear.setStanding`.
pub fn set_standing(m: &mut Mob, standing: bool) {
m.extra.flag = standing;
}
/// `PolarBear.playWarningSound`.
fn play_warning_sound(m: &mut Mob, cx: &mut Cx) {
if m.extra.counter <= 0 {
m.voice("entity.polar_bear.warning", cx.events);
m.extra.counter = 40;
}
}
/// `PolarBearMeleeAttackGoal.checkAndPerformAttack`: strike when ready and
/// in reach, rear up and growl in the last 10 ticks while close.
pub fn check_and_perform_attack(
until_attack: &mut i32,
cooldown: i32,
m: &mut Mob,
who: Who,
t: &TargetInfo,
cx: &mut Cx,
) {
if *until_attack <= 0 && m.within_melee_range(t) && m.sees(cx.w, who) {
*until_attack = cooldown;
super::ai::do_hurt_target(m, who, cx);
set_standing(m, false);
return;
}
let reach = t.bounds.size().x as f32 + 3.0;
if m.distance_sqr(t.position) < f64::from(reach * reach) {
if *until_attack <= 0 {
set_standing(m, false);
*until_attack = cooldown;
}
if *until_attack <= 10 {
set_standing(m, true);
play_warning_sound(m, cx);
}
} else {
*until_attack = cooldown;
set_standing(m, false);
}
}
/// `PolarBear.tick`'s client half: `clientSideStandAnimation` follows the
/// synched standing flag by one tick a tick. A client of a server runs it
/// too.
pub fn client_tick(m: &mut Mob) {
let v = m.anim.v[STAND];
m.anim.vo[STAND] = v;
let step = if m.extra.flag { 1.0 } else { -1.0 };
m.anim.v[STAND] = (v + step).clamp(0.0, STAND_TICKS);
}
/// `PolarBear.getStandingAnimationScale`.
pub fn standing_scale(m: &Mob, partial: f32) -> f32 {
m.anim.lerp(STAND, partial) / STAND_TICKS
}
/// `PolarBear.tick`: the stand animation, the warning sound's delay and
/// `NeutralMob.updatePersistentAnger`.
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
client_tick(m);
if m.extra.counter > 0 {
m.extra.counter -= 1;
}
if m.ai.target.is_some() {
// Anger follows the target and starts over every tick it is held:
// 20 to 39 seconds (`PERSISTENT_ANGER_TIME`).
m.extra.flag2 = m.ai.target == Some(Who::Player);
m.extra.anger = 400 + m.random.next_int_bound(381).unwrap_or(0);
} else if m.extra.anger > 0 {
m.extra.anger -= 1;
if m.extra.anger == 0 {
stop_being_angry(m);
}
}
// A player in creative or spectator mode is forgiven at once.
if m.extra.flag2 && w.player.as_ref().is_some_and(|p| p.creative || p.spectator) {
stop_being_angry(m);
}
}
/// `NeutralMob.stopBeingAngry`.
fn stop_being_angry(m: &mut Mob) {
m.ai.last_hurt_by = None;
m.ai.target = None;
m.extra.anger = 0;
m.extra.flag2 = false;
}
+16 -11
View File
@@ -232,8 +232,10 @@ pub fn drowned_travel(
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
true
}
/// The trident throw of `Drowned.performRangedAttack`, until thrown tridents
/// exist: an arrow-like shot with the trident's damage.
/// The trident throw of `Drowned.performRangedAttack`: a `ThrownTrident` of
/// the held trident (a plain one when it holds none), owned by the drowned,
/// which cannot be picked up and does not return (`AbstractArrow` constructor:
/// only a player's projectile is `Pickup.ALLOWED`).
fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
let Some(t) = cx.w.target_info(who) else {
return;
@@ -243,15 +245,18 @@ fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
let yd = t.position.y + (t.bounds.max_position().y - t.bounds.min_position().y) / 3.0 - start.y;
let zd = t.position.z - m.position.z;
let dist = (xd * xd + zd * zd).sqrt();
let mut p = Projectile::new(
ProjectileKind::Arrow {
base_damage: 8.0,
critical: false,
effect: None,
},
start,
Some(Who::Mob(m.id)),
);
let mut trident = crate::items::ItemStack::new("minecraft:trident", 1);
if m.extra.main_hand.as_deref() == Some("minecraft:trident")
&& let Some(g) = super::gear::gear(m)
{
for (e, l) in &g.slots[super::gear::MAIN] {
trident.enchant(e, *l);
}
}
let mut p = Projectile::new(ProjectileKind::Trident, start, Some(Who::Mob(m.id)));
if let Some(a) = p.arrow.as_mut() {
a.set_item(&trident);
}
p.shoot(
&mut crate::projectiles::own_random(m),
[xd, yd + dist * f64::from(0.2_f32), zd],
+55
View File
@@ -226,6 +226,14 @@ pub enum MotionEvent {
bubble: bool,
position: Vec3,
},
/// `HoneyBlock.maybeDoSlideEffects` for a player sliding down the side of
/// the honey block at `pos`: its slide sound, and the server's entity
/// event 53 (the five block particles at the player).
HoneySlide {
pos: BlockPos,
sound: bool,
particles: bool,
},
/// Entity event 67 (`LivingEntity.makeDrownParticles`): eight bubbles
/// around a drowning player.
Drown,
@@ -1449,6 +1457,9 @@ impl MotionWorld<'_, '_, '_> {
"minecraft:sweet_berry_bush" if damage_only => {
self.sweet_berry_bush_damage(state)?;
}
// HoneyBlock.entityInside: a server's player slides too, so
// its fall distance resets (its client moves it).
"minecraft:honey_block" => self.honey_block_inside(p)?,
// PowderSnowBlock.entityInside's FREEZE.
"minecraft:powder_snow" if damage_only => entered.push((step, p)),
_ => {}
@@ -1479,6 +1490,50 @@ impl MotionWorld<'_, '_, '_> {
}
Ok(iterations + 1)
}
/// `HoneyBlock.entityInside`: a falling player touching a side of the block
/// slides down it (`isSlidingDown`, `doSlideMovement`, `maybeDoSlideEffects`).
fn honey_block_inside(&mut self, pos: BlockPos) -> Result<()> {
let old_delta_y = |dy: f64| dy / f64::from(0.98_f32) + 0.08;
let new_delta_y = |dy: f64| (dy - 0.08) * f64::from(0.98_f32);
let position = self.player.position;
let velocity = self.player.velocity;
if self.player.ground.on_ground
|| position.y > f64::from(pos.y) + 0.9375 - 1.0e-7
|| old_delta_y(velocity.y) >= -0.08
{
return Ok(());
}
let dx = (f64::from(pos.x) + 0.5 - position.x).abs();
let dz = (f64::from(pos.z) + 0.5 - position.z).abs();
let overlap = 0.4375 + f64::from(self.player.dimensions.width / 2.0);
if !(dx + 1.0e-7 > overlap || dz + 1.0e-7 > overlap) {
return Ok(());
}
// doSlideMovement
let old = old_delta_y(velocity.y);
if old < -0.13 {
let factor = -0.05 / old;
self.player.velocity =
Vec3::new(velocity.x * factor, new_delta_y(-0.05), velocity.z * factor);
} else {
self.player.velocity = Vec3::new(velocity.x, new_delta_y(-0.05), velocity.z);
}
self.player.fall_distance = 0.0;
// maybeDoSlideEffects: the sound, then the server's event 53.
let random = &mut self.scene.random;
let sound = random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0;
// Only the server broadcasts event 53 (`!level.isClientSide()`).
let particles = !self.player.client_side
&& random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0;
if sound || particles {
self.player.events.push(MotionEvent::HoneySlide {
pos,
sound,
particles,
});
}
Ok(())
}
/// `Player.makeStuckInBlock`: the next move is scaled by `multiplier`
/// (and the fall forgotten) unless flying; the impulse context resets
/// either way.
+36
View File
@@ -67,6 +67,7 @@ pub enum Opt {
ReducedDebugInfo,
HighContrast,
ShowSubtitles,
MusicFrequency,
NotificationDisplayTime,
Narrator,
TextBackground,
@@ -172,6 +173,10 @@ impl Opt {
| Opt::MonochromeLogo
| Opt::RotateWithMinecarts
| Opt::HighContrastBlockOutlines
// Saved, but nothing in rendering reads them yet.
| Opt::ChunkFade
| Opt::ImprovedTransparency
| Opt::ChunkBuilder
)
}
fn file_key(self) -> Option<&'static str> {
@@ -192,6 +197,7 @@ impl Opt {
Opt::NarratorHotkey => "narratorHotkey",
Opt::RotateWithMinecarts => "rotateWithMinecart",
Opt::HighContrastBlockOutlines => "highContrastBlockOutline",
Opt::MusicFrequency => "musicFrequency",
_ => return None,
})
}
@@ -248,6 +254,7 @@ impl Opt {
Opt::ReducedDebugInfo => "options.reducedDebugInfo",
Opt::HighContrast => "options.accessibility.high_contrast",
Opt::ShowSubtitles => "options.showSubtitles",
Opt::MusicFrequency => "options.music_frequency",
Opt::NotificationDisplayTime => "options.notifications.display_time",
Opt::Narrator => "options.narrator",
Opt::TextBackground => "options.accessibility.text_background",
@@ -578,6 +585,11 @@ impl Opt {
Opt::ReducedDebugInfo => on_off(s.reduced_debug_info),
Opt::HighContrast => on_off(s.high_contrast),
Opt::ShowSubtitles => on_off(s.show_subtitles),
Opt::MusicFrequency => tr([
"options.music_frequency.default",
"options.music_frequency.frequent",
"options.music_frequency.constant",
][s.file.int("musicFrequency").clamp(0, 2) as usize]),
Opt::ForceUnicode => on_off(s.force_unicode),
Opt::JapaneseGlyphs => on_off(s.japanese_glyphs),
Opt::PadEnabled => on_off(s.controller.enabled),
@@ -747,6 +759,11 @@ impl Opt {
Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info,
Opt::HighContrast => s.high_contrast = !s.high_contrast,
Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles,
Opt::MusicFrequency => {
let n = next(s.file.int("musicFrequency").clamp(0, 2) as u8, 3);
s.file
.set("musicFrequency", crate::options_file::V::Int(i32::from(n)));
}
Opt::ForceUnicode => s.force_unicode = !s.force_unicode,
Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs,
Opt::PadEnabled => s.controller.enabled = !s.controller.enabled,
@@ -1412,6 +1429,9 @@ impl OptionsUi {
let others: Vec<Opt> = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect();
rows.extend(pairs(&others));
rows.extend(pairs(&[Opt::ShowSubtitles]));
// SoundOptionsScreen: Music Frequency starts the next row (with
// Music Toast, not in Horizon yet).
rows.extend(pairs(&[Opt::MusicFrequency]));
rows
}
Page::Controls => {
@@ -2533,6 +2553,21 @@ impl OptionsUi {
if opt == Opt::Preset {
apply_preset(s);
}
if opt == Opt::HighContrast {
// Options.highContrast: the built-in pack follows the option.
let on = s.resource_packs.iter().any(|id| id == "high_contrast");
if on != s.high_contrast {
s.resource_packs.retain(|id| id != "high_contrast");
if s.high_contrast {
s.resource_packs.push("high_contrast".into());
}
// PackSelectionScreen reads the repository each time it
// opens: the next one starts from this selection.
self.pack_selection = s.resource_packs.clone();
self.pack_screen = None;
events.push(Event::Packs(s.resource_packs.clone()));
}
}
events.push(Event::Changed);
}
Act::Extra(item) => {
@@ -2701,6 +2736,7 @@ impl OptionsUi {
{
let ids = p.commit();
s.resource_packs = ids.clone();
self.pack_selection = ids.clone();
events.push(Event::Packs(ids));
}
}
+17 -4
View File
@@ -1176,16 +1176,17 @@ impl ParticleEngine {
}
}
/// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the
/// explosion particle (emitter for radius >= 2) and up to 512 poof/smoke
/// particles thrown from air inside the radius.
/// explosion particle (the emitter unless `ServerExplosion.isSmall`) and up
/// to 512 poof/smoke particles thrown from air inside the radius.
pub fn explosion(
&mut self,
center: [f64; 3],
radius: f32,
small: bool,
block_count: usize,
radius: f32,
is_air: &dyn Fn([i32; 3]) -> bool,
) {
let ty = if radius < 2.0 {
let ty = if small {
ParticleType::Explosion
} else {
ParticleType::ExplosionEmitter
@@ -1193,6 +1194,18 @@ impl ParticleEngine {
self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]);
self.explosion_blocks(center, radius, block_count, is_air);
}
/// `LlamaSpit.recreateFromPacket`: seven spit particles thrown ahead of a
/// new spit, each faster than the last along x and z.
pub fn llama_spit_burst(&mut self, at: [f64; 3], movement: [f64; 3]) {
for i in 0..7 {
let k = 0.4 + 0.1 * f64::from(i);
self.add(
&ParticleOptions::simple(ParticleType::Spit),
at,
[movement[0] * k, movement[1], movement[2] * k],
);
}
}
/// `ClientExplosionTracker` with `Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES`.
pub fn explosion_blocks(
&mut self,
+11 -5
View File
@@ -28,6 +28,10 @@ pub enum ProjectileKind {
critical: bool,
effect: Option<(&'static str, i32)>,
},
/// `ThrownTrident` of a mob (a drowned's): flies and sticks with
/// `AbstractArrow`'s tick; the trident itself is the arrow state's
/// `pickup_item`.
Trident,
Snowball,
Egg,
EnderPearl,
@@ -66,6 +70,7 @@ impl ProjectileKind {
pub fn id(&self) -> &'static str {
match self {
Self::Arrow { .. } => "minecraft:arrow",
Self::Trident => "minecraft:trident",
Self::Snowball => "minecraft:snowball",
Self::Egg => "minecraft:egg",
Self::EnderPearl => "minecraft:ender_pearl",
@@ -152,7 +157,7 @@ fn axis_of(d: u8) -> u8 {
}
impl Projectile {
pub fn new(kind: ProjectileKind, position: Vec3, owner: Option<Who>) -> Self {
let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. });
let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. } | ProjectileKind::Trident);
Self {
id: 0,
kind,
@@ -253,7 +258,7 @@ impl Projectile {
}
fn gravity(&self) -> f64 {
match self.kind {
ProjectileKind::Arrow { .. } => 0.05,
ProjectileKind::Arrow { .. } | ProjectileKind::Trident => 0.05,
ProjectileKind::SmallFireball
| ProjectileKind::LargeFireball { .. }
| ProjectileKind::WitherSkull { .. } => 0.0,
@@ -604,8 +609,8 @@ impl Projectile {
| ProjectileKind::WitherSkull { .. } => {
self.apply_hurting_inertia(water);
}
// Arrows tick with `arrows::tick`.
ProjectileKind::Arrow { .. } => {}
// Arrows and tridents tick with `arrows::tick`.
ProjectileKind::Arrow { .. } | ProjectileKind::Trident => {}
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {}
// LlamaSpit.tick: gone in water; drag and gravity follow the move.
ProjectileKind::LlamaSpit => {
@@ -746,7 +751,8 @@ impl Projectile {
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => return None,
ProjectileKind::WitherSkull { dangerous: false } => "entity/wither/wither",
ProjectileKind::WitherSkull { dangerous: true } => "entity/wither/wither_invulnerable",
ProjectileKind::Arrow { .. } => return None,
// Drawn as their models by the game.
ProjectileKind::Arrow { .. } | ProjectileKind::Trident => return None,
})
}
/// Render scale of the item billboard (fireball renderers).
+8
View File
@@ -1417,6 +1417,14 @@ impl Streaming {
pub fn band(&self) -> Option<Band> {
self.band
}
/// Rank the chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)`
/// decorates in vanilla's order (`forced_order`), after every chunk
/// ranked before.
pub fn rank_forced(&mut self, x0: i32, z0: i32, x1: i32, z1: i32) {
for (x, z) in horizon_world::worldgen::decoration_order::forced_order(x0, z0, x1, z1) {
self.decoration_order.rank_or_append(x, z);
}
}
/// Generate, light and keep the chunks of `band` (none: stop), and let
/// go of what earlier bands held as it falls out of range. The chunks a
/// band reaches are ranked for decoration row by row, as they first come
+19 -15
View File
@@ -196,23 +196,27 @@ fn text(nbt: &Compound, key: &str) -> Option<String> {
/// The client block entity for one of a chunk's generated block entities,
/// before a container's loot is unpacked: `StructureTemplate.placeInWorld`
/// hands the template's block entity NBT to the level's block entity.
/// hands the template's block entity NBT to `loadWithComponents`, which is
/// what a chunk load does with a saved one.
fn generated_block_entity(block: &str, nbt: &Compound) -> Option<BlockEntity> {
let mut entity = BlockEntity::for_block(block)?;
match &mut entity {
// MonsterRoomFeature and the structures' setEntityId.
BlockEntity::Spawner(s) => {
**s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone()));
}
BlockEntity::TrialSpawner(s) => {
**s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone()));
}
BlockEntity::Vault(v) => **v = crate::vault::Vault::load(&Tag::Compound(nbt.clone())),
// BannerBlockEntity.loadAdditional: the End cities' black triangles.
BlockEntity::Banner(b) => *b = crate::save::decode_banner(&Tag::Compound(nbt.clone())),
_ => {}
let fallback = BlockEntity::for_block(block)?;
let mut tag = nbt.clone();
// RandomizableContainer.tryLoadLootTable: with a table the items are not read.
if text(&tag, "LootTable").is_some() {
tag.remove(&JavaString::from("Items"));
}
Some(entity)
// Programmatic block entities (and a template that saved none) carry no id.
if !tag.contains_key(&JavaString::from("id")) {
tag.insert("id".into(), Tag::String(fallback.id().into()));
}
for axis in ["x", "y", "z"] {
tag.insert(axis.into(), Tag::Int(0));
}
// A saved kind the client cannot decode keeps the block's own entity.
Some(
crate::save::decode_block_entity(&Tag::Compound(tag))
.map_or(fallback, |(_, entity)| entity),
)
}
/// Client block entities for the generated block entities of a chunk, and the
+99 -2
View File
@@ -24,7 +24,9 @@ use horizon_world::{
};
use std::{path::Path, sync::Arc};
mod lod;
mod structure_mobs;
use lod::VanillaLodSampler;
use structure_mobs::StructureMobFinalizer;
pub struct VanillaTerrain {
generator: OverworldGenerator,
@@ -32,6 +34,7 @@ pub struct VanillaTerrain {
biome_map: Vec<u16>,
/// Loot tables for generated containers.
loot: Option<Arc<horizon_world::loot::LootData>>,
structure_mobs: Arc<StructureMobFinalizer>,
/// A worker for structure queries from the game thread.
query: std::sync::Mutex<Option<GeneratorWorker>>,
/// Block state id -> block index, the game's block tick type: worldgen
@@ -39,6 +42,8 @@ pub struct VanillaTerrain {
tick_blocks: Vec<u32>,
/// Block index -> default state id: `tick_blocks` the other way.
tick_states: Vec<u32>,
/// Block state id -> the block entity type of its block, if it has one.
block_entity_types: Vec<Option<&'static str>>,
seed: i64,
dimension: String,
/// When the last proto chunk was generated, in milliseconds since
@@ -51,6 +56,51 @@ enum VanillaProto {
Ready(Box<ProtoChunk>),
Failed(i32, i32),
}
/// WorldGenRegion.setBlock gives every block with a block entity a new
/// one: the blocks nothing placed data for (a sculk patch's sensors) get
/// vanilla's defaults.
fn add_default_block_entities(kinds: &[Option<&str>], out: &mut Chunk, raw: &mut Vec<Tag>) {
let kind = |v: u32| kinds.get(v as usize).copied().flatten();
let mut states = [0u32; 4096];
for (si, section) in out.sections.iter().enumerate() {
if !section.blocks.maybe_has(|v| kind(v).is_some()) {
continue;
}
section.unpack(&mut states);
for (i, &v) in states.iter().enumerate() {
let Some(id) = kind(v) else {
continue;
};
let i = i as i32;
let pos = [
out.x * 16 + (i & 15),
MIN_Y + si as i32 * 16 + (i >> 8),
out.z * 16 + ((i >> 4) & 15),
];
let at = |t: &Tag| {
["x", "y", "z"]
.iter()
.zip(pos)
.all(|(k, p)| t.get(k) == Some(&Tag::Int(p)))
};
if raw.iter().any(at) || out.block_entities.iter().any(|(p, _)| *p == pos.into()) {
continue;
}
let tag = Tag::compound([
("id", Tag::String(id.into())),
("x", Tag::Int(pos[0])),
("y", Tag::Int(pos[1])),
("z", Tag::Int(pos[2])),
]);
let tag = crate::block_entity_nbt::canonical(&tag).unwrap_or(tag);
match crate::save::decode_block_entity(&tag) {
Some(modelled) => out.block_entities.push(modelled),
None => raw.push(tag),
}
}
}
}
impl VanillaTerrain {
fn client_surface(&self, surface: SurfaceSample) -> crate::lod::Surface {
crate::lod::Surface {
@@ -119,6 +169,7 @@ impl VanillaTerrain {
}
let mut tick_blocks = Vec::with_capacity(registry.len());
let mut tick_states = Vec::new();
let mut block_entity_types = Vec::with_capacity(registry.len());
let mut last: Option<&str> = None;
let mut index = 0u32;
for id in 0..registry.len() {
@@ -133,20 +184,31 @@ impl VanillaTerrain {
}
last = Some(name);
tick_blocks.push(index);
block_entity_types.push(crate::lan::chunks::block_entity_type(name));
}
Ok(Self {
generator,
biome_map,
loot,
structure_mobs: Arc::new(StructureMobFinalizer::new(
dir.parent().unwrap_or(dir).to_owned(),
dimension,
)),
query: std::sync::Mutex::new(None),
tick_blocks,
tick_states,
block_entity_types,
seed,
dimension: dimension.to_owned(),
last_proto: std::sync::atomic::AtomicU64::new(0),
created: std::time::Instant::now(),
})
}
/// The difficulty (0 peaceful to 3 hard) and overworld clock structure
/// mobs are finalized with.
pub fn set_spawn_conditions(&self, difficulty: u8, day_time: i64) {
self.structure_mobs.set_conditions(difficulty, day_time);
}
/// A proto chunk's blocks, biomes, scheduled ticks and post-processing
/// marks as a column.
fn column(&self, chunk: &ProtoChunk) -> Chunk {
@@ -362,7 +424,9 @@ pub fn shared_data(
impl ChunkGenerator for VanillaTerrain {
type Worker = GeneratorWorker;
fn worker(&self) -> GeneratorWorker {
self.generator.worker()
let mut worker = self.generator.worker();
worker.set_structure_mobs(self.structure_mobs.clone());
worker
}
fn lod_sampler(self: Arc<Self>) -> Box<dyn LodSampler> {
Box::new(VanillaLodSampler::new(self))
@@ -561,7 +625,7 @@ impl ChunkGenerator for VanillaTerrain {
// The block entities Horizon does not model (decorated pots with their
// sherds and loot table, brushable blocks) stay as placed, like a
// loaded chunk's.
let unmodelled: Vec<Tag> = chunk
let mut unmodelled: Vec<Tag> = chunk
.block_entities
.iter()
.filter(|(pos, _)| {
@@ -581,6 +645,7 @@ impl ChunkGenerator for VanillaTerrain {
Some(Tag::Compound(nbt))
})
.collect();
add_default_block_entities(&self.block_entity_types, &mut out, &mut unmodelled);
if !unmodelled.is_empty() || !rolled_loot.is_empty() {
let mut extras = out
.saved
@@ -604,3 +669,35 @@ impl ChunkGenerator for VanillaTerrain {
out
}
}
#[cfg(test)]
mod default_block_entity_tests {
use super::*;
#[test]
fn generated_blocks_get_their_block_entities() {
let mut out = Chunk::empty(-2, 3);
out.set(4, -40, 9, 7);
out.set(5, -40, 9, 6);
let mut kinds = vec![None; 8];
kinds[6] = Some("minecraft:potent_sulfur");
kinds[7] = Some("minecraft:sculk_sensor");
let mut raw = vec![];
add_default_block_entities(&kinds, &mut out, &mut raw);
assert!(matches!(
out.block_entities[..],
[((-28, -40, 57), crate::containers::BlockEntity::Sculk(_))]
));
assert_eq!(raw.len(), 1);
assert_eq!(
raw[0].get("id"),
Some(&Tag::String("minecraft:potent_sulfur".into()))
);
add_default_block_entities(&kinds, &mut out, &mut raw);
assert_eq!(
(out.block_entities.len(), raw.len()),
(1, 1),
"a placed block entity is kept, not doubled"
);
}
}
@@ -0,0 +1,446 @@
//! `Mob.finalizeSpawn(level, level.getCurrentDifficultyAt(pos), STRUCTURE, null)`
//! of the mobs structures place (StructureTemplate.placeEntities with
//! finalizeEntities, ocean ruin drowned, mansion illagers, witch huts,
//! monuments), run as decoration places them, with the WorldGenRegion's random.
use crate::{
enchant::Enchantments,
entity_nbt,
items::Items,
mobs::{
Mob, MobType, MobTypes,
finalize::{self, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries},
spawning::{LocalDifficulty, MOON_BRIGHTNESS},
},
};
use chrono::Datelike;
use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource, XoroshiroRandom},
};
use horizon_world::{
nbt::{Compound, Tag},
worldgen::{generator::StructureMobs, structure::legacy::PieceRandom},
};
use std::{
collections::{HashMap, HashSet},
path::PathBuf,
sync::{
Arc, OnceLock,
atomic::{AtomicI64, AtomicU8, Ordering},
},
};
struct Data {
types: HashMap<String, Arc<MobType>>,
biome_tags: HashMap<String, HashSet<String>>,
registries: SpawnRegistries,
enchantments: Enchantments,
items: Items,
camel_husk: (f32, f32),
}
fn load(root: &std::path::Path) -> Option<Data> {
let types = MobTypes::load(root).ok()?.types;
let camel = types.get("minecraft:camel_husk")?;
let camel_husk = (camel.width as f32, camel.height as f32);
Some(Data {
types: types.into_iter().map(|(k, t)| (k, Arc::new(t))).collect(),
biome_tags: crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(),
registries: SpawnRegistries::load(root),
enchantments: Enchantments::load(root),
items: Items::tags_only(root).ok()?,
camel_husk,
})
}
pub struct StructureMobFinalizer {
root: PathBuf,
dimension: String,
data: OnceLock<Option<Data>>,
/// The level's difficulty (0 peaceful to 3 hard) and overworld clock.
difficulty: AtomicU8,
day_time: AtomicI64,
}
impl StructureMobFinalizer {
pub fn new(root: PathBuf, dimension: &str) -> Self {
Self {
root,
dimension: dimension.to_owned(),
data: OnceLock::new(),
difficulty: AtomicU8::new(2),
day_time: AtomicI64::new(0),
}
}
pub fn set_conditions(&self, difficulty: u8, day_time: i64) {
self.difficulty.store(difficulty, Ordering::Relaxed);
self.day_time.store(day_time, Ordering::Relaxed);
}
}
struct Level<'a> {
data: &'a Data,
biome: &'a str,
structures: &'a [String],
difficulty: u8,
day_time: i64,
next_id: u32,
}
impl FinalizeLevel for Level<'_> {
fn biome(&self, _: [i32; 3]) -> String {
self.biome.to_owned()
}
fn biome_tag(&self, tag: &str, _: [i32; 3]) -> bool {
self.data
.biome_tags
.get(tag)
.is_some_and(|b| b.contains(self.biome))
}
fn structures_with_piece_at(&self, _: [i32; 3]) -> Vec<String> {
self.structures.to_vec()
}
fn moon_phase(&self, _: [i32; 3]) -> usize {
self.day_time.div_euclid(24000).rem_euclid(8) as usize
}
fn spawning_monsters(&self) -> bool {
self.difficulty != 0
}
// No block collision: only a husk's camel asks, and no structure places husks.
fn no_collision(&self, _: Aabb) -> bool {
true
}
// WorldGenRegion holds no entities.
fn free_chicken(&self, _: Aabb) -> Option<u32> {
None
}
fn ride_chicken(&mut self, _: u32, _: u32) {}
fn game_time(&self) -> i64 {
self.day_time
}
fn halloween(&self) -> bool {
let today = chrono::Local::now();
(today.month(), today.day()) == (10, 31)
}
fn create(&mut self, kind: &str, _: Reason) -> Option<Mob> {
if self.difficulty == 0 && !finalize::allowed_in_peaceful(kind) {
return None;
}
let t = self.data.types.get(kind)?.clone();
self.next_id += 1;
Some(Mob::new(self.next_id, t, Vec3::ZERO, 0.0))
}
}
fn run<R: RandomSource>(
level: &mut Level<'_>,
random: &mut R,
difficulty: LocalDifficulty,
data: &SpawnData<'_>,
m: &mut Mob,
) -> Vec<Mob> {
let mut cx = Ctx {
level,
random,
difficulty,
data,
created: Vec::new(),
};
cx.finalize(m, Reason::Structure, None);
cx.created
}
/// The saved compound of mob `i` with the mobs riding it under `Passengers`.
fn tree(mobs: &[(Mob, Option<Tag>)], i: usize, dimension: &str) -> Compound {
let (m, raw) = &mobs[i];
let Tag::Compound(mut c) = entity_nbt::mob_to_nbt(m, [0; 4], raw.as_ref()) else {
return Compound::new();
};
c.remove(&"UUID".into());
entity_nbt::put_brain(&mut c, m, dimension);
let riders: Vec<Tag> = (0..mobs.len())
.filter(|&j| mobs[j].0.extra.mount == Some(m.id))
.map(|j| Tag::Compound(tree(mobs, j, dimension)))
.collect();
if !riders.is_empty() {
c.insert("Passengers".into(), Tag::List(riders));
}
c
}
impl StructureMobs for StructureMobFinalizer {
fn finalize(
&self,
nbt: &mut Compound,
biome: &str,
structures: &[String],
random: &mut dyn PieceRandom,
) -> bool {
let Some(data) = self.data.get_or_init(|| {
let data = load(&self.root);
if data.is_none() {
log::error!("Horizon: no mob data, structure mobs are finalized when loaded");
}
data
}) else {
return false;
};
let mut raw = Tag::Compound(nbt.clone());
if let Tag::Compound(c) = &mut raw {
c.remove(&"horizon:finalize".into());
}
let Some(mut m) = entity_nbt::mob_from_nbt(&raw, &data.types, 1) else {
// Not a mob: vanilla finalizes only Mob instances.
return true;
};
let base = self.difficulty.load(Ordering::Relaxed);
let day_time = self.day_time.load(Ordering::Relaxed);
let mut level = Level {
data,
biome,
structures,
difficulty: base,
day_time,
next_id: 1,
};
let moon = MOON_BRIGHTNESS[level.moon_phase([0; 3])];
// WorldGenRegion.getCurrentDifficultyAt: no inhabited time.
let difficulty = LocalDifficulty::new(base, day_time, 0, moon);
let spawn = SpawnData {
registries: &data.registries,
enchantments: &data.enchantments,
items: &data.items,
camel_husk_size: data.camel_husk,
};
let any = random.as_any();
let created = if let Some(r) = any.downcast_mut::<LegacyRandom>() {
run(&mut level, r, difficulty, &spawn, &mut m)
} else if let Some(r) = any.downcast_mut::<XoroshiroRandom>() {
run(&mut level, r, difficulty, &spawn, &mut m)
} else {
log::error!("Horizon: unknown region random, structure mobs are finalized when loaded");
return false;
};
let mut mobs = vec![(m, Some(raw))];
mobs.extend(created.into_iter().map(|c| (c, None)));
let root = mobs
.iter()
.position(|(m, _)| m.extra.mount.is_none())
.unwrap_or(0);
*nbt = tree(&mobs, root, &self.dimension);
true
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The bastion's crossbow piglin keeps its crossbow (STRUCTURE skips
/// createSpawnWeapon) and saves what Piglin.addAdditionalSaveData writes.
#[test]
fn bastion_crossbow_piglin_finalizes_as_structure() {
let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else {
return;
};
let file = root.join("worldgen/structure/minecraft/bastion/mobs/crossbow_piglin.nbt");
let mut bytes = Vec::new();
std::io::Read::read_to_end(
&mut flate2::read::GzDecoder::new(std::fs::File::open(file).unwrap()),
&mut bytes,
)
.unwrap();
let limits = horizon_world::nbt::Limits::templates();
let template = horizon_world::nbt::read_named(&bytes, limits)
.unwrap()
.0
.tag;
let Some(Tag::List(entities)) = template.get("entities") else {
panic!("no entities");
};
let Some(Tag::Compound(mut nbt)) = entities[0].get("nbt").cloned() else {
panic!("no nbt");
};
nbt.remove(&"UUID".into());
let hook = StructureMobFinalizer::new(root, "minecraft:the_nether");
let mut random = LegacyRandom::new(12345);
hook.finalize(&mut nbt, "minecraft:nether_wastes", &[], &mut random);
let keys: Vec<String> = {
let mut k: Vec<String> = nbt.keys().map(|k| k.to_string_lossy()).collect();
k.sort();
k
};
assert_eq!(
keys,
[
"AbsorptionAmount",
"Air",
"Brain",
"CanPickUpLoot",
"CannotHunt",
"DeathTime",
"FallFlying",
"Fire",
"Health",
"HurtTime",
"Inventory",
"Invulnerable",
"IsBaby",
"IsImmuneToZombification",
"LeftHanded",
"Motion",
"OnGround",
"PersistenceRequired",
"PortalCooldown",
"Pos",
"Rotation",
"TimeInOverworld",
"attributes",
"current_impulse_context_reset_grace_time",
"equipment",
"fall_distance",
"id",
]
);
let tag = Tag::Compound(nbt);
let held = tag.get("equipment").and_then(|e| e.get("mainhand"));
assert!(
matches!(held.and_then(|h| h.get("id")), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:crossbow")
);
let hunted = tag
.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|m| m.get("minecraft:hunted_recently"));
assert!(matches!(
hunted.and_then(|h| h.get("ttl")),
Some(Tag::Long(600..=2400))
));
let Some(Tag::List(attributes)) = tag.get("attributes") else {
panic!("no attributes");
};
assert!(attributes.iter().any(|a| {
matches!(a.get("id"), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:follow_range")
&& matches!(a.get("modifiers"), Some(Tag::List(m)) if m.len() == 1)
}));
}
fn id(t: Option<&Tag>) -> String {
match t.and_then(|t| t.get("id")) {
Some(Tag::String(s)) => s.to_string_lossy().trim_start_matches("minecraft:").into(),
_ => "-".into(),
}
}
/// What a vanilla world saves of a structure mob that finalizeSpawn decides.
fn describe(mob: &Tag) -> String {
let eq = mob.get("equipment");
let gear: Vec<String> = ["mainhand", "head", "chest", "legs", "feet"]
.iter()
.map(|slot| id(eq.and_then(|e| e.get(slot))))
.collect();
let ttl = match mob
.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|m| m.get("minecraft:hunted_recently"))
.and_then(|h| h.get("ttl"))
{
Some(Tag::Long(t)) => t.to_string(),
_ => "-".into(),
};
let bonus = crate::entity_nbt::spawn_bonus(mob).unwrap_or(f64::NAN);
let flag = |k: &str| matches!(mob.get(k), Some(Tag::Byte(1)));
let riders = match mob.get("Passengers") {
Some(Tag::List(p)) => format!(
" [{}]",
p.iter().map(describe).collect::<Vec<_>>().join("; ")
),
_ => String::new(),
};
format!(
"{} {} ttl={ttl} bonus={bonus:.6} left={} baby={}{riders}",
id(Some(mob)),
gear.join(","),
flag("LeftHanded"),
flag("IsBaby") || matches!(mob.get("Age"), Some(Tag::Int(a)) if *a < 0),
)
}
/// The described entities of chunk (x, z) after decorating the 3x3 around it.
fn chunk_mobs(
root: &std::path::Path,
seed: i64,
dimension: &str,
x: i32,
z: i32,
) -> Vec<String> {
use crate::streaming::{ChunkGenerator, Proto};
let assets = crate::assets::Assets::load(root).unwrap();
let biomes = crate::biome::Biomes::load(root).unwrap();
let terrain = super::super::VanillaTerrain::for_dimension(
&root.join("worldgen"),
assets.registry,
&biomes,
seed,
dimension,
)
.unwrap();
let mut worker = terrain.worker();
let mut region: [Proto; 9] = std::array::from_fn(|i| {
terrain.proto(&mut worker, x + i as i32 % 3 - 1, z + i as i32 / 3 - 1)
});
terrain.decorate(&mut worker, &mut region);
let center = std::mem::replace(&mut region[4], Box::new(()));
let mut got: Vec<String> = terrain
.finish(center)
.entities
.iter()
.map(describe)
.collect();
got.sort();
got
}
/// Seed 12345's bastion at chunk (-21, 8): the mobs of chunk (-23, 8) as two
/// vanilla 26.3 runs saved them (weapons and armour, hunting memory, follow
/// range bonus, handedness), from the region random of that chunk. The
/// memories are as placed: vanilla saved them 13 brain ticks later.
#[test]
fn bastion_chunk_mobs_match_vanilla() {
let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else {
return;
};
let got = chunk_mobs(&root, 12345, "minecraft:the_nether", -23, 8);
let mut expected = [
"piglin golden_sword,-,golden_chestplate,-,- ttl=1760 bonus=0.013784",
"piglin crossbow,-,-,-,- ttl=806 bonus=-0.011458",
"piglin golden_sword,-,-,-,- ttl=1315 bonus=-0.084585",
"piglin golden_sword,-,-,-,- ttl=1489 bonus=-0.038292",
"piglin_brute golden_axe,-,-,-,- ttl=- bonus=-0.020574",
"piglin crossbow,-,-,-,- ttl=1620 bonus=-0.079135",
"hoglin -,-,-,-,- ttl=- bonus=-0.012052",
"piglin golden_sword,-,-,-,- ttl=783 bonus=-0.077071",
"piglin crossbow,-,-,golden_leggings,- ttl=1431 bonus=0.007058",
]
.map(|e| format!("{e} left=false baby=false"));
expected.sort();
assert_eq!(got, expected);
}
/// Seed 12345's ocean ruin at (53, 39, 424): Drowned.finalizeSpawn mounts the
/// trident drowned on a zombie nautilus, as vanilla saved chunk (3, 26).
#[test]
fn ocean_ruin_drowned_match_vanilla() {
let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else {
return;
};
let got = chunk_mobs(&root, 12345, "minecraft:overworld", 3, 26);
let d = |gear: &str, bonus: &str| {
format!("drowned {gear},-,-,-,- ttl=- bonus={bonus} left=false baby=false")
};
let mut expected = vec![
d("-", "0.001996"),
format!(
"zombie_nautilus -,-,-,-,- ttl=- bonus=-0.044983 left=false baby=false [{}]",
d("trident", "-0.045604")
),
d("fishing_rod", "-0.059079"),
d("-", "0.021658"),
];
expected.sort();
assert_eq!(got, expected);
}
}
+1
View File
@@ -186,6 +186,7 @@ impl Server {
attributes: Vec::new(),
bed: None,
living_flags: 0,
body: Default::default(),
};
let mut ctx = TickCtx {
world: &mut self.world,
@@ -1,7 +1,7 @@
id = "beacons"
name = "Beacons"
version = "0.1.0"
description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome."
description = "/beacon [height] lights a pillar of glowstone beside you; /ground [pos] says what you are standing on (or what is at pos), and in which biome."
authors = ["Horizon"]
api = "0.3"
side = "server"
@@ -1,9 +1,12 @@
//! Example Horizon server mod (`docs/mods.md`, "Server mods") with
//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east
//! of the player, `/ground` reads the block under their feet and the biome.
use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world};
//! capability `world` and typed commands: `/beacon [height]` lights a
//! pillar of glowstone two blocks east of the player, `/ground [pos]` reads
//! the block under their feet (or at `pos`) and its biome.
use horizon_mod_sdk::server::{
Args, Argument, BlockChange, Player, Registration, ServerMod, players, world,
};
/// How tall `/beacon` builds.
/// How tall `/beacon` builds when no height is given.
const HEIGHT: i32 = 4;
struct Beacons;
@@ -17,10 +20,10 @@ fn feet(player: &Player) -> (i32, i32, i32) {
)
}
/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up.
fn pillar(player: &Player) -> Vec<BlockChange> {
/// The pillar beside `player`: `height` blocks of glowstone, from their feet up.
fn pillar(player: &Player, height: i32) -> Vec<BlockChange> {
let (x, y, z) = feet(player);
(0..HEIGHT)
(0..height)
.map(|dy| BlockChange {
x: x + 2,
y: y + dy,
@@ -34,7 +37,12 @@ impl ServerMod for Beacons {
fn init() -> Result<(Self, Registration), String> {
Ok((
Beacons,
Registration::new().command("beacon").command("ground"),
Registration::new()
.command_with(
"beacon",
[Argument::integer("height", Some(1), Some(64)).optional()],
)
.command_with("ground", [Argument::block_pos("pos").optional()]),
))
}
@@ -42,11 +50,12 @@ impl ServerMod for Beacons {
&mut self,
player: &Player,
name: &str,
_args: &str,
args: &Args,
) -> Result<Option<String>, String> {
let (x, y, z) = feet(player);
if name == "beacon" {
world::set_blocks(&player.dimension, &pillar(player))?;
let height = args.integer("height").unwrap_or(HEIGHT);
world::set_blocks(&player.dimension, &pillar(player, height))?;
players::broadcast(&format!(
"{} lit a beacon at {} {y} {z}",
player.name,
@@ -54,10 +63,17 @@ impl ServerMod for Beacons {
));
return Ok(None);
}
let below = world::get_block(&player.dimension, x, y - 1, z)
.ok_or("The ground under you isn't loaded")?;
let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default();
Ok(Some(format!("You are standing on {below} in {biome}")))
let (bx, by, bz) = match args.block_pos("pos") {
Some(p) => (p.x, p.y, p.z),
None => (x, y - 1, z),
};
let block =
world::get_block(&player.dimension, bx, by, bz).ok_or("That block isn't loaded")?;
let biome = world::get_biome(&player.dimension, bx, by, bz).unwrap_or_default();
if args.block_pos("pos").is_some() {
return Ok(Some(format!("{bx} {by} {bz} is {block} in {biome}")));
}
Ok(Some(format!("You are standing on {block} in {biome}")))
}
}
@@ -79,7 +95,7 @@ mod tests {
game_mode: horizon_mod_sdk::server::GameMode::Survival,
health: 20.0,
};
let blocks = pillar(&p);
let blocks = pillar(&p, HEIGHT);
assert_eq!(blocks.len(), HEIGHT as usize);
assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3));
assert_eq!(blocks[3].y, 67);
@@ -1,4 +1,4 @@
# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east.
# /ground [pos] reads the block under the player (or at pos) and the biome; /beacon [height] sets glowstone two to the east.
[[step]]
join = "Alex"
@@ -20,3 +20,20 @@ expect.blocks = [
player = { x = 10.5, z = 10.5 }
command = "ground"
expect.feedback = "You are standing on minecraft:air in minecraft:plains"
# Typed arguments: a height, a position relative to the player.
[[step]]
player = { x = 5.5, y = 64.0, z = 5.5 }
command = "beacon 2"
expect.blocks = [
{ x = 7, y = 65, z = 5, state = "minecraft:glowstone" },
{ x = 7, y = 66, z = 5, state = "minecraft:air" },
]
[[step]]
command = "beacon 65"
expect.error = "Integer must not be more than 64, found 65"
[[step]]
command = "ground ~2 ~1 ~"
expect.feedback = "7 65 5 is minecraft:glowstone in minecraft:plains"
@@ -1,9 +1,10 @@
//! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each
//! player who joins, announces a newcomer to everyone (the players it has
//! seen are kept in `storage`), `/online` lists who is on and where, and
//! `/mined` counts the blocks the player broke since the server started.
//! `/mined [player]` counts the blocks a player broke since the server
//! started (typed arguments: the chat box completes the player's name).
use horizon_mod_sdk::{
server::{BlockPos, Player, Registration, ServerMod, players},
server::{Args, Argument, BlockPos, Player, Registration, ServerMod, players},
storage,
};
use std::collections::HashMap;
@@ -25,8 +26,8 @@ impl ServerMod for Welcome {
})
.unwrap_or_default();
let hooks = Registration::new()
.command("online")
.command("mined")
.command_with("online", [])
.command_with("mined", [Argument::player("player").optional()])
.on_joins()
.on_blocks();
Ok((
@@ -55,7 +56,7 @@ impl ServerMod for Welcome {
&mut self,
player: &Player,
name: &str,
_args: &str,
args: &Args,
) -> Result<Option<String>, String> {
Ok(Some(match name {
"online" => players::online()
@@ -69,10 +70,16 @@ impl ServerMod for Welcome {
})
.collect::<Vec<_>>()
.join(", "),
_ => {
let n = self.mined.get(&player.id).copied().unwrap_or(0);
format!("You broke {n} block(s)")
}
_ => match args.player("player") {
Some(other) if other.id != player.id => {
let n = self.mined.get(&other.id).copied().unwrap_or(0);
format!("{} broke {n} block(s)", other.name)
}
_ => {
let n = self.mined.get(&player.id).copied().unwrap_or(0);
format!("You broke {n} block(s)")
}
},
}))
}
@@ -1,4 +1,4 @@
# /online lists the players and their dimension; /mined counts the acting player's blocks.
# /online lists the players and their dimension; /mined [player] counts a player's blocks.
[[step]]
join = "Alex"
@@ -29,3 +29,18 @@ expect.feedback = "You broke 2 block(s)"
as = "Steve"
command = "mined"
expect.feedback = "You broke 0 block(s)"
[[step]]
as = "Steve"
command = "mined alex"
expect.feedback = "Alex broke 2 block(s)"
# The server parses the arguments before the mod: vanilla's errors.
[[step]]
as = "Steve"
command = "mined Herobrine"
expect.error = "No player was found"
[[step]]
command = "online now"
expect.error = "Incorrect argument for command"
+127 -8
View File
@@ -194,7 +194,10 @@ pub mod server {
},
});
pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration};
pub use exports::horizon::mods::server_events::{
Argument, ArgumentKind, ArgumentValue, BlockPos, Guest as __Guest, Registration,
ServerCommand,
};
pub use horizon::mods::players::{self, GameMode, Player};
pub use horizon::mods::world::{self, BlockChange};
@@ -211,13 +214,14 @@ pub mod server {
fn player_left(&mut self, _player: &Player) {}
/// A chat message a player sent, when [`Registration::chat`] is set.
fn chat(&mut self, _player: &Player, _text: &str) {}
/// `/name args` typed by `player`. `Ok(Some(text))` is their
/// feedback, `Err(text)` their error in red.
/// `/name args` typed by `player`, parsed as the command's
/// arguments say ([`Registration::command_with`]). `Ok(Some(text))`
/// is their feedback, `Err(text)` their error in red.
fn command(
&mut self,
_player: &Player,
_name: &str,
_args: &str,
_args: &Args,
) -> Result<Option<String>, String> {
Err("This command does nothing".into())
}
@@ -237,9 +241,23 @@ pub mod server {
blocks: false,
}
}
/// Adds `/name`.
pub fn command(mut self, name: &str) -> Self {
self.commands.push(name.into());
/// Adds `/name`, taking free text ([`Args::text`]): one optional
/// `text` argument named `args`.
pub fn command(self, name: &str) -> Self {
self.command_with(name, [Argument::text("args").optional()])
}
/// Adds `/name` with typed arguments (none: nothing after the name):
/// players' chat boxes complete and check them, and the server
/// parses them into [`Args`].
pub fn command_with(
mut self,
name: &str,
arguments: impl IntoIterator<Item = Argument>,
) -> Self {
self.commands.push(ServerCommand {
name: name.into(),
arguments: arguments.into_iter().collect(),
});
self
}
pub fn on_tick(mut self) -> Self {
@@ -264,6 +282,105 @@ pub mod server {
Self::new()
}
}
impl Argument {
fn of(name: &str, kind: ArgumentKind) -> Self {
Self {
name: name.into(),
kind,
optional: false,
}
}
/// One word: letters, digits and `_ - . +`.
pub fn word(name: &str) -> Self {
Self::of(name, ArgumentKind::Word)
}
/// The rest of the line: only last.
pub fn text(name: &str) -> Self {
Self::of(name, ArgumentKind::Text)
}
/// A whole number, at least `min` and at most `max` when given.
pub fn integer(name: &str, min: Option<i32>, max: Option<i32>) -> Self {
Self::of(name, ArgumentKind::Integer((min, max)))
}
pub fn number(name: &str) -> Self {
Self::of(name, ArgumentKind::Number)
}
pub fn boolean(name: &str) -> Self {
Self::of(name, ArgumentKind::Boolean)
}
/// One online player: a name, `@s` or `@p`.
pub fn player(name: &str) -> Self {
Self::of(name, ArgumentKind::Player)
}
/// `x y z`, each one also `~` or `~n`.
pub fn block_pos(name: &str) -> Self {
Self::of(name, ArgumentKind::BlockPos)
}
/// May be left out; optional arguments come after the required ones.
pub fn optional(mut self) -> Self {
self.optional = true;
self
}
}
/// A command's arguments: the line as typed, and the values the server
/// parsed from it, by argument name.
#[derive(Clone, Debug, Default)]
pub struct Args {
text: String,
values: Vec<(String, ArgumentValue)>,
}
impl Args {
pub fn new(text: String, values: Vec<(String, ArgumentValue)>) -> Self {
Self { text, values }
}
/// The line after the command's name, as typed.
pub fn text(&self) -> &str {
&self.text
}
/// The value of argument `name`; `None` when it was left out.
pub fn get(&self, name: &str) -> Option<&ArgumentValue> {
self.values.iter().find(|(n, _)| n == name).map(|(_, v)| v)
}
pub fn integer(&self, name: &str) -> Option<i32> {
match self.get(name)? {
ArgumentValue::Integer(n) => Some(*n),
_ => None,
}
}
pub fn number(&self, name: &str) -> Option<f64> {
match self.get(name)? {
ArgumentValue::Number(n) => Some(*n),
_ => None,
}
}
/// A `word` or `text` argument.
pub fn string(&self, name: &str) -> Option<&str> {
match self.get(name)? {
ArgumentValue::Word(s) | ArgumentValue::Text(s) => Some(s),
_ => None,
}
}
pub fn boolean(&self, name: &str) -> Option<bool> {
match self.get(name)? {
ArgumentValue::Boolean(b) => Some(*b),
_ => None,
}
}
pub fn player(&self, name: &str) -> Option<&Player> {
match self.get(name)? {
ArgumentValue::Player(p) => Some(p),
_ => None,
}
}
pub fn block_pos(&self, name: &str) -> Option<BlockPos> {
match self.get(name)? {
ArgumentValue::BlockPos(p) => Some(*p),
_ => None,
}
}
}
}
/// Exports a [`ServerMod`](server::ServerMod) as the component's
@@ -273,7 +390,7 @@ macro_rules! export_server_mod {
($t:ty) => {
const _: () = {
use ::std::cell::RefCell;
use $crate::server::{BlockPos, Player, Registration, ServerMod};
use $crate::server::{Args, ArgumentValue, BlockPos, Player, Registration, ServerMod};
::std::thread_local! {
static STATE: RefCell<Option<$t>> = const { RefCell::new(None) };
}
@@ -307,8 +424,10 @@ macro_rules! export_server_mod {
player: Player,
name: String,
args: String,
values: Vec<(String, ArgumentValue)>,
) -> Result<Option<String>, String> {
let mut out = Err("The mod is not running".to_string());
let args = Args::new(args, values);
with(|m| out = m.command(&player, &name, &args));
out
}
+58 -10
View File
@@ -680,10 +680,61 @@ interface %world {
interface server-events {
use players.{player};
record block-pos {
x: s32,
y: s32,
z: s32,
}
/// What an argument of a command takes. The server sends each command
/// and its arguments to players' games, whose chat box completes and
/// colours them as vanilla's; the server parses them before the mod's
/// `command` hook gets their values.
variant argument-kind {
/// One word: letters, digits and `_ - . +`.
word,
/// The rest of the line, spaces included: only last.
text,
/// A whole number, within the bounds given.
integer(tuple<option<s32>, option<s32>>),
/// A number with or without decimals.
number,
/// `true` or `false`.
boolean,
/// One online player: a name, or `@s` or `@p` (whoever typed it,
/// as vanilla picks for a player).
player,
/// A block position: three whole numbers, each one also `~` or
/// `~n`, relative to whoever typed it.
block-pos,
}
record argument {
/// Shown in the chat box's hint (`<height>`) and the key of its value.
name: string,
kind: argument-kind,
/// Optional arguments come after every required one.
optional: bool,
}
record server-command {
/// Without the slash. A name vanilla already uses is refused
/// (vanilla's command runs).
name: string,
/// In order; none: the command takes nothing after its name. Free
/// text is one optional `text` argument.
arguments: list<argument>,
}
/// An argument's value, parsed as its kind says.
variant argument-value {
word(string),
text(string),
integer(s32),
number(f64),
boolean(bool),
player(player),
block-pos(block-pos),
}
record registration {
/// Commands players may type, without the slash. A name vanilla
/// already uses is refused (vanilla's command runs).
commands: list<string>,
/// Commands players may type.
commands: list<server-command>,
/// Call `tick` every server tick (20 per second).
tick: bool,
/// Call `player-joined` and `player-left`.
@@ -693,11 +744,6 @@ interface server-events {
/// Call `block-broken` and `block-placed`.
blocks: bool,
}
record block-pos {
x: s32,
y: s32,
z: s32,
}
/// Once, after loading. An error keeps the mod off and is logged.
init: func() -> result<registration, string>;
/// Each server tick, with the server's tick counter.
@@ -709,8 +755,10 @@ interface server-events {
/// A chat message a player sent, as plain text.
chat: func(player: player, text: string);
/// `/name args` typed by `player`: ok(some(text)) is their feedback,
/// err(text) their error in red.
command: func(player: player, name: string, args: string) -> result<option<string>, string>;
/// err(text) their error in red. `values` holds each argument given, by
/// name, in order (an optional one left out isn't there); a line that
/// doesn't parse never reaches the mod: the player gets vanilla's error.
command: func(player: player, name: string, args: string, values: list<tuple<string, argument-value>>) -> result<option<string>, string>;
/// A player broke the block at `pos` in their dimension: `state` is what
/// was there, as `minecraft:oak_log[axis=y]`.
block-broken: func(player: player, pos: block-pos, state: string);
+301
View File
@@ -0,0 +1,301 @@
//! Server mods' typed commands: an argument line parsed as the command's
//! arguments say, the way vanilla's Brigadier parsers read them, with
//! vanilla's error messages. The game sends the same arguments to players'
//! command trees, so their chat box checks them before the server does.
use crate::runtime::{Argument, ArgumentKind, ArgumentValue, BlockPos, ServerPlayer};
/// The values of `args`, typed by `player`, for `arguments` (in order;
/// optional ones left out aren't there), or the error the player reads.
pub fn parse(
arguments: &[Argument],
args: &str,
player: &ServerPlayer,
online: &[ServerPlayer],
) -> Result<Vec<(String, ArgumentValue)>, String> {
let mut values = Vec::new();
let mut rest = args;
for (i, argument) in arguments.iter().enumerate() {
if i > 0 && !rest.is_empty() {
rest = rest.strip_prefix(' ').ok_or(
"Expected whitespace to end one argument, but found trailing data".to_string(),
)?;
}
if rest.is_empty() {
if argument.optional {
break;
}
return Err("Unknown or incomplete command, see below for error".into());
}
let (value, after) = one(&argument.kind, rest, player, online)?;
values.push((argument.name.clone(), value));
rest = after;
}
if !rest.is_empty() {
return Err("Incorrect argument for command".into());
}
Ok(values)
}
/// StringReader.isAllowedInUnquotedString.
fn unquoted(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+')
}
/// The unquoted string at the start of `s`, and what follows it.
fn word(s: &str) -> (&str, &str) {
let end = s.find(|c: char| !unquoted(c)).unwrap_or(s.len());
s.split_at(end)
}
/// One argument from the start of `s`, and what follows it.
fn one<'a>(
kind: &ArgumentKind,
s: &'a str,
player: &ServerPlayer,
online: &[ServerPlayer],
) -> Result<(ArgumentValue, &'a str), String> {
Ok(match kind {
ArgumentKind::Word => {
let (w, rest) = word(s);
if w.is_empty() {
return Err("Expected string".into());
}
(ArgumentValue::Word(w.into()), rest)
}
ArgumentKind::Text => (ArgumentValue::Text(s.into()), ""),
ArgumentKind::Integer((min, max)) => {
let (n, rest) = integer(s)?;
if let Some(min) = min.filter(|m| n < *m) {
return Err(format!("Integer must not be less than {min}, found {n}"));
}
if let Some(max) = max.filter(|m| n > *m) {
return Err(format!("Integer must not be more than {max}, found {n}"));
}
(ArgumentValue::Integer(n), rest)
}
ArgumentKind::Number => {
let (n, rest) = double(s)?;
(ArgumentValue::Number(n), rest)
}
ArgumentKind::Boolean => {
let (w, rest) = word(s);
let b = match w {
"true" => true,
"false" => false,
"" => return Err("Expected bool".into()),
_ => {
return Err(format!(
"Invalid boolean, expected 'true' or 'false' but found '{w}'"
));
}
};
(ArgumentValue::Boolean(b), rest)
}
ArgumentKind::Player => {
if let Some(selector) = s.strip_prefix('@') {
let (kind, rest) = word(selector);
return match kind {
// A player's @p is themselves (the nearest to where they are).
"s" | "p" => Ok((ArgumentValue::Player(player.clone()), rest)),
"a" | "e" | "r" | "n" => {
Err("Only one player is allowed, but the provided selector allows more than one".into())
}
_ => Err(format!("Unknown selector type '@{kind}'")),
};
}
let (name, rest) = word(s);
if name.is_empty() {
return Err("Invalid name or UUID".into());
}
let found = online
.iter()
.find(|p| p.name.eq_ignore_ascii_case(name))
.ok_or("No player was found")?;
(ArgumentValue::Player(found.clone()), rest)
}
ArgumentKind::BlockPos => {
let (x, rest) = coordinate(s, player.x)?;
let rest = rest
.strip_prefix(' ')
.ok_or("Incomplete (expected 3 coordinates)")?;
let (y, rest) = coordinate(rest, player.y)?;
let rest = rest
.strip_prefix(' ')
.ok_or("Incomplete (expected 3 coordinates)")?;
let (z, rest) = coordinate(rest, player.z)?;
(ArgumentValue::BlockPos(BlockPos { x, y, z }), rest)
}
})
}
/// StringReader.readInt.
fn integer(s: &str) -> Result<(i32, &str), String> {
let end = s
.find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.'))
.unwrap_or(s.len());
let (n, rest) = s.split_at(end);
if n.is_empty() {
return Err("Expected integer".into());
}
let n = n.parse().map_err(|_| format!("Invalid integer '{n}'"))?;
Ok((n, rest))
}
/// StringReader.readDouble.
fn double(s: &str) -> Result<(f64, &str), String> {
let end = s
.find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.'))
.unwrap_or(s.len());
let (n, rest) = s.split_at(end);
if n.is_empty() {
return Err("Expected double".into());
}
let n = n.parse().map_err(|_| format!("Invalid double '{n}'"))?;
Ok((n, rest))
}
/// WorldCoordinate.parseInt, then BlockPos.containing: `~` and `~n` from
/// `base`, a whole number as it is.
fn coordinate(s: &str, base: f64) -> Result<(i32, &str), String> {
if s.starts_with('^') {
return Err(
"Cannot mix world & local coordinates (everything must either use ^ or not)".into(),
);
}
if let Some(offset) = s.strip_prefix('~') {
if offset.is_empty() || offset.starts_with(' ') {
return Ok((base.floor() as i32, offset));
}
let (n, rest) = double(offset)?;
return Ok(((base + n).floor() as i32, rest));
}
integer(s)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::GameMode;
fn player(name: &str) -> ServerPlayer {
ServerPlayer {
id: format!("id-{name}"),
name: name.into(),
x: 10.7,
y: 64.0,
z: -3.2,
dimension: "minecraft:overworld".into(),
game_mode: GameMode::Survival,
health: 20.0,
}
}
fn arg(name: &str, kind: ArgumentKind, optional: bool) -> Argument {
Argument {
name: name.into(),
kind,
optional,
}
}
#[test]
fn values_in_order_and_optional_ones_left_out() {
let alex = player("Alex");
let online = [alex.clone(), player("Steve")];
let args = [
arg("who", ArgumentKind::Player, false),
arg("height", ArgumentKind::Integer((Some(1), Some(64))), true),
arg("note", ArgumentKind::Text, true),
];
let v = parse(&args, "steve 5 hello there", &alex, &online).unwrap();
assert_eq!(v[0].0, "who");
assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Steve"));
assert_eq!(v[1], ("height".into(), ArgumentValue::Integer(5)));
assert_eq!(
v[2],
("note".into(), ArgumentValue::Text("hello there".into()))
);
let v = parse(&args, "@s", &alex, &online).unwrap();
assert_eq!(v.len(), 1);
assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Alex"));
}
#[test]
fn vanilla_errors() {
let alex = player("Alex");
let online = [alex.clone()];
let height = [arg(
"height",
ArgumentKind::Integer((Some(1), Some(64))),
false,
)];
let err = |a: &[Argument], s| parse(a, s, &alex, &online).unwrap_err();
assert_eq!(
err(&height, "0"),
"Integer must not be less than 1, found 0"
);
assert_eq!(
err(&height, "65"),
"Integer must not be more than 64, found 65"
);
assert_eq!(err(&height, "x"), "Expected integer");
assert_eq!(err(&height, "1.5"), "Invalid integer '1.5'");
assert_eq!(
err(&height, ""),
"Unknown or incomplete command, see below for error"
);
assert_eq!(err(&height, "3 4"), "Incorrect argument for command");
let who = [arg("who", ArgumentKind::Player, false)];
assert_eq!(err(&who, "Herobrine"), "No player was found");
assert_eq!(err(&who, "@q"), "Unknown selector type '@q'");
let flag = [arg("on", ArgumentKind::Boolean, false)];
assert_eq!(
err(&flag, "yes"),
"Invalid boolean, expected 'true' or 'false' but found 'yes'"
);
let pos = [arg("at", ArgumentKind::BlockPos, false)];
assert_eq!(err(&pos, "1 2"), "Incomplete (expected 3 coordinates)");
}
#[test]
fn block_positions_relative_to_the_player() {
let alex = player("Alex");
let pos = [arg("at", ArgumentKind::BlockPos, false)];
let v = parse(&pos, "~ ~1 ~-0.5", &alex, &[]).unwrap();
assert_eq!(
v[0].1,
ArgumentValue::BlockPos(BlockPos {
x: 10,
y: 65,
z: -4
})
);
let v = parse(&pos, "-5 70 ~", &alex, &[]).unwrap();
assert_eq!(
v[0].1,
ArgumentValue::BlockPos(BlockPos {
x: -5,
y: 70,
z: -4
})
);
}
#[test]
fn free_text_is_an_optional_text_argument() {
let alex = player("Alex");
let free = [arg("args", ArgumentKind::Text, true)];
assert_eq!(parse(&free, "", &alex, &[]), Ok(Vec::new()));
assert_eq!(
parse(&free, "anything at all", &alex, &[]),
Ok(vec![(
"args".into(),
ArgumentValue::Text("anything at all".into())
)])
);
assert_eq!(
parse(&[], "more", &alex, &[]),
Err("Incorrect argument for command".into())
);
assert_eq!(parse(&[], "", &alex, &[]), Ok(Vec::new()));
}
}
+2
View File
@@ -6,6 +6,8 @@
//! Nothing here runs unless a mod is installed and turned on: an empty
//! [`Mods`] makes no engine and every hook returns at once.
pub mod api_level;
#[cfg(feature = "runtime")]
pub mod commands;
pub mod content;
#[cfg(feature = "index")]
pub mod index;

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