Skip to main content

steel_core/inventory/
equipment.rs

1//! Entity equipment access and owned storage.
2
3use std::mem;
4
5use steel_registry::item_stack::ItemStack;
6
7pub use steel_registry::equipment::{EquipmentSlot, EquipmentSlotType};
8
9/// Equipment access shared by player inventories and owned entity storage.
10pub trait EntityEquipment: Send {
11    /// Gets a reference to the item in a slot.
12    fn get_ref(&self, slot: EquipmentSlot) -> &ItemStack;
13
14    /// Gets a mutable reference to the item in a slot.
15    fn get_mut(&mut self, slot: EquipmentSlot) -> &mut ItemStack;
16
17    /// Sets the item in a slot, returning the old item.
18    fn set(&mut self, slot: EquipmentSlot, stack: ItemStack) -> ItemStack;
19
20    /// Takes the item from a slot, leaving an empty stack in its place.
21    fn take(&mut self, slot: EquipmentSlot) -> ItemStack;
22
23    /// Clears all equipment slots.
24    fn clear(&mut self);
25
26    /// Returns non-empty equipment slots for initial spawn synchronization.
27    fn non_empty_items(&self) -> Vec<(EquipmentSlot, ItemStack)> {
28        EquipmentSlot::ALL
29            .into_iter()
30            .filter_map(|slot| {
31                let item = self.get_ref(slot);
32                (!item.is_empty()).then(|| (slot, item.clone()))
33            })
34            .collect()
35    }
36}
37
38/// Owned equipment storage used by non-player living entities.
39pub struct OwnedEntityEquipment {
40    slots: [ItemStack; 8],
41}
42
43impl Default for OwnedEntityEquipment {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49impl OwnedEntityEquipment {
50    /// Creates a new empty equipment storage.
51    #[must_use]
52    pub fn new() -> Self {
53        Self {
54            slots: [
55                ItemStack::empty(),
56                ItemStack::empty(),
57                ItemStack::empty(),
58                ItemStack::empty(),
59                ItemStack::empty(),
60                ItemStack::empty(),
61                ItemStack::empty(),
62                ItemStack::empty(),
63            ],
64        }
65    }
66}
67
68impl EntityEquipment for OwnedEntityEquipment {
69    fn get_ref(&self, slot: EquipmentSlot) -> &ItemStack {
70        &self.slots[slot.index()]
71    }
72
73    fn get_mut(&mut self, slot: EquipmentSlot) -> &mut ItemStack {
74        &mut self.slots[slot.index()]
75    }
76
77    fn set(&mut self, slot: EquipmentSlot, stack: ItemStack) -> ItemStack {
78        mem::replace(&mut self.slots[slot.index()], stack)
79    }
80
81    fn take(&mut self, slot: EquipmentSlot) -> ItemStack {
82        mem::take(&mut self.slots[slot.index()])
83    }
84
85    fn clear(&mut self) {
86        for slot in EquipmentSlot::ALL {
87            self.slots[slot.index()] = ItemStack::empty();
88        }
89    }
90}