diff --git a/crates/mcrs_minecraft_engine_registries/src/item_table_inputs.rs b/crates/mcrs_minecraft_engine_registries/src/item_table_inputs.rs index 8b6fa93ab..43dc840fa 100644 --- a/crates/mcrs_minecraft_engine_registries/src/item_table_inputs.rs +++ b/crates/mcrs_minecraft_engine_registries/src/item_table_inputs.rs @@ -1,6 +1,7 @@ use mcrs_minecraft_block::block_keys::Block; use mcrs_minecraft_entity::damage_type::DamageType; use mcrs_minecraft_entity::entity_type_keys::EntityType; +use mcrs_minecraft_entity::mob_effect_keys::MobEffect; use mcrs_minecraft_registries::Registries; use mcrs_minecraft_registries::Tags; use mcrs_minecraft_resource::ResourceLocation; @@ -17,6 +18,7 @@ pub struct ItemTableInputs { block_tags: Vec, entity_type_tags: Vec, damage_type_tags: Vec, + mob_effect_tags: Vec, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -34,6 +36,7 @@ impl ItemTableInputs { block_tags: tag_names(registries.tags::()), entity_type_tags: tag_names(registries.tags::()), damage_type_tags: tag_names(registries.tags::()), + mob_effect_tags: tag_names(registries.tags::()), } } } diff --git a/crates/mcrs_minecraft_engine_registries/src/registry_names.rs b/crates/mcrs_minecraft_engine_registries/src/registry_names.rs index bd7a19041..c6542022e 100644 --- a/crates/mcrs_minecraft_engine_registries/src/registry_names.rs +++ b/crates/mcrs_minecraft_engine_registries/src/registry_names.rs @@ -1,6 +1,7 @@ use mcrs_minecraft_block::block_keys::Block; use mcrs_minecraft_entity::damage_type::DamageType; use mcrs_minecraft_entity::entity_type_keys::EntityType; +use mcrs_minecraft_entity::mob_effect_keys::MobEffect; use mcrs_minecraft_item_stack::NameLookup; use mcrs_minecraft_item_stack::NameTable; use mcrs_minecraft_item_table::ItemTable; @@ -15,6 +16,7 @@ pub struct RegistryNames<'a> { block_tags: Option>, entity_type_tags: Option>, damage_type_tags: Option>, + mob_effect_tags: Option>, } impl<'a> RegistryNames<'a> { @@ -26,6 +28,7 @@ impl<'a> RegistryNames<'a> { block_tags: registries.tags::(), entity_type_tags: registries.tags::(), damage_type_tags: registries.tags::(), + mob_effect_tags: registries.tags::(), } } @@ -36,6 +39,7 @@ impl<'a> RegistryNames<'a> { block_tags: registries.tags::(), entity_type_tags: registries.tags::(), damage_type_tags: registries.tags::(), + mob_effect_tags: registries.tags::(), } } } @@ -141,6 +145,9 @@ impl NameLookup for RegistryNames<'_> { if table == NameTable::DamageTypeTag { return tag_id(self.damage_type_tags.as_ref()?, name); } + if table == NameTable::MobEffectTag { + return tag_id(self.mob_effect_tags.as_ref()?, name); + } let key = ResourceLocation::read(registry_key(table)?).ok()?; self.registries.id_of(key, name) } @@ -158,6 +165,9 @@ impl NameLookup for RegistryNames<'_> { if table == NameTable::DamageTypeTag { return tag_name(self.damage_type_tags.as_ref()?, id); } + if table == NameTable::MobEffectTag { + return tag_name(self.mob_effect_tags.as_ref()?, id); + } let key = ResourceLocation::read(registry_key(table)?).ok()?; let names = self.registries.names_of(key)?; Some(names.get(usize::from(id))?.as_location()) diff --git a/crates/mcrs_minecraft_item_stack/src/consumable.rs b/crates/mcrs_minecraft_item_stack/src/consumable.rs new file mode 100644 index 000000000..06065a407 --- /dev/null +++ b/crates/mcrs_minecraft_item_stack/src/consumable.rs @@ -0,0 +1,75 @@ +use alloc::vec::Vec; +use core::hash::{Hash, Hasher}; +use core::mem::{align_of, size_of}; + +use crate::ConsumeEffect; +use crate::SoundEventRef; +use crate::UseAnimation; +use crate::float_key; + +#[derive(Clone, Debug)] +#[cfg_attr(feature = "bevy", derive(bevy_ecs::component::Component))] +pub struct Consumable { + pub consume_seconds: f32, + pub animation: UseAnimation, + pub sound: Option, + pub has_consume_particles: bool, + pub on_consume_effects: Vec, +} + +impl Consumable { + pub const DEFAULT_CONSUME_SECONDS: f32 = 1.6; + pub const DEFAULT_ANIMATION: UseAnimation = UseAnimation::Eat; + pub const DEFAULT_HAS_CONSUME_PARTICLES: bool = true; + + #[must_use] + pub const fn new() -> Self { + Self { + consume_seconds: Self::DEFAULT_CONSUME_SECONDS, + animation: Self::DEFAULT_ANIMATION, + sound: None, + has_consume_particles: Self::DEFAULT_HAS_CONSUME_PARTICLES, + on_consume_effects: Vec::new(), + } + } +} + +impl Default for Consumable { + fn default() -> Self { + Self::new() + } +} + +impl PartialEq for Consumable { + fn eq(&self, other: &Self) -> bool { + float_key::of_f32(self.consume_seconds) == float_key::of_f32(other.consume_seconds) + && self.animation == other.animation + && self.sound == other.sound + && self.has_consume_particles == other.has_consume_particles + && self.on_consume_effects == other.on_consume_effects + } +} + +impl Eq for Consumable {} + +impl Hash for Consumable { + fn hash(&self, state: &mut H) { + float_key::of_f32(self.consume_seconds).hash(state); + self.animation.hash(state); + self.sound.hash(state); + self.has_consume_particles.hash(state); + self.on_consume_effects.hash(state); + } +} + +const _: () = { + assert!( + size_of::() + >= size_of::>() + size_of::>(), + "Consumable stores sound, effects list, and scalars" + ); + assert!( + align_of::() >= align_of::>(), + "Consumable aligns at least to vector alignment" + ); +}; diff --git a/crates/mcrs_minecraft_item_stack/src/consume_effect.rs b/crates/mcrs_minecraft_item_stack/src/consume_effect.rs new file mode 100644 index 000000000..e8e3c3ddb --- /dev/null +++ b/crates/mcrs_minecraft_item_stack/src/consume_effect.rs @@ -0,0 +1,104 @@ +use alloc::vec::Vec; +use core::hash::{Hash, Hasher}; +use core::mem::{align_of, size_of}; + +use crate::EffectInstance; +use crate::MobEffectSet; +use crate::SoundEventRef; +use crate::float_key; + +#[derive(Clone, Debug)] +pub enum ConsumeEffect { + ApplyEffects { + effects: Vec, + probability: f32, + }, + RemoveEffects(MobEffectSet), + ClearAllEffects, + TeleportRandomly { + diameter: f32, + directional_particles: bool, + }, + PlaySound(SoundEventRef), +} + +impl ConsumeEffect { + pub const DEFAULT_PROBABILITY: f32 = 1.0; + pub const DEFAULT_TELEPORT_DIAMETER: f32 = 16.0; + pub const DEFAULT_DIRECTIONAL_PARTICLES: bool = true; +} + +impl PartialEq for ConsumeEffect { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + ( + Self::ApplyEffects { + effects: left_effects, + probability: left_probability, + }, + Self::ApplyEffects { + effects: right_effects, + probability: right_probability, + }, + ) => { + left_effects == right_effects + && float_key::of_f32(*left_probability) == float_key::of_f32(*right_probability) + } + (Self::RemoveEffects(left), Self::RemoveEffects(right)) => left == right, + (Self::ClearAllEffects, Self::ClearAllEffects) => true, + ( + Self::TeleportRandomly { + diameter: left_diameter, + directional_particles: left_particles, + }, + Self::TeleportRandomly { + diameter: right_diameter, + directional_particles: right_particles, + }, + ) => { + float_key::of_f32(*left_diameter) == float_key::of_f32(*right_diameter) + && left_particles == right_particles + } + (Self::PlaySound(left), Self::PlaySound(right)) => left == right, + _ => false, + } + } +} + +impl Eq for ConsumeEffect {} + +impl Hash for ConsumeEffect { + fn hash(&self, state: &mut H) { + core::mem::discriminant(self).hash(state); + match self { + Self::ApplyEffects { + effects, + probability, + } => { + effects.hash(state); + float_key::of_f32(*probability).hash(state); + } + Self::RemoveEffects(effects) => effects.hash(state), + Self::ClearAllEffects => {} + Self::TeleportRandomly { + diameter, + directional_particles, + } => { + float_key::of_f32(*diameter).hash(state); + directional_particles.hash(state); + } + Self::PlaySound(sound) => sound.hash(state), + } + } +} + +const _: () = { + assert!( + size_of::() >= size_of::(), + "ConsumeEffect carries at least SoundEventRef" + ); + assert!( + align_of::() >= align_of::(), + "ConsumeEffect aligns at least to pointer alignment" + ); +}; diff --git a/crates/mcrs_minecraft_item_stack/src/effect_details.rs b/crates/mcrs_minecraft_item_stack/src/effect_details.rs new file mode 100644 index 000000000..5b2cd8f61 --- /dev/null +++ b/crates/mcrs_minecraft_item_stack/src/effect_details.rs @@ -0,0 +1,200 @@ +use alloc::boxed::Box; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::mem::{align_of, size_of}; + +const MAX_DEBUG_DEPTH: usize = 16; + +#[non_exhaustive] +pub struct EffectDetails { + pub amplifier: u8, + pub duration: i32, + pub ambient: bool, + pub show_particles: bool, + pub show_icon: bool, + pub hidden_effect: Option>, +} + +const _: () = { + assert!( + size_of::() == 8 + size_of::(), + "EffectDetails packs duration, flags, and optional boxed child" + ); + assert!( + align_of::() + == if align_of::() > 4 { + align_of::() + } else { + 4 + }, + "EffectDetails aligns to pointer or i32 alignment" + ); +}; + +impl EffectDetails { + #[must_use] + pub const fn new() -> Self { + Self { + amplifier: 0, + duration: 0, + ambient: false, + show_particles: true, + show_icon: true, + hidden_effect: None, + } + } + + pub(crate) fn drop_chain(head: &mut Option>) { + let mut next = head.take(); + while let Some(mut node) = next { + next = node.hidden_effect.take(); + } + } + + pub(crate) fn clone_chain(head: Option<&EffectDetails>) -> Option> { + let first = head?; + let mut root = Box::new(first.clone_shallow()); + let mut tail = &mut root.hidden_effect; + let mut cursor = first.hidden_effect.as_deref(); + while let Some(node) = cursor { + let inserted = tail.insert(Box::new(node.clone_shallow())); + tail = &mut inserted.hidden_effect; + cursor = node.hidden_effect.as_deref(); + } + Some(root) + } + + pub(crate) fn eq_chain( + mut left: Option<&EffectDetails>, + mut right: Option<&EffectDetails>, + ) -> bool { + while let (Some(left_node), Some(right_node)) = (left, right) { + if !left_node.shallow_eq(right_node) { + return false; + } + left = left_node.hidden_effect.as_deref(); + right = right_node.hidden_effect.as_deref(); + } + left.is_none() && right.is_none() + } + + pub(crate) fn hash_chain(mut cursor: Option<&EffectDetails>, state: &mut H) { + while let Some(node) = cursor { + true.hash(state); + node.hash_shallow(state); + cursor = node.hidden_effect.as_deref(); + } + false.hash(state); + } + + fn clone_shallow(&self) -> Self { + Self { + amplifier: self.amplifier, + duration: self.duration, + ambient: self.ambient, + show_particles: self.show_particles, + show_icon: self.show_icon, + hidden_effect: None, + } + } + + fn shallow_eq(&self, other: &Self) -> bool { + self.amplifier == other.amplifier + && self.duration == other.duration + && self.ambient == other.ambient + && self.show_particles == other.show_particles + && self.show_icon == other.show_icon + } + + fn hash_shallow(&self, state: &mut H) { + self.amplifier.hash(state); + self.duration.hash(state); + self.ambient.hash(state); + self.show_particles.hash(state); + self.show_icon.hash(state); + } + + pub(crate) fn debug_hidden(head: Option<&EffectDetails>) -> impl fmt::Debug + '_ { + HiddenEffectDebug(head) + } + + fn fmt_shallow_head(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "EffectDetails {{ amplifier: {:?}, duration: {:?}, ambient: {:?}, show_particles: {:?}, show_icon: {:?}, hidden_effect: ", + self.amplifier, self.duration, self.ambient, self.show_particles, self.show_icon + ) + } +} + +impl Default for EffectDetails { + fn default() -> Self { + Self::new() + } +} + +impl Drop for EffectDetails { + fn drop(&mut self) { + Self::drop_chain(&mut self.hidden_effect); + } +} + +impl Clone for EffectDetails { + fn clone(&self) -> Self { + let mut cloned = self.clone_shallow(); + cloned.hidden_effect = Self::clone_chain(self.hidden_effect.as_deref()); + cloned + } +} + +impl PartialEq for EffectDetails { + fn eq(&self, other: &Self) -> bool { + Self::eq_chain(Some(self), Some(other)) + } +} + +impl Eq for EffectDetails {} + +impl Hash for EffectDetails { + fn hash(&self, state: &mut H) { + self.hash_shallow(state); + Self::hash_chain(self.hidden_effect.as_deref(), state); + } +} + +impl fmt::Debug for EffectDetails { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.fmt_shallow_head(formatter)?; + fmt::Debug::fmt(&HiddenEffectDebug(self.hidden_effect.as_deref()), formatter)?; + formatter.write_str(" }") + } +} + +struct HiddenEffectDebug<'node>(Option<&'node EffectDetails>); + +impl fmt::Debug for HiddenEffectDebug<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let Some(first) = self.0 else { + return formatter.write_str("None"); + }; + let mut opened = 0usize; + let mut cursor = Some(first); + while let Some(node) = cursor { + if opened >= MAX_DEBUG_DEPTH { + formatter.write_str("Some(..)")?; + break; + } + formatter.write_str("Some(")?; + opened += 1; + node.fmt_shallow_head(formatter)?; + cursor = node.hidden_effect.as_deref(); + if cursor.is_none() { + formatter.write_str("None")?; + } + } + for _ in 0..opened { + formatter.write_str(" })")?; + } + Ok(()) + } +} diff --git a/crates/mcrs_minecraft_item_stack/src/effect_instance.rs b/crates/mcrs_minecraft_item_stack/src/effect_instance.rs index aa2f7dc1c..1c86458ab 100644 --- a/crates/mcrs_minecraft_item_stack/src/effect_instance.rs +++ b/crates/mcrs_minecraft_item_stack/src/effect_instance.rs @@ -1,6 +1,11 @@ +use alloc::boxed::Box; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::mem::{align_of, size_of}; + +use crate::EffectDetails; use crate::MobEffectId; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct EffectInstance { pub effect: MobEffectId, @@ -9,8 +14,21 @@ pub struct EffectInstance { pub ambient: bool, pub show_particles: bool, pub show_icon: bool, + pub hidden_effect: Option>, } +const _: () = { + assert!( + size_of::() + == (12 + size_of::()).next_multiple_of(align_of::()), + "EffectInstance packs effect id, duration, flags, and optional boxed child" + ); + assert!( + align_of::() == align_of::(), + "EffectInstance matches EffectDetails alignment" + ); +}; + impl EffectInstance { #[must_use] pub const fn new(effect: MobEffectId) -> Self { @@ -21,6 +39,147 @@ impl EffectInstance { ambient: false, show_particles: true, show_icon: true, + hidden_effect: None, + } + } +} + +impl Drop for EffectInstance { + fn drop(&mut self) { + EffectDetails::drop_chain(&mut self.hidden_effect); + } +} + +impl Clone for EffectInstance { + fn clone(&self) -> Self { + Self { + effect: self.effect, + amplifier: self.amplifier, + duration: self.duration, + ambient: self.ambient, + show_particles: self.show_particles, + show_icon: self.show_icon, + hidden_effect: EffectDetails::clone_chain(self.hidden_effect.as_deref()), } } } + +impl PartialEq for EffectInstance { + fn eq(&self, other: &Self) -> bool { + self.effect == other.effect + && self.amplifier == other.amplifier + && self.duration == other.duration + && self.ambient == other.ambient + && self.show_particles == other.show_particles + && self.show_icon == other.show_icon + && EffectDetails::eq_chain( + self.hidden_effect.as_deref(), + other.hidden_effect.as_deref(), + ) + } +} + +impl Eq for EffectInstance {} + +impl Hash for EffectInstance { + fn hash(&self, state: &mut H) { + self.effect.hash(state); + self.amplifier.hash(state); + self.duration.hash(state); + self.ambient.hash(state); + self.show_particles.hash(state); + self.show_icon.hash(state); + EffectDetails::hash_chain(self.hidden_effect.as_deref(), state); + } +} + +impl fmt::Debug for EffectInstance { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("EffectInstance") + .field("effect", &self.effect) + .field("amplifier", &self.amplifier) + .field("duration", &self.duration) + .field("ambient", &self.ambient) + .field("show_particles", &self.show_particles) + .field("show_icon", &self.show_icon) + .field( + "hidden_effect", + &EffectDetails::debug_hidden(self.hidden_effect.as_deref()), + ) + .finish() + } +} + +#[cfg(test)] +mod tests { + use core::hash::{Hash, Hasher}; + + use alloc::boxed::Box; + use alloc::format; + + use crate::{EffectDetails, EffectInstance, MobEffectId}; + + struct ByteMixHasher(u64); + + impl Hasher for ByteMixHasher { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + for &byte in bytes { + self.0 = self.0.wrapping_mul(131).wrapping_add(u64::from(byte)); + } + } + } + + #[test] + fn deep_hidden_effect_chain_is_iterative_across_clone_eq_hash_debug_and_drop() { + const CHAIN_DEPTH: usize = 50_000; + let mut head: Option> = None; + for step in 0..CHAIN_DEPTH { + let mut node = EffectDetails::new(); + node.duration = step as i32; + node.hidden_effect = head; + head = Some(Box::new(node)); + } + let mut instance = EffectInstance::new(MobEffectId(1)); + instance.hidden_effect = head; + + let cloned = instance.clone(); + assert_eq!( + instance, cloned, + "deep EffectInstance chain clone must equal original" + ); + + let mut mutated = cloned.clone(); + if let Some(child) = mutated.hidden_effect.as_deref_mut() { + child.amplifier = child.amplifier.wrapping_add(1); + } + assert_ne!( + instance, mutated, + "modifying deep EffectInstance chain must compare unequal" + ); + + let mut hash_left = ByteMixHasher(0); + let mut hash_right = ByteMixHasher(0); + instance.hash(&mut hash_left); + cloned.hash(&mut hash_right); + assert_eq!( + hash_left.finish(), + hash_right.finish(), + "equal deep EffectInstance chains must hash identically" + ); + + let formatted = format!("{instance:?}"); + assert!( + formatted.contains("Some(..)"), + "deep Debug output must bound recursion with Some(..)" + ); + + drop(mutated); + drop(cloned); + drop(instance); + } +} diff --git a/crates/mcrs_minecraft_item_stack/src/lib.rs b/crates/mcrs_minecraft_item_stack/src/lib.rs index 9b2b1f260..41828afe8 100644 --- a/crates/mcrs_minecraft_item_stack/src/lib.rs +++ b/crates/mcrs_minecraft_item_stack/src/lib.rs @@ -26,6 +26,8 @@ mod charged_projectiles; mod check_saved_form; mod component_hash; mod component_type; +mod consumable; +mod consume_effect; mod container; mod container_loot; mod count; @@ -46,6 +48,7 @@ pub mod data_component_type_keys; mod dimension_pos; mod dye_color; mod dyed_color; +mod effect_details; mod effect_instance; mod enchantment_glint_override; mod enchantment_id; @@ -91,6 +94,8 @@ mod map_id; mod max_damage; mod max_stack_size; mod mob_effect_id; +mod mob_effect_set; +mod mob_effect_tag_id; mod modifier_display; mod name_lookup; mod name_table; @@ -141,6 +146,7 @@ mod trim_pattern_id; mod unbreakable; mod undecoded_value; mod undecoded_wire_value; +mod use_animation; mod use_effects; mod weapon; mod wire; @@ -174,6 +180,8 @@ pub use builtin_key::BuiltinKey; pub use bundle_contents::BundleContents; pub use charged_projectiles::ChargedProjectiles; pub use component_type::ComponentType; +pub use consumable::Consumable; +pub use consume_effect::ConsumeEffect; pub use container::Container; pub use container_loot::ContainerLoot; pub use count::Count; @@ -191,6 +199,7 @@ pub use damage_type_tag_id::DamageTypeTagId; pub use dimension_pos::DimensionPos; pub use dye_color::DyeColor; pub use dyed_color::DyedColor; +pub use effect_details::EffectDetails; pub use effect_instance::EffectInstance; pub use enchantment_glint_override::EnchantmentGlintOverride; pub use enchantment_id::EnchantmentId; @@ -233,6 +242,8 @@ pub use max_damage::MaxDamage; pub use max_stack_size::MaxStackSize; pub use mcrs_minecraft_profile::Profile; pub use mob_effect_id::MobEffectId; +pub use mob_effect_set::MobEffectSet; +pub use mob_effect_tag_id::MobEffectTagId; pub use modifier_display::ModifierDisplay; pub use name_lookup::NameLookup; pub use name_table::NameTable; @@ -273,6 +284,7 @@ pub use trim_pattern_id::TrimPatternId; pub use unbreakable::Unbreakable; pub use undecoded_value::UndecodedValue; pub use undecoded_wire_value::UndecodedWireValue; +pub use use_animation::UseAnimation; pub use use_effects::UseEffects; pub use weapon::Weapon; pub use wire::read_wire; diff --git a/crates/mcrs_minecraft_item_stack/src/mob_effect_set.rs b/crates/mcrs_minecraft_item_stack/src/mob_effect_set.rs new file mode 100644 index 000000000..e8619c971 --- /dev/null +++ b/crates/mcrs_minecraft_item_stack/src/mob_effect_set.rs @@ -0,0 +1,23 @@ +use alloc::borrow::Cow; +use core::mem::{align_of, size_of}; + +use crate::BlockSet; +use crate::MobEffectId; +use crate::MobEffectTagId; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum MobEffectSet { + Tag(MobEffectTagId), + Effects(Cow<'static, [MobEffectId]>), +} + +const _: () = { + assert!( + size_of::() == size_of::(), + "MobEffectSet matches BlockSet size" + ); + assert!( + align_of::() == align_of::(), + "MobEffectSet matches BlockSet alignment" + ); +}; diff --git a/crates/mcrs_minecraft_item_stack/src/mob_effect_tag_id.rs b/crates/mcrs_minecraft_item_stack/src/mob_effect_tag_id.rs new file mode 100644 index 000000000..26167a99f --- /dev/null +++ b/crates/mcrs_minecraft_item_stack/src/mob_effect_tag_id.rs @@ -0,0 +1,11 @@ +use core::mem::{align_of, size_of}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct MobEffectTagId(pub u16); + +const _: () = { + assert!( + size_of::() == 2 && align_of::() == 2, + "MobEffectTagId wraps one u16" + ); +}; diff --git a/crates/mcrs_minecraft_item_stack/src/name_table.rs b/crates/mcrs_minecraft_item_stack/src/name_table.rs index 225734933..5b0d08a18 100644 --- a/crates/mcrs_minecraft_item_stack/src/name_table.rs +++ b/crates/mcrs_minecraft_item_stack/src/name_table.rs @@ -12,6 +12,7 @@ pub enum NameTable { EntityType, EntityTypeTag, MobEffect, + MobEffectTag, DamageType, DamageTypeTag, Potion, diff --git a/crates/mcrs_minecraft_item_stack/src/saved.rs b/crates/mcrs_minecraft_item_stack/src/saved.rs index 59df27903..44b4527f7 100644 --- a/crates/mcrs_minecraft_item_stack/src/saved.rs +++ b/crates/mcrs_minecraft_item_stack/src/saved.rs @@ -56,6 +56,7 @@ use crate::DamageTypeTagId; use crate::DimensionPos; use crate::DyeColor; use crate::DyedColor; +use crate::EffectDetails; use crate::EffectInstance; use crate::EnchantmentGlintOverride; use crate::EnchantmentId; @@ -990,31 +991,60 @@ impl Reader<'_, L> { } _ => self.map(tag)?, }; + let effect_depth = self.depth.saturating_add(4); Ok(PotionContents { potion: self.optional(map, "potion", Self::potion)?, custom_color: self.optional(map, "custom_color", |reader, tag| { Ok(reader.number(tag)?.to_int()) })?, - custom_effects: self.listed(map, "custom_effects", Self::effect_instance)?, + custom_effects: self.listed(map, "custom_effects", |reader, tag| { + reader.effect_instance_stripping_hidden(tag, effect_depth) + })?, custom_name: self.optional(map, "custom_name", |reader, tag| { Ok(reader.string(tag)?.to_string()) })?, }) } - fn effect_instance(&self, tag: &NbtTag) -> Result { + fn effect_instance_stripping_hidden( + &self, + tag: &NbtTag, + depth: u32, + ) -> Result { let map = self.map(tag)?; - let mut effect = EffectInstance::new(self.mob_effect(self.necessary(map, "id")?)?); + let id = self.mob_effect(self.necessary(map, "id")?)?; + let details = self.effect_details_stripping_hidden(map, depth)?; + let mut effect = EffectInstance::new(id); + effect.amplifier = details.amplifier; + effect.duration = details.duration; + effect.ambient = details.ambient; + effect.show_particles = details.show_particles; + effect.show_icon = details.show_icon; + Ok(effect) + } + + fn effect_details_stripping_hidden( + &self, + map: &NbtCompound, + depth: u32, + ) -> Result { + if depth > MAX_DEPTH { + return Err(SavedError::TooDeep); + } + let mut details = EffectDetails::new(); if let Some(amplifier) = map.get("amplifier") { - effect.amplifier = self.number(amplifier)?.to_int() as u8; + details.amplifier = self.number(amplifier)?.to_int() as u8; } if let Some(duration) = map.get("duration") { - effect.duration = self.number(duration)?.to_int(); + details.duration = self.number(duration)?.to_int(); } - effect.ambient = self.flag(map, "ambient", false)?; - effect.show_particles = self.flag(map, "show_particles", true)?; - effect.show_icon = self.flag(map, "show_icon", effect.show_particles)?; - Ok(effect) + details.ambient = self.flag(map, "ambient", false)?; + details.show_particles = self.flag(map, "show_particles", true)?; + details.show_icon = self.flag(map, "show_icon", details.show_particles)?; + let _ = self.optional(map, "hidden_effect", |reader, tag| { + reader.effect_details_stripping_hidden(reader.map(tag)?, depth.saturating_add(1)) + })?; + Ok(details) } fn custom_data(&self, tag: &NbtTag) -> Result { diff --git a/crates/mcrs_minecraft_item_stack/src/saved_form.rs b/crates/mcrs_minecraft_item_stack/src/saved_form.rs index 6376f4e3a..f2d53e22e 100644 --- a/crates/mcrs_minecraft_item_stack/src/saved_form.rs +++ b/crates/mcrs_minecraft_item_stack/src/saved_form.rs @@ -686,8 +686,9 @@ impl Walk<'_, L> { let potion = (contents.potion) .map(|potion| self.entry(sink, NameTable::Potion, potion.0)) .transpose()?; + let effect_depth = self.depth.saturating_add(4); let custom_effects = listed(sink, &contents.custom_effects, |sink, effect| { - self.effect_instance(sink, effect) + self.effect_instance(sink, effect, effect_depth) })?; let custom_color = (contents.custom_color).map(|color| sink.leaf(Leaf::Int(color))); let custom_name = @@ -704,7 +705,11 @@ impl Walk<'_, L> { &self, sink: &S, effect: &EffectInstance, + depth: u32, ) -> Result { + if depth > MAX_DEPTH { + return Err(Fault::TooDeep); + } let id = self.entry(sink, NameTable::MobEffect, effect.effect.0)?; let amplifier = (effect.amplifier != 0).then(|| sink.leaf(Leaf::Byte(effect.amplifier.cast_signed()))); diff --git a/crates/mcrs_minecraft_item_stack/src/use_animation.rs b/crates/mcrs_minecraft_item_stack/src/use_animation.rs new file mode 100644 index 000000000..5c648fddf --- /dev/null +++ b/crates/mcrs_minecraft_item_stack/src/use_animation.rs @@ -0,0 +1,63 @@ +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum UseAnimation { + None, + #[default] + Eat, + Drink, + Block, + Bow, + Trident, + Crossbow, + Spyglass, + TootHorn, + Brush, + Bundle, + Spear, +} + +impl UseAnimation { + pub(crate) const ALL: [Self; 12] = [ + Self::None, + Self::Eat, + Self::Drink, + Self::Block, + Self::Bow, + Self::Trident, + Self::Crossbow, + Self::Spyglass, + Self::TootHorn, + Self::Brush, + Self::Bundle, + Self::Spear, + ]; + + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Self::None => "none", + Self::Eat => "eat", + Self::Drink => "drink", + Self::Block => "block", + Self::Bow => "bow", + Self::Trident => "trident", + Self::Crossbow => "crossbow", + Self::Spyglass => "spyglass", + Self::TootHorn => "toot_horn", + Self::Brush => "brush", + Self::Bundle => "bundle", + Self::Spear => "spear", + } + } + + #[must_use] + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|value| value.name() == name) + } +} + +const _: () = { + assert!( + core::mem::size_of::() == 1 && core::mem::align_of::() == 1, + "UseAnimation is a single-byte enum" + ); +}; diff --git a/crates/mcrs_minecraft_item_stack/src/wire_value.rs b/crates/mcrs_minecraft_item_stack/src/wire_value.rs index e291c2c6d..039a47b6f 100644 --- a/crates/mcrs_minecraft_item_stack/src/wire_value.rs +++ b/crates/mcrs_minecraft_item_stack/src/wire_value.rs @@ -52,6 +52,7 @@ use crate::DamageTypeTagId; use crate::DimensionPos; use crate::DyeColor; use crate::DyedColor; +use crate::EffectDetails; use crate::EffectInstance; use crate::EnchantmentGlintOverride; use crate::EnchantmentId; @@ -880,33 +881,45 @@ impl Reader<'_, L> { custom_color: self.optional(input, |reader, input| { Ok(i32::from_be_bytes(reader.bytes(input)?)) })?, - custom_effects: self.list(input, Self::effect_instance)?, + custom_effects: self.list(input, Self::effect_instance_stripping_hidden)?, custom_name: self.optional(input, Self::string)?, }) } - fn effect_instance(&self, input: &mut &[u8]) -> Result { + fn effect_instance_stripping_hidden( + &self, + input: &mut &[u8], + ) -> Result { let mut effect = EffectInstance::new(MobEffectId(self.known_id(input, NameTable::MobEffect)?)); - self.effect_details(input, &mut effect)?; - let mut hidden = EffectInstance::new(effect.effect); - while self.boolean(input)? { - self.effect_details(input, &mut hidden)?; - } + let details = self.effect_details_stripping_hidden(input, self.depth)?; + effect.amplifier = details.amplifier; + effect.duration = details.duration; + effect.ambient = details.ambient; + effect.show_particles = details.show_particles; + effect.show_icon = details.show_icon; Ok(effect) } - fn effect_details( + fn effect_details_stripping_hidden( &self, input: &mut &[u8], - effect: &mut EffectInstance, - ) -> Result<(), WireError> { - effect.amplifier = u8::try_from(self.var_int(input)?.clamp(0, 255)).unwrap_or(u8::MAX); - effect.duration = self.var_int(input)?; - effect.ambient = self.boolean(input)?; - effect.show_particles = self.boolean(input)?; - effect.show_icon = self.boolean(input)?; - Ok(()) + depth: u32, + ) -> Result { + let mut details = EffectDetails::new(); + details.amplifier = u8::try_from(self.var_int(input)?.clamp(0, 255)).unwrap_or(u8::MAX); + details.duration = self.var_int(input)?; + details.ambient = self.boolean(input)?; + details.show_particles = self.boolean(input)?; + details.show_icon = self.boolean(input)?; + if self.boolean(input)? { + let next_depth = depth.saturating_add(1); + if next_depth > MAX_DEPTH { + return Err(WireError::TooDeep); + } + let _ = self.effect_details_stripping_hidden(input, next_depth)?; + } + Ok(details) } fn custom_data(&self, input: &mut &[u8]) -> Result { diff --git a/crates/mcrs_minecraft_item_stack/tests/it/saved.rs b/crates/mcrs_minecraft_item_stack/tests/it/saved.rs index 2cf8b60f2..1b5f3ac88 100644 --- a/crates/mcrs_minecraft_item_stack/tests/it/saved.rs +++ b/crates/mcrs_minecraft_item_stack/tests/it/saved.rs @@ -9,11 +9,13 @@ use mcrs_minecraft_item_stack::AttributeModifiers; use mcrs_minecraft_item_stack::BlockId; use mcrs_minecraft_item_stack::BlockSet; use mcrs_minecraft_item_stack::BlockTagId; +use mcrs_minecraft_item_stack::Builtin; use mcrs_minecraft_item_stack::BuiltinKey; use mcrs_minecraft_item_stack::ComponentType; use mcrs_minecraft_item_stack::CustomName; use mcrs_minecraft_item_stack::Damage; use mcrs_minecraft_item_stack::DimensionPos; +use mcrs_minecraft_item_stack::EffectInstance; use mcrs_minecraft_item_stack::EnchantmentId; use mcrs_minecraft_item_stack::EnchantmentLevel; use mcrs_minecraft_item_stack::Enchantments; @@ -994,3 +996,55 @@ fn use_effects_and_blocks_attacks_validate_ranges_in_saved_form() { "expected out of range for item_damage.threshold=-0.0" ); } + +fn nested_hidden_effect_tag(levels: usize) -> NbtCompound { + let mut current = NbtCompound::new(); + current.put("show_icon", NbtTag::Byte(1)); + for _ in 0..levels { + let mut outer = NbtCompound::new(); + outer.put("show_icon", NbtTag::Byte(1)); + outer.put("hidden_effect", NbtTag::Compound(current)); + current = outer; + } + current +} + +#[test] +fn potion_contents_enforces_depth_512_when_stripping_hidden_effect_in_saved_form() { + let potion_valid = { + let mut effect = nested_hidden_effect_tag(507); + effect.put("id", NbtTag::String("minecraft:speed".into())); + let mut potion = NbtCompound::new(); + potion.put( + "custom_effects", + NbtTag::List(vec![NbtTag::Compound(effect)]), + ); + with_component("potion_contents", NbtTag::Compound(potion)) + }; + let parsed_potion = read_saved(&potion_valid, &Names) + .expect("potion_contents within depth 512 strips hidden_effect"); + assert!( + matches!( + parsed_potion.patch(), + [PatchEntry::Value(Builtin::PotionContents(contents))] + if matches!(contents.custom_effects.as_slice(), [EffectInstance { hidden_effect: None, .. }]) + ), + "potion_contents must strip nested hidden_effect on read" + ); + + let potion_too_deep = { + let mut effect = nested_hidden_effect_tag(508); + effect.put("id", NbtTag::String("minecraft:speed".into())); + let mut potion = NbtCompound::new(); + potion.put( + "custom_effects", + NbtTag::List(vec![NbtTag::Compound(effect)]), + ); + with_component("potion_contents", NbtTag::Compound(potion)) + }; + assert_eq!( + read_saved(&potion_too_deep, &Names), + Err(SavedError::TooDeep), + "potion_contents with hidden_effect deeper than 512 returns TooDeep" + ); +} diff --git a/crates/mcrs_minecraft_item_stack/tests/it/wire.rs b/crates/mcrs_minecraft_item_stack/tests/it/wire.rs index fd3ae4885..280fcdc91 100644 --- a/crates/mcrs_minecraft_item_stack/tests/it/wire.rs +++ b/crates/mcrs_minecraft_item_stack/tests/it/wire.rs @@ -1653,6 +1653,36 @@ fn weapon_wire_round_trips_and_rejects_out_of_range() { let negative_wire = with_one_component("weapon", "ffffffff0f00000000"); assert_eq!( read_all(&negative_wire, read_wire), - Err(WireError::OutOfRange(BuiltinKey::Weapon)) + Err(WireError::OutOfRange(BuiltinKey::Weapon)), + "weapon with negative damage should reject out of range" + ); +} + +#[test] +fn potion_contents_enforces_depth_512_when_stripping_hidden_effect_in_wire_form() { + let potion_id = COMPONENT_TYPES + .iter() + .position(|name| *name == "potion_contents") + .expect("potion_contents component type registered"); + let mut frame = vec![ + 1, + 1, + 1, + 0, + u8::try_from(potion_id).expect("id fits byte"), + 0, + 0, + 1, + 0, + ]; + for _ in 0..512 { + frame.extend_from_slice(&[0, 0, 0, 1, 1, 1]); + } + frame.extend_from_slice(&[0, 0, 0, 1, 1, 0]); + frame.push(0); + assert_eq!( + read_all(&frame, read_wire), + Err(WireError::TooDeep), + "potion_contents with > 512 hidden_effects rejects TooDeep before deep recursion" ); }