Merge remote-tracking branch 'origin/feat/server-entity-attributes' into integ/sh7
This commit is contained in:
@@ -101,6 +101,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
sprinting: false,
|
||||
equipment: Default::default(),
|
||||
health: 20.0,
|
||||
attributes: Vec::new(),
|
||||
};
|
||||
loop {
|
||||
world.game_time += 1;
|
||||
|
||||
@@ -336,73 +336,8 @@ impl PlayerEffects {
|
||||
pub fn modifiers(&self) -> Vec<(&'static str, &'static str, f64, &'static str)> {
|
||||
let mut out = Vec::new();
|
||||
for e in &self.list {
|
||||
let level = f64::from(e.amplifier + 1);
|
||||
let m = match e.id {
|
||||
"speed" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.speed",
|
||||
0.2,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"slowness" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.slowness",
|
||||
-0.15,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"haste" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.haste",
|
||||
0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"mining_fatigue" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.mining_fatigue",
|
||||
-0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"strength" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.strength",
|
||||
3.0,
|
||||
"add_value",
|
||||
)),
|
||||
"weakness" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.weakness",
|
||||
-4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"jump_boost" => Some((
|
||||
"minecraft:safe_fall_distance",
|
||||
"minecraft:effect.jump_boost",
|
||||
1.0,
|
||||
"add_value",
|
||||
)),
|
||||
"health_boost" => Some((
|
||||
"minecraft:max_health",
|
||||
"minecraft:effect.health_boost",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"absorption" => Some((
|
||||
"minecraft:max_absorption",
|
||||
"minecraft:effect.absorption",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")),
|
||||
"unluck" => Some((
|
||||
"minecraft:luck",
|
||||
"minecraft:effect.unluck",
|
||||
-1.0,
|
||||
"add_value",
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((a, id, amount, op)) = m {
|
||||
out.push((a, id, amount * level, op));
|
||||
if let Some((a, id, amount, op)) = effect_modifier(e.id) {
|
||||
out.push((a, id, amount * f64::from(e.amplifier + 1), op));
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -445,6 +380,76 @@ impl StatusFlags {
|
||||
}
|
||||
}
|
||||
|
||||
/// The attribute modifier an effect adds at amplifier 0
|
||||
/// (`MobEffect.addAttributeModifier`): (attribute, id, amount, operation).
|
||||
/// Each level multiplies the amount (`amplifier + 1`).
|
||||
pub fn effect_modifier(effect: &str) -> Option<(&'static str, &'static str, f64, &'static str)> {
|
||||
match effect {
|
||||
"speed" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.speed",
|
||||
0.2,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"slowness" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.slowness",
|
||||
-0.15,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"haste" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.haste",
|
||||
0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"mining_fatigue" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.mining_fatigue",
|
||||
-0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"strength" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.strength",
|
||||
3.0,
|
||||
"add_value",
|
||||
)),
|
||||
"weakness" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.weakness",
|
||||
-4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"jump_boost" => Some((
|
||||
"minecraft:safe_fall_distance",
|
||||
"minecraft:effect.jump_boost",
|
||||
1.0,
|
||||
"add_value",
|
||||
)),
|
||||
"health_boost" => Some((
|
||||
"minecraft:max_health",
|
||||
"minecraft:effect.health_boost",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"absorption" => Some((
|
||||
"minecraft:max_absorption",
|
||||
"minecraft:effect.absorption",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")),
|
||||
"unluck" => Some((
|
||||
"minecraft:luck",
|
||||
"minecraft:effect.unluck",
|
||||
-1.0,
|
||||
"add_value",
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -840,9 +840,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.species(),
|
||||
crate::mobs::Species::Slime | crate::mobs::Species::MagmaCube
|
||||
) {
|
||||
let health = m.health;
|
||||
// AbstractCubeMob.readAdditionalSaveData: the size's attributes, then
|
||||
// the saved health, the max health when there is none.
|
||||
crate::mobs::cube::set_size(&mut m, number(tag.get("Size")).unwrap_or(0) as i32 + 1);
|
||||
m.health = health;
|
||||
if let Some(h) = float(tag.get("Health")) {
|
||||
m.health = h as f32;
|
||||
}
|
||||
m.extra.flag2 = flag(tag, "wasOnGround");
|
||||
}
|
||||
// Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby
|
||||
|
||||
@@ -65,6 +65,7 @@ mod item_particles;
|
||||
mod jukebox;
|
||||
mod lan;
|
||||
mod lan_actions;
|
||||
mod lan_attributes;
|
||||
mod lan_chat;
|
||||
mod lan_crafting;
|
||||
mod lan_entities;
|
||||
|
||||
@@ -726,6 +726,7 @@ impl Game<'_> {
|
||||
sprinting: p.sprinting,
|
||||
equipment,
|
||||
health: p.health.health(),
|
||||
attributes: horizon_client::lan::attributes::syncable(&p.attributes),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -736,6 +737,7 @@ impl Game<'_> {
|
||||
let kind = m.kind.id.as_str();
|
||||
let meta = mob_meta(m, hub);
|
||||
let equipment = mob_equipment(m, hub);
|
||||
let attributes = self.mob_attributes(m);
|
||||
let (yaw, pitch) = (m.yaw, m.head_pitch);
|
||||
out.push(EntityState {
|
||||
id: m.id as i32,
|
||||
@@ -750,6 +752,7 @@ impl Game<'_> {
|
||||
data: 0,
|
||||
meta,
|
||||
equipment,
|
||||
attributes,
|
||||
precise: false,
|
||||
});
|
||||
}
|
||||
@@ -768,6 +771,7 @@ impl Game<'_> {
|
||||
data: 0,
|
||||
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
});
|
||||
}
|
||||
@@ -786,6 +790,7 @@ impl Game<'_> {
|
||||
// ExperienceOrb.DATA_VALUE.
|
||||
meta: vec![(8, serializer::INT, Value::Int(o.value as i32))],
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1330,6 +1330,7 @@ impl Game<'_> {
|
||||
self.as_guest(host, conn, |g| {
|
||||
g.count_tick_stats(sleeping);
|
||||
g.tick_advancements();
|
||||
g.update_player_attributes();
|
||||
});
|
||||
host.hub.flush_progress(conn);
|
||||
self.guest_dig_feedback(host, conn);
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
//! The attribute instances a server syncs for the living entities it tracks
|
||||
//! (`ClientboundUpdateAttributesPacket`, lan/attributes.rs): the ones
|
||||
//! vanilla's `AttributeMap` would have created by then, since only those are
|
||||
//! sent, never the type's other defaults.
|
||||
use super::Game;
|
||||
use super::commands::Target;
|
||||
use horizon_client::{
|
||||
effects,
|
||||
lan::attributes::{add_modifier, generic_syncable, instance, operation_named},
|
||||
mobs::{
|
||||
Mob,
|
||||
finalize::{self, Attr, Op},
|
||||
},
|
||||
};
|
||||
use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// `EquipmentSlotGroup.test`: whether a modifier's slot group covers a slot.
|
||||
fn slot_in_group(group: &str, slot: &str) -> bool {
|
||||
group == slot
|
||||
|| group == "any"
|
||||
|| (group == "hand" && matches!(slot, "mainhand" | "offhand"))
|
||||
|| (group == "armor" && matches!(slot, "feet" | "legs" | "chest" | "head" | "body"))
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The registry id of a client-syncable attribute the entity type has
|
||||
/// (`AttributeMap.getInstance` is null for the others), by name.
|
||||
fn synced_attribute(&self, entity: &str, name: &str) -> Option<i32> {
|
||||
let catalog = &self.motion.attributes;
|
||||
let id = catalog.id(name)?;
|
||||
(catalog.attribute(id).syncable && catalog.default_base(entity, id).is_some())
|
||||
.then(|| id.registry_id())
|
||||
}
|
||||
|
||||
/// The type's base value of an attribute, as the instance starts.
|
||||
fn attribute_default(&self, entity: &str, name: &str) -> f64 {
|
||||
let catalog = &self.motion.attributes;
|
||||
catalog
|
||||
.id(name)
|
||||
.and_then(|id| catalog.default_base(entity, id))
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// `LivingEntity.collectEquipmentChanges`: each worn or held item's
|
||||
/// attribute modifiers, slot by slot in `EquipmentSlot` order, create
|
||||
/// their instances (an instance without a modifier keeps its base).
|
||||
fn equipment_attributes<'a>(
|
||||
&self,
|
||||
entity: &str,
|
||||
base: impl Fn(&str) -> Option<f64>,
|
||||
slots: impl IntoIterator<Item = (&'static str, Option<&'a Arc<str>>)>,
|
||||
out: &mut Vec<AttributeSnapshot>,
|
||||
) {
|
||||
for (slot, item) in slots {
|
||||
let Some(info) = item.and_then(|i| self.res.items.get(i)) else {
|
||||
continue;
|
||||
};
|
||||
for (attribute, id, amount, op, group) in &info.modifiers {
|
||||
if !slot_in_group(group, slot) {
|
||||
continue;
|
||||
}
|
||||
let Some(a) = self.synced_attribute(entity, attribute) else {
|
||||
continue;
|
||||
};
|
||||
let start =
|
||||
base(attribute).unwrap_or_else(|| self.attribute_default(entity, attribute));
|
||||
add_modifier(
|
||||
out,
|
||||
a,
|
||||
start,
|
||||
AttributeModifier {
|
||||
id: id.clone(),
|
||||
amount: *amount,
|
||||
operation: operation_named(op),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mob's synced instances: movement speed (its first `aiStep` reads it,
|
||||
/// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed
|
||||
/// modifier, its effects' modifiers, its equipment's, and what
|
||||
/// `/attribute` changed.
|
||||
pub(super) fn mob_attributes(&self, m: &Mob) -> Vec<AttributeSnapshot> {
|
||||
let kind = m.kind.id.as_str();
|
||||
let mut out = Vec::new();
|
||||
if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") {
|
||||
instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed));
|
||||
}
|
||||
if let Some(s) = m.extra.attributes.as_deref() {
|
||||
for (attr, v) in &s.bases {
|
||||
if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name()))
|
||||
{
|
||||
instance(&mut out, a, *v).base = *v;
|
||||
}
|
||||
}
|
||||
for x in &s.modifiers {
|
||||
if let Some(a) =
|
||||
self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name()))
|
||||
{
|
||||
add_modifier(
|
||||
&mut out,
|
||||
a,
|
||||
finalize::base_value(m, x.attr),
|
||||
AttributeModifier {
|
||||
id: x.id.to_owned(),
|
||||
amount: x.amount,
|
||||
operation: match x.op {
|
||||
Op::AddValue => 0,
|
||||
Op::AddMultipliedBase => 1,
|
||||
Op::AddMultipliedTotal => 2,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(a), Some((amount, Op::AddMultipliedBase))) = (
|
||||
self.synced_attribute(kind, "minecraft:movement_speed"),
|
||||
finalize::transient(m, Attr::MovementSpeed),
|
||||
) {
|
||||
add_modifier(
|
||||
&mut out,
|
||||
a,
|
||||
finalize::base_value(m, Attr::MovementSpeed),
|
||||
AttributeModifier {
|
||||
id: "minecraft:baby".into(),
|
||||
amount,
|
||||
operation: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
let base = |name: &str| {
|
||||
Attr::ALL
|
||||
.into_iter()
|
||||
.find(|a| name.strip_prefix("minecraft:") == Some(a.name()))
|
||||
.map(|a| finalize::base_value(m, a))
|
||||
};
|
||||
// LivingEntity.onEffectAdded: MobEffect.addAttributeModifiers.
|
||||
for &(effect, _, amplifier) in &m.extra.effects {
|
||||
let Some((attribute, id, amount, op)) =
|
||||
effects::effect_modifier(effect.trim_start_matches("minecraft:"))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(a) = self.synced_attribute(kind, attribute) else {
|
||||
continue;
|
||||
};
|
||||
let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute));
|
||||
add_modifier(
|
||||
&mut out,
|
||||
a,
|
||||
start,
|
||||
AttributeModifier {
|
||||
id: id.to_owned(),
|
||||
amount: amount * f64::from(amplifier + 1),
|
||||
operation: operation_named(op),
|
||||
},
|
||||
);
|
||||
}
|
||||
let e = &m.extra;
|
||||
self.equipment_attributes(
|
||||
kind,
|
||||
base,
|
||||
[
|
||||
("mainhand", e.main_hand.as_ref()),
|
||||
("offhand", e.off_hand.as_ref()),
|
||||
("feet", e.feet.as_ref()),
|
||||
("legs", e.legs.as_ref()),
|
||||
("chest", e.chest.as_ref()),
|
||||
("head", e.head.as_ref()),
|
||||
],
|
||||
&mut out,
|
||||
);
|
||||
self.generic_attributes_of(Target::Mob(m.id), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// An armor stand's synced instances: movement speed (its first
|
||||
/// `aiStep`), its equipment's modifiers and what `/attribute` changed.
|
||||
pub(super) fn stand_attributes(
|
||||
&self,
|
||||
id: u32,
|
||||
equipment: &[Option<horizon_client::items::ItemStack>; 6],
|
||||
) -> Vec<AttributeSnapshot> {
|
||||
const KIND: &str = "minecraft:armor_stand";
|
||||
let mut out = Vec::new();
|
||||
if let Some(a) = self.synced_attribute(KIND, "minecraft:movement_speed") {
|
||||
instance(
|
||||
&mut out,
|
||||
a,
|
||||
self.attribute_default(KIND, "minecraft:movement_speed"),
|
||||
);
|
||||
}
|
||||
let slots = horizon_client::entities::ArmorStand::SLOTS
|
||||
.into_iter()
|
||||
.zip(equipment.iter().map(|s| s.as_ref().map(|s| &s.item)));
|
||||
self.equipment_attributes(KIND, |_| None, slots, &mut out);
|
||||
self.generic_attributes_of(Target::Stand(id), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The instances a server player's tick creates, and
|
||||
/// `ServerPlayer.updatePlayerAttributes`: a creative player reaches 0.5
|
||||
/// further to blocks and 2 to entities. Its client reads the reach from
|
||||
/// these synced modifiers. (The crouching player's waypoint range is
|
||||
/// server-side only: lan_waypoints.rs hides it.)
|
||||
pub(super) fn update_player_attributes(&mut self) {
|
||||
let creative = self.mode_id() == 1;
|
||||
let Some(p) = self.player.as_mut() else {
|
||||
return;
|
||||
};
|
||||
// LivingEntity.aiStep's removeFrost reads the movement speed instance
|
||||
// every tick, which creates it (and its first sync).
|
||||
if let Some(key) = p.attributes.key("minecraft:movement_speed") {
|
||||
let _ = p.attributes.get_instance(Some(key));
|
||||
}
|
||||
for (attribute, id, amount) in [
|
||||
(
|
||||
"minecraft:block_interaction_range",
|
||||
"minecraft:creative_mode_block_range",
|
||||
0.5,
|
||||
),
|
||||
(
|
||||
"minecraft:entity_interaction_range",
|
||||
"minecraft:creative_mode_entity_range",
|
||||
2.0,
|
||||
),
|
||||
] {
|
||||
let Some(key) = p.attributes.key(attribute) else {
|
||||
continue;
|
||||
};
|
||||
// getAttribute creates the instance, a creative player's or not.
|
||||
if !matches!(p.attributes.get_instance(Some(key.clone())), Ok(Some(_))) {
|
||||
continue;
|
||||
}
|
||||
// addOrUpdateTransientModifier with the same modifier and
|
||||
// removeModifier of a missing one leave the instance clean.
|
||||
let has = p.attributes.has_modifier(Some(key), id).unwrap_or(false);
|
||||
if has != creative {
|
||||
let _ = p.set_modifier(attribute, id, amount, "add_value", creative);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The instances `/attribute` created in an entity's generic map
|
||||
/// replace the ones derived from its state.
|
||||
fn generic_attributes_of(&self, t: Target, out: &mut Vec<AttributeSnapshot>) {
|
||||
let Some(map) = self.cmds.attributes.get(&t) else {
|
||||
return;
|
||||
};
|
||||
for s in generic_syncable(map) {
|
||||
let (attribute, base) = (s.attribute, s.base);
|
||||
*instance(out, attribute, base) = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::slot_in_group;
|
||||
|
||||
#[test]
|
||||
fn slot_groups_cover_their_slots() {
|
||||
assert!(slot_in_group("head", "head"));
|
||||
assert!(slot_in_group("armor", "chest"));
|
||||
assert!(!slot_in_group("armor", "mainhand"));
|
||||
assert!(slot_in_group("hand", "offhand"));
|
||||
assert!(slot_in_group("any", "feet"));
|
||||
assert!(!slot_in_group("mainhand", "offhand"));
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) ->
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
}
|
||||
}
|
||||
@@ -179,6 +180,7 @@ impl Game<'_> {
|
||||
e.equipment.push((slot as u8, hub.stack(item)));
|
||||
}
|
||||
}
|
||||
e.attributes = self.stand_attributes(a.id, &a.equipment);
|
||||
out.push(e);
|
||||
}
|
||||
for f in &self.item_frames {
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! `ClientboundUpdateAttributesPacket`: the attribute instances a server syncs
|
||||
//! to its clients. `ServerEntity.sendPairingData` sends every client-syncable
|
||||
//! instance an entity has (`AttributeMap.getSyncableAttributes`: the instances
|
||||
//! created so far, not the type's defaults), `sendDirtyEntityData` the ones
|
||||
//! changed since (`getAttributesToSync`), to the trackers and the player itself.
|
||||
use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot};
|
||||
use horizon_world::attributes::{
|
||||
Instance, Operation,
|
||||
entity::{AttributeId, EntityAttributes},
|
||||
live::LiveAttributes,
|
||||
};
|
||||
|
||||
/// `AttributeModifier.Operation.id`.
|
||||
pub fn operation_id(op: Operation) -> i32 {
|
||||
match op {
|
||||
Operation::AddValue => 0,
|
||||
Operation::AddMultipliedBase => 1,
|
||||
Operation::AddMultipliedTotal => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// An `Operation`'s serialized name (`add_value` ...) as its id.
|
||||
pub fn operation_named(name: &str) -> i32 {
|
||||
match name {
|
||||
"add_multiplied_base" => 1,
|
||||
"add_multiplied_total" => 2,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `AttributeSnapshot`: the base and every modifier, in the order they were added.
|
||||
pub fn snapshot(attribute: AttributeId, instance: &Instance) -> AttributeSnapshot {
|
||||
AttributeSnapshot {
|
||||
attribute: attribute.registry_id(),
|
||||
base: instance.base_value(),
|
||||
modifiers: instance
|
||||
.modifiers()
|
||||
.iter()
|
||||
.map(|m| AttributeModifier {
|
||||
id: m.id().to_owned(),
|
||||
amount: m.amount(),
|
||||
operation: operation_id(m.operation()),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `AttributeMap.getSyncableAttributes` of a live map (a player's).
|
||||
pub fn syncable<G: FnMut() -> i32>(map: &LiveAttributes<G>) -> Vec<AttributeSnapshot> {
|
||||
let catalog = map.catalog();
|
||||
map.instances()
|
||||
.filter(|(_, key, _)| catalog.attribute(key.attribute()).syncable)
|
||||
.map(|(_, key, instance)| snapshot(key.attribute(), instance))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `getAttributesToSync`, cleared once read (`ServerEntity.sendDirtyEntityData`).
|
||||
pub fn take_dirty<G: FnMut() -> i32>(map: &mut LiveAttributes<G>) -> Vec<AttributeSnapshot> {
|
||||
if map.sync().is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let handles: Vec<_> = map.sync().values().flatten().cloned().collect();
|
||||
map.sync_mut().clear();
|
||||
handles
|
||||
.iter()
|
||||
.filter_map(|h| {
|
||||
let key = map.attribute(h).ok()?;
|
||||
Some(snapshot(key.attribute(), map.instance(h).ok()?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The client-syncable instances of a generic attribute map.
|
||||
pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator<Item = AttributeSnapshot> + '_ {
|
||||
let catalog = map.catalog();
|
||||
catalog
|
||||
.attributes()
|
||||
.filter(|(_, a)| a.syncable)
|
||||
.filter_map(move |(id, _)| map.instance(id).map(|i| snapshot(id, i)))
|
||||
}
|
||||
|
||||
/// Adds a modifier to the snapshot of `attribute`, creating it with `base`.
|
||||
pub fn add_modifier(
|
||||
out: &mut Vec<AttributeSnapshot>,
|
||||
attribute: i32,
|
||||
base: f64,
|
||||
modifier: AttributeModifier,
|
||||
) {
|
||||
let snapshot = instance(out, attribute, base);
|
||||
match snapshot.modifiers.iter_mut().find(|m| m.id == modifier.id) {
|
||||
Some(m) => *m = modifier,
|
||||
None => snapshot.modifiers.push(modifier),
|
||||
}
|
||||
}
|
||||
|
||||
/// The snapshot of `attribute`, created with `base` if it isn't there yet.
|
||||
pub fn instance(
|
||||
out: &mut Vec<AttributeSnapshot>,
|
||||
attribute: i32,
|
||||
base: f64,
|
||||
) -> &mut AttributeSnapshot {
|
||||
let i = match out.iter().position(|a| a.attribute == attribute) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
out.push(AttributeSnapshot {
|
||||
attribute,
|
||||
base,
|
||||
modifiers: Vec::new(),
|
||||
});
|
||||
out.len() - 1
|
||||
}
|
||||
};
|
||||
&mut out[i]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn modifiers_replace_by_id_and_instances_are_created_once() {
|
||||
let mut out = Vec::new();
|
||||
let m = |id: &str, amount| AttributeModifier {
|
||||
id: id.into(),
|
||||
amount,
|
||||
operation: 0,
|
||||
};
|
||||
add_modifier(&mut out, 1, 0.0, m("minecraft:armor.helmet", 3.0));
|
||||
add_modifier(&mut out, 1, 5.0, m("minecraft:armor.chestplate", 8.0));
|
||||
add_modifier(&mut out, 1, 5.0, m("minecraft:armor.helmet", 2.0));
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].base, 0.0);
|
||||
assert_eq!(
|
||||
out[0].modifiers,
|
||||
[
|
||||
m("minecraft:armor.helmet", 2.0),
|
||||
m("minecraft:armor.chestplate", 8.0)
|
||||
]
|
||||
);
|
||||
instance(&mut out, 26, 0.7);
|
||||
assert_eq!(out.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,28 @@ use horizon_protocol::{
|
||||
entity_data::Value,
|
||||
item::Stack,
|
||||
packets::play::{
|
||||
self, AddEntity, EntityPositionSync, MoveEntity, MoveEntityPos, MoveEntityPosRot,
|
||||
MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, SetEquipment,
|
||||
SetPassengers, VecDelta,
|
||||
self, AddEntity, AttributeSnapshot, EntityPositionSync, MoveEntity, MoveEntityPos,
|
||||
MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion,
|
||||
SetEquipment, SetPassengers, UpdateAttributes, VecDelta,
|
||||
},
|
||||
};
|
||||
|
||||
/// The attribute instances of `now` that differ from what `sent` held (an
|
||||
/// instance is never removed: one that disappears is left as it was sent).
|
||||
pub fn changed_attributes(
|
||||
now: &[AttributeSnapshot],
|
||||
sent: &[AttributeSnapshot],
|
||||
) -> Vec<AttributeSnapshot> {
|
||||
now.iter()
|
||||
.filter(|a| {
|
||||
sent.iter()
|
||||
.find(|b| b.attribute == a.attribute)
|
||||
.is_none_or(|b| b != *a)
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the game says about one entity this tick.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EntityState {
|
||||
@@ -37,6 +53,9 @@ pub struct EntityState {
|
||||
/// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs,
|
||||
/// 4 chest, 5 head, 6 body, 7 saddle) and their stacks.
|
||||
pub equipment: Vec<(u8, Option<Stack>)>,
|
||||
/// A living entity's client-syncable attribute instances
|
||||
/// (`AttributeMap.getSyncableAttributes`), by registry id.
|
||||
pub attributes: Vec<AttributeSnapshot>,
|
||||
/// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks
|
||||
/// touching a block): moves are sent as full position syncs.
|
||||
pub precise: bool,
|
||||
@@ -117,6 +136,8 @@ struct ServerEntity {
|
||||
/// trackedDataValues: the entity data the clients hold.
|
||||
meta: Vec<(u8, i32, Value)>,
|
||||
equipment: Vec<(u8, Option<Stack>)>,
|
||||
/// The attribute instances the clients hold.
|
||||
attributes: Vec<AttributeSnapshot>,
|
||||
was_on_ground: bool,
|
||||
tick: u32,
|
||||
teleport_delay: u32,
|
||||
@@ -153,6 +174,7 @@ impl ServerEntity {
|
||||
velocity: e.velocity,
|
||||
meta: e.meta.clone(),
|
||||
equipment: e.equipment.clone(),
|
||||
attributes: e.attributes.clone(),
|
||||
was_on_ground: e.on_ground,
|
||||
tick: 0,
|
||||
teleport_delay: 0,
|
||||
@@ -190,6 +212,13 @@ impl ServerEntity {
|
||||
values: self.meta.clone(),
|
||||
}));
|
||||
}
|
||||
// getSyncableAttributes: the instances as they are now.
|
||||
if !e.attributes.is_empty() {
|
||||
out.push(play::Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: e.id,
|
||||
values: e.attributes.clone(),
|
||||
}));
|
||||
}
|
||||
if !self.equipment.is_empty() {
|
||||
out.push(play::Clientbound::SetEquipment(SetEquipment {
|
||||
id: e.id,
|
||||
@@ -342,24 +371,35 @@ impl ServerEntity {
|
||||
self.send_equipment(e, out);
|
||||
}
|
||||
|
||||
/// ServerEntity.sendDirtyEntityData.
|
||||
/// ServerEntity.sendDirtyEntityData: the changed entity data, then the
|
||||
/// attribute instances that changed since they were last sent
|
||||
/// (`AttributeMap.getAttributesToSync`).
|
||||
fn send_dirty(&mut self, e: &EntityState, dirty: bool, out: &mut Vec<play::Clientbound>) {
|
||||
if !dirty {
|
||||
return;
|
||||
if dirty {
|
||||
let changed: Vec<_> = e
|
||||
.meta
|
||||
.iter()
|
||||
.filter(|m| !self.meta.contains(m))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !changed.is_empty() {
|
||||
out.push(play::Clientbound::SetEntityData(SetEntityData {
|
||||
id: e.id,
|
||||
values: changed,
|
||||
}));
|
||||
}
|
||||
self.meta.clone_from(&e.meta);
|
||||
}
|
||||
let changed: Vec<_> = e
|
||||
.meta
|
||||
.iter()
|
||||
.filter(|m| !self.meta.contains(m))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !changed.is_empty() {
|
||||
out.push(play::Clientbound::SetEntityData(SetEntityData {
|
||||
id: e.id,
|
||||
values: changed,
|
||||
}));
|
||||
if e.attributes != self.attributes {
|
||||
let changed = changed_attributes(&e.attributes, &self.attributes);
|
||||
if !changed.is_empty() {
|
||||
out.push(play::Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: e.id,
|
||||
values: changed,
|
||||
}));
|
||||
}
|
||||
self.attributes.clone_from(&e.attributes);
|
||||
}
|
||||
self.meta.clone_from(&e.meta);
|
||||
}
|
||||
|
||||
fn send_head(&mut self, e: &EntityState, out: &mut Vec<play::Clientbound>) {
|
||||
@@ -645,6 +685,7 @@ mod tests {
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
}
|
||||
}
|
||||
@@ -741,6 +782,42 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_pair_whole_then_send_the_changed_instances_when_due() {
|
||||
let speed = |base| AttributeSnapshot {
|
||||
attribute: 26,
|
||||
base,
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
let armor = AttributeSnapshot {
|
||||
attribute: 1,
|
||||
base: 0.0,
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
let mut e = state(0.0);
|
||||
e.attributes = vec![speed(0.23), armor];
|
||||
let mut s = added(&e);
|
||||
let mut spawn = Vec::new();
|
||||
s.pairing(&e, 100, &Riding::default(), &mut spawn);
|
||||
let Some(play::Clientbound::UpdateAttributes(p)) = spawn.get(1) else {
|
||||
panic!("expected the attributes after the add");
|
||||
};
|
||||
assert_eq!(p.values, e.attributes);
|
||||
changes(&mut s, &e);
|
||||
e.attributes[0] = speed(0.3);
|
||||
// Not due (a zombie's interval is 3): sendDirtyEntityData waits for the update.
|
||||
assert!(changes(&mut s, &e).is_empty());
|
||||
assert!(changes(&mut s, &e).is_empty());
|
||||
let out = changes(&mut s, &e);
|
||||
let Some(play::Clientbound::UpdateAttributes(p)) = out
|
||||
.iter()
|
||||
.find(|p| matches!(p, play::Clientbound::UpdateAttributes(_)))
|
||||
else {
|
||||
panic!("expected the changed attribute");
|
||||
};
|
||||
assert_eq!(p.values, vec![speed(0.3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_and_equipment_send_only_the_changes() {
|
||||
let mut e = state(0.0);
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct HostState {
|
||||
pub sprinting: bool,
|
||||
pub equipment: [Option<ItemStack>; 6],
|
||||
pub health: f32,
|
||||
/// The host player's client-syncable attribute instances.
|
||||
pub attributes: Vec<play::AttributeSnapshot>,
|
||||
}
|
||||
|
||||
/// Everything the hub needs from the game for one tick.
|
||||
@@ -1392,6 +1394,7 @@ impl Hub {
|
||||
skin: u8,
|
||||
health: f32,
|
||||
equipment: Vec<(u8, Option<horizon_protocol::item::Stack>)>,
|
||||
attributes: Vec<play::AttributeSnapshot>,
|
||||
) -> EntityState {
|
||||
let (sneaking, sprinting, gliding, sleeping) = flags;
|
||||
let mut shared = 0i8;
|
||||
@@ -1439,6 +1442,7 @@ impl Hub {
|
||||
data: 0,
|
||||
meta,
|
||||
equipment,
|
||||
attributes,
|
||||
precise: false,
|
||||
}
|
||||
}
|
||||
@@ -1486,6 +1490,7 @@ impl Hub {
|
||||
0x7F,
|
||||
h.health,
|
||||
equipment,
|
||||
h.attributes.clone(),
|
||||
));
|
||||
}
|
||||
let placed: Vec<usize> = (0..self.guests.len())
|
||||
@@ -1515,6 +1520,10 @@ impl Hub {
|
||||
g.info.model_customisation,
|
||||
g.health,
|
||||
equipment,
|
||||
g.motion
|
||||
.as_ref()
|
||||
.map(|m| super::attributes::syncable(&m.attributes))
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -1625,6 +1634,19 @@ impl Hub {
|
||||
self.flush_advancements(i, true);
|
||||
}
|
||||
}
|
||||
// ServerEntity.sendDirtyEntityData: the player's changed attribute
|
||||
// instances go to the player too (its trackers get them from
|
||||
// track_entities).
|
||||
let g = &mut self.guests[i];
|
||||
if let Some(m) = g.motion.as_mut() {
|
||||
let values = super::attributes::take_dirty(&mut m.attributes);
|
||||
if !values.is_empty() {
|
||||
g.send(&C::UpdateAttributes(play::UpdateAttributes {
|
||||
id: g.entity_id,
|
||||
values,
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Sent when the health or the food level changes, or the saturation
|
||||
// reaches or leaves zero; a dead player's health of 0 too.
|
||||
let g = &mut self.guests[i];
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! ever exchanges decoded packets with these threads through channels, so a
|
||||
//! world that is not open to the network pays nothing.
|
||||
mod advancements;
|
||||
pub mod attributes;
|
||||
pub mod chunks;
|
||||
mod command_order;
|
||||
pub mod command_suggestions;
|
||||
|
||||
@@ -47,14 +47,24 @@ pub fn register(m: &mut Mob) {
|
||||
m.extra.vector[0] = f64::from(180.0 * m.yaw / std::f32::consts::PI);
|
||||
set_size(m, 1);
|
||||
}
|
||||
/// AbstractCubeMob.setSize: health size^2, speed 0.2 + 0.1 * size, damage size.
|
||||
/// AbstractCubeMob.setSize(size, true): the max health (size^2), movement
|
||||
/// speed (0.2 + 0.1 * size, in floats) and attack damage (size) bases, a
|
||||
/// magma cube's armor (size * 3), then the health back to the max.
|
||||
pub fn set_size(m: &mut Mob, size: i32) {
|
||||
use super::finalize::{Attr, set_base};
|
||||
let size = size.clamp(1, 127);
|
||||
m.extra.size = size;
|
||||
m.attrs.max_health = (size * size) as f32;
|
||||
m.attrs.speed = 0.2 + 0.1 * f64::from(size);
|
||||
m.attrs.attack_damage = size as f32;
|
||||
m.health = m.attrs.max_health;
|
||||
set_base(m, Attr::MaxHealth, f64::from(size * size));
|
||||
set_base(
|
||||
m,
|
||||
Attr::MovementSpeed,
|
||||
f64::from(0.2f32 + 0.1f32 * size as f32),
|
||||
);
|
||||
set_base(m, Attr::AttackDamage, f64::from(size));
|
||||
if m.species() == super::Species::MagmaCube {
|
||||
set_base(m, Attr::Armor, f64::from(size * 3));
|
||||
}
|
||||
m.health = super::finalize::max_health(m);
|
||||
}
|
||||
/// AbstractCubeMob.setSpawnSize: 1, 2 or 4 (normal difficulty special multiplier 0).
|
||||
pub fn finalize(m: &mut Mob) {
|
||||
|
||||
@@ -483,7 +483,7 @@ pub fn base_value(m: &Mob, a: Attr) -> f64 {
|
||||
.unwrap_or(if a == Attr::BurningTime { 1.0 } else { 0.0 })
|
||||
}
|
||||
/// The transient modifiers of the mob's state (`SPEED_MODIFIER_BABY`).
|
||||
fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> {
|
||||
pub fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> {
|
||||
if a != Attr::MovementSpeed || !m.is_baby() {
|
||||
return None;
|
||||
}
|
||||
@@ -1961,19 +1961,7 @@ fn sulfur_size(m: &mut Mob, size: i32) {
|
||||
m.health = max_health(m);
|
||||
}
|
||||
fn cube_size(m: &mut Mob, size: i32) {
|
||||
let size = size.clamp(1, 127);
|
||||
m.extra.size = size;
|
||||
set_base(m, Attr::MaxHealth, f64::from(size * size));
|
||||
set_base(
|
||||
m,
|
||||
Attr::MovementSpeed,
|
||||
f64::from(0.2f32 + 0.1f32 * size as f32),
|
||||
);
|
||||
set_base(m, Attr::AttackDamage, f64::from(size));
|
||||
if m.species() == Species::MagmaCube {
|
||||
set_base(m, Attr::Armor, f64::from(size * 3));
|
||||
}
|
||||
m.health = max_health(m);
|
||||
super::cube::set_size(m, size);
|
||||
}
|
||||
/// The index the game keeps for a variant registry entry.
|
||||
pub fn variant_index(s: Species, name: &str) -> u8 {
|
||||
|
||||
@@ -181,6 +181,7 @@ impl Server {
|
||||
sprinting: false,
|
||||
equipment: Default::default(),
|
||||
health: 20.0,
|
||||
attributes: Vec::new(),
|
||||
};
|
||||
let mut ctx = TickCtx {
|
||||
world: &mut self.world,
|
||||
@@ -422,6 +423,7 @@ fn guests_see_each_other_and_the_world_entities() {
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
};
|
||||
let first = thread::spawn(move || {
|
||||
|
||||
@@ -881,6 +881,24 @@ packet!(
|
||||
UpdateMobEffect { id: i32 => VarInt, effect: i32 => VarInt, amplifier: i32 => VarInt, duration: i32 => VarInt, flags: i8 => Byte }
|
||||
);
|
||||
packet!(RemoveMobEffect { id: i32 => VarInt, effect: i32 => VarInt });
|
||||
packet!(
|
||||
/// AttributeModifier.STREAM_CODEC: id, amount and operation (0 add_value,
|
||||
/// 1 add_multiplied_base, 2 add_multiplied_total).
|
||||
AttributeModifier { id: String => Ident, amount: f64 => Double, operation: i32 => VarInt }
|
||||
);
|
||||
packet!(
|
||||
/// ClientboundUpdateAttributesPacket.AttributeSnapshot: the attribute's
|
||||
/// registry id, its base value and every modifier.
|
||||
AttributeSnapshot {
|
||||
attribute: i32 => VarInt,
|
||||
base: f64 => Double,
|
||||
modifiers: Vec<AttributeModifier> => List<AttributeModifier>,
|
||||
}
|
||||
);
|
||||
packet!(
|
||||
/// ClientboundUpdateAttributesPacket: an entity's synced attribute instances.
|
||||
UpdateAttributes { id: i32 => VarInt, values: Vec<AttributeSnapshot> => List<AttributeSnapshot> }
|
||||
);
|
||||
packet!(
|
||||
/// ClientboundSwingAnimationPacket: hand (0 main, 1 off) and the swing
|
||||
/// type (0 none, 1 whack, 2 stab) with its duration in ticks.
|
||||
@@ -1455,6 +1473,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
TickingState(TickingState) = TICKING_STATE,
|
||||
TickingStep(TickingStep) = TICKING_STEP,
|
||||
UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS,
|
||||
UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES,
|
||||
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
|
||||
UpdateTags(UpdateTags) = UPDATE_TAGS,
|
||||
TrackedWaypoint(TrackedWaypoint) = WAYPOINT,
|
||||
@@ -2110,6 +2129,18 @@ mod tests {
|
||||
id: 2,
|
||||
slots: vec![(0, None), (5, Some(Stack::new(1, 1)))],
|
||||
}),
|
||||
Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: 2,
|
||||
values: vec![AttributeSnapshot {
|
||||
attribute: 26,
|
||||
base: 0.23,
|
||||
modifiers: vec![AttributeModifier {
|
||||
id: "minecraft:baby".into(),
|
||||
amount: 0.5,
|
||||
operation: 1,
|
||||
}],
|
||||
}],
|
||||
}),
|
||||
Clientbound::SetHealth(SetHealth {
|
||||
health: 17.5,
|
||||
food: 18,
|
||||
@@ -2347,4 +2378,31 @@ mod tests {
|
||||
);
|
||||
assert_eq!(p.encode()[1..], [1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_attributes_encode_like_vanilla() {
|
||||
let p = Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: 5,
|
||||
values: vec![AttributeSnapshot {
|
||||
attribute: 1,
|
||||
base: 0.0,
|
||||
modifiers: vec![AttributeModifier {
|
||||
id: "minecraft:armor.helmet".into(),
|
||||
amount: 3.0,
|
||||
operation: 0,
|
||||
}],
|
||||
}],
|
||||
});
|
||||
let body = p.encode();
|
||||
// The packet id (134) is a two-byte VarInt.
|
||||
let mut expected = vec![134, 1, 5, 1, 1];
|
||||
expected.extend(0.0f64.to_be_bytes());
|
||||
expected.extend([1, 22]);
|
||||
expected.extend(b"minecraft:armor.helmet");
|
||||
expected.extend(3.0f64.to_be_bytes());
|
||||
expected.push(0);
|
||||
assert_eq!(body, expected);
|
||||
assert_eq!(crate::ids::play::clientbound::UPDATE_ATTRIBUTES, 134);
|
||||
assert_eq!(Clientbound::decode(134, &body[2..]).unwrap(), p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,11 @@ impl AttributeId {
|
||||
pub(super) fn index(self) -> usize {
|
||||
self.0
|
||||
}
|
||||
/// The attribute's id in the `minecraft:attribute` registry: the catalog
|
||||
/// export lists `BuiltInRegistries.ATTRIBUTE` in order.
|
||||
pub fn registry_id(self) -> i32 {
|
||||
self.0 as i32
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct RegisteredAttribute {
|
||||
@@ -100,6 +105,10 @@ impl Catalog {
|
||||
defaults,
|
||||
})
|
||||
}
|
||||
/// The entity type's supplier base of an attribute, if the type has it.
|
||||
pub fn default_base(&self, entity: &str, id: AttributeId) -> Option<f64> {
|
||||
self.defaults.get(entity).and_then(|b| b[id.0])
|
||||
}
|
||||
pub fn id(&self, name: &str) -> Option<AttributeId> {
|
||||
self.ids.get(name).copied()
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ import net.minecraft.world.phys.Vec3;
|
||||
* equipment, attributes and passengers, and where the position syncs leave
|
||||
* it (VecDeltaCodec, as handleMoveEntity and handleEntityPositionSync).
|
||||
* Entity ids differ between servers: an entity is named by its type and the
|
||||
* block it was added in, passengers by those names. Players are left out.
|
||||
* block it was added in, passengers by those names. Players are left out, but
|
||||
* for the attributes the player itself is sent from its login on.
|
||||
*/
|
||||
final class EntityTranscript {
|
||||
private static final class Tracked {
|
||||
@@ -67,6 +68,21 @@ final class EntityTranscript {
|
||||
|
||||
private final Map<Integer, Tracked> byId = new HashMap<>();
|
||||
private final List<Tracked> all = new ArrayList<>();
|
||||
private int self = Integer.MIN_VALUE;
|
||||
private final Map<String, String> selfAttributes = new TreeMap<>();
|
||||
|
||||
/** The player's own id (login) and attribute instances; false for any other packet. */
|
||||
boolean acceptSelf(Packet<?> packet) {
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket p) {
|
||||
self = p.playerId();
|
||||
return true;
|
||||
}
|
||||
if (packet instanceof ClientboundUpdateAttributesPacket p && p.getEntityId() == self) {
|
||||
p.getValues().forEach(a -> selfAttributes.put(a.attribute().getRegisteredName(), a.base() + " " + a.modifiers()));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private int unknown;
|
||||
|
||||
/** Applies one packet; false when it isn't about a tracked entity. */
|
||||
@@ -158,6 +174,7 @@ final class EntityTranscript {
|
||||
+ " | attributes " + t.attributes + " | passengers " + riders + " | now " + t.codec.getBase() + " rot " + t.xRot + ","
|
||||
+ t.yRot + " head " + t.headRot + " ground " + t.onGround + " motion " + t.motion + t.power + (t.removed ? " | removed" : ""));
|
||||
}
|
||||
out.add("self attributes " + selfAttributes);
|
||||
out.sort(null);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -476,7 +476,7 @@ public final class VanillaProtocolClient {
|
||||
if (r != null) {
|
||||
Packet<?> packet = r.packet;
|
||||
counts.merge(r.type, 1, Integer::sum);
|
||||
if (entities != null && step >= ENTITIES) entities.accept(packet);
|
||||
if (entities != null && !entities.acceptSelf(packet) && step >= ENTITIES) entities.accept(packet);
|
||||
if (r.type.equals("minecraft:chunk_batch_start")) ordered = false;
|
||||
if (respawning && !respawned) {
|
||||
String line = respawnLine(r);
|
||||
|
||||
@@ -6,13 +6,17 @@ world vanilla generated first, with the same server.properties (offline, view di
|
||||
client (VanillaProtocolClient in its entity mode) joins, and once its chunks are in it asks for the scene: the
|
||||
console freezes the ticks, builds a wall and a rail and summons, around the spawn, every kind of minecart (one
|
||||
set rolling along the rail), boats and a raft (one falling onto the ground), armor stands (posed, small, with
|
||||
arms, wearing a helmet, one falling), a chicken jockey, item frames (one holding a turned diamond), paintings,
|
||||
primed TNT (one falling), a floating falling block, an arrow that lands and an end crystal. The client records
|
||||
for 20 seconds, the ticks running for 200 more after 3, what ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn
|
||||
arms, wearing a helmet, one falling), a chicken jockey, a slime, a pig whose scale `/attribute` sets, item
|
||||
frames (one holding a turned diamond), paintings, primed TNT (one falling), a floating falling block, an arrow
|
||||
that lands and an end crystal. The client records for 20 seconds, the ticks running for 200 more after 3, what
|
||||
ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn
|
||||
packet (position, rotations, data, motion), the entity data it was paired with and all it was sent since, its
|
||||
equipment and passengers, and where its position syncs leave it. Both transcripts must match exactly,
|
||||
entity by entity (named by type and the block it was added in). Attributes are recorded but not compared yet:
|
||||
Horizon sends no ClientboundUpdateAttributesPacket, for mobs either.
|
||||
equipment, its attribute instances (ClientboundUpdateAttributesPacket: the ones its first tick creates, the
|
||||
type's set by finalizeSpawn, the baby speed modifier, effects', equipment's and /attribute's) and passengers, and
|
||||
where its position syncs leave it; and the attribute instances the player itself is sent from its login on. Both
|
||||
transcripts must match exactly, entity by entity (named by type and the block it was added in), once the amounts
|
||||
of vanilla's random spawn modifiers are normalised (only client-syncable attributes are sent, so follow range and
|
||||
knockback resistance never show).
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -63,6 +67,10 @@ SCENE = [
|
||||
'Pose:{Head:[10f,20f,0f],RightArm:[-30f,0f,15f]},equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}',
|
||||
# A chicken jockey (passengers).
|
||||
'summon minecraft:chicken -6.5 -60 -2.5 {NoAI:1b,Passengers:[{id:"minecraft:husk",IsBaby:1b,NoAI:1b}]}',
|
||||
# Attributes: a slime's size sets its bases, /attribute a pig's scale.
|
||||
'summon minecraft:slime 2.5 -60 1.5 {Size:1,NoAI:1b}',
|
||||
'summon minecraft:pig -0.5 -60 1.5 {NoAI:1b}',
|
||||
'attribute @e[type=minecraft:pig,limit=1,x=-0.5,y=-60,z=1.5,distance=..1] minecraft:scale base set 1.5',
|
||||
# Frames and paintings on the wall's south face.
|
||||
'summon minecraft:item_frame -3.5 -59 -4.97 {block_pos:[I;-4,-59,-5],Facing:3b,'
|
||||
'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}',
|
||||
@@ -78,14 +86,19 @@ SCENE = [
|
||||
]
|
||||
|
||||
|
||||
# finalizeSpawn's random modifiers on client-syncable attributes (a leader zombie's max health); their amounts
|
||||
# differ from one server to the other.
|
||||
RANDOM_MODIFIERS = re.compile(r'(id=minecraft:(?:random_spawn_bonus|leader_zombie_bonus), amount=)[^,]+')
|
||||
|
||||
|
||||
def scene_lines(lines):
|
||||
"""The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere),
|
||||
without their attributes: ClientboundUpdateAttributesPacket isn't sent by Horizon yet, for mobs either."""
|
||||
"""The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere), the
|
||||
amounts of random spawn modifiers normalised."""
|
||||
out = []
|
||||
for line in lines:
|
||||
m = re.match(r'play-entities entity \S+ (-?\d+),-?\d+,(-?\d+)', line)
|
||||
if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10:
|
||||
out.append(re.sub(r' \| attributes \{[^|]*\}', '', line))
|
||||
if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10 or line.startswith('play-entities self '):
|
||||
out.append(RANDOM_MODIFIERS.sub(r'\1~', line))
|
||||
return out
|
||||
|
||||
|
||||
@@ -171,10 +184,10 @@ def main():
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
entities=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, item frames, paintings, primed '
|
||||
'TNT, a falling block, an arrow and an end crystal tracked to a '
|
||||
'vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, passengers and the '
|
||||
'positions the syncs leave them at.'))
|
||||
scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, a slime, a pig with a '
|
||||
'scale, item frames, paintings, primed TNT, a falling block, an arrow and an end crystal '
|
||||
'tracked to a vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, '
|
||||
'attributes, passengers and the positions the syncs leave them at.'))
|
||||
print(f'server entities: {len(vanilla)} entities identical')
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user