Skip to main content

voxel_framework/items/
inventory.rs

1//! Slot-based inventory resource and the [`ItemType`] trait.
2//!
3//! This module is the data layer of the item system.  It defines the
4//! [`ItemType`] trait that all item enums must implement, the [`Inventory`]
5//! resource that stores collected items, and the [`ItemPickedUp`] message
6//! emitted whenever items successfully enter the inventory.
7//!
8//! The design mirrors [`crate::voxel::VoxelType`]: item types are lightweight
9//! value types (typically unit-variant enums) stored densely in a flat slot
10//! vector.  The actual spawning, attraction, and pickup logic lives in
11//! [`crate::items::drops`]; this module is concerned only with the data model.
12
13use std::hash::Hash;
14
15use crate::voxel::{DefaultTerrainVoxel, VoxelType};
16use bevy::prelude::*;
17
18// ─── Container trait ─────────────────────────────────────────────────────────
19
20/// Neutral failure reasons for an atomic container exchange.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum ContainerExchangeError {
24    /// A positive sentinel quantity or an overflowing quantity list.
25    InvalidRequest,
26    /// The container's shape, live stacks, or totals are invalid.
27    InvalidContainer,
28    /// The container cannot supply every requested item.
29    InsufficientItems,
30    /// The post-consumption outputs exceed slot or numeric capacity.
31    CapacityExceeded,
32}
33
34/// Normalize by item equality, retaining first-occurrence order (not byte identity).
35pub(crate) fn normalize_quantities<I: ItemType>(
36    quantities: &[(I, u32)],
37) -> Result<Vec<(I, u32)>, ContainerExchangeError> {
38    let mut normalized: Vec<(I, u32)> = Vec::new();
39    for &(item, count) in quantities {
40        if count == 0 {
41            continue;
42        }
43        if item == I::default() || item.is_empty() {
44            return Err(ContainerExchangeError::InvalidRequest);
45        }
46        if let Some((_, total)) = normalized
47            .iter_mut()
48            .find(|(existing, _)| *existing == item)
49        {
50            *total = total
51                .checked_add(count)
52                .ok_or(ContainerExchangeError::InvalidRequest)?;
53        } else {
54            normalized.push((item, count));
55        }
56    }
57    Ok(normalized)
58}
59
60/// Abstraction over slot-based item storage.
61///
62/// Any type that holds items in indexed slots can implement this trait to be
63/// usable with the framework's pickup, hotbar, and crafting systems.
64///
65/// The framework provides two built-in implementors:
66/// - [`Inventory<I>`] — the standalone resource form (backward-compatible).
67/// - [`ContainerComponent<I>`] — the Bevy component form used by the new
68///   entity-based pipeline.
69pub trait Container<I: ItemType> {
70    /// Adds `count` of `item`.  Returns the number of items that could NOT be
71    /// inserted due to capacity (0 = all inserted).
72    fn add(&mut self, item: I, count: u32) -> u32;
73
74    /// Removes up to `count` of `item`.  Returns the number actually removed.
75    fn remove(&mut self, item: I, count: u32) -> u32;
76
77    /// Total number of `item` across all slots.
78    fn count_of(&self, item: I) -> u32;
79
80    /// Maximum number of distinct item stacks this container can hold.
81    fn capacity(&self) -> usize;
82
83    /// Returns `true` if every slot is occupied.
84    fn is_full(&self) -> bool;
85
86    /// Iterates over all slots, yielding `Some(&InventorySlot<I>)` for occupied
87    /// slots and `None` for empty ones.  Yields exactly `capacity()` items.
88    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>>;
89
90    /// Returns the slot at `index`, or `None` if the index is out of bounds or
91    /// the slot is empty.  Never panics.
92    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>>;
93
94    /// Optionally consume and produce a complete exchange atomically.
95    ///
96    /// `None` means unsupported; `None` and `Some(Err(_))` MUST leave the
97    /// container unchanged. `Some(Ok(()))` means every quantity was exchanged.
98    /// Normalize duplicates by equality in first-occurrence order, ignore zero
99    /// quantities, allow empty lists, and reject positive default/empty sentinels
100    /// and checked `u32` sums that overflow. Evaluate capacity after consumption.
101    /// The default keeps existing implementors compatible; legacy crafting may
102    /// partially mutate when their individual operations fail.
103    fn try_exchange_atomic(
104        &mut self,
105        _remove: &[(I, u32)],
106        _add: &[(I, u32)],
107    ) -> Option<Result<(), ContainerExchangeError>> {
108        None
109    }
110}
111
112// ─── ItemType trait ───────────────────────────────────────────────────────────
113
114/// Contract that all item types must satisfy to participate in the item pipeline.
115///
116/// Implement this trait for any `Copy + Hash + Default` enum to make it usable
117/// with [`Inventory`], [`crate::items::drops::DropTable`],
118/// [`crate::items::drops::DropsPlugin`], and
119/// [`crate::items::persistence::save_inventory`] /
120/// [`crate::items::persistence::load_inventory`].
121///
122/// The framework ships [`DefaultItem`] as a ready-made implementation.
123/// Custom implementations should designate one variant as the *empty sentinel*
124/// (returned by [`Default`]) and override [`ItemType::is_empty`] accordingly.
125///
126/// # Contract
127///
128/// * `Copy + Clone` — slots are copied freely; no heap allocation per item.
129/// * `Default` — produces the empty-sentinel value.
130/// * `PartialEq + Eq + Hash` — required for slot deduplication and hash-map
131///   lookups in [`crate::items::drops::DropTable`].
132/// * `Send + Sync + 'static` — required for use as a Bevy [`Resource`] type
133///   parameter.
134/// * [`to_byte`](ItemType::to_byte) / [`from_byte`](ItemType::from_byte) —
135///   stable single-byte encoding used by the JSON persistence layer.  Unknown
136///   bytes must round-trip to `Self::default()`.
137///
138/// # Examples
139///
140/// ```rust,no_run
141/// use voxel_framework::items::ItemType;
142///
143/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
144/// enum MyItem { #[default] Empty, Wood, Stone }
145///
146/// impl ItemType for MyItem {
147///     fn name(&self) -> &'static str {
148///         match self { MyItem::Empty => "Empty", MyItem::Wood => "Wood", MyItem::Stone => "Stone" }
149///     }
150///     fn color(&self) -> [f32; 4] {
151///         match self {
152///             MyItem::Empty => [0.0; 4],
153///             MyItem::Wood  => [0.55, 0.35, 0.20, 1.0],
154///             MyItem::Stone => [0.50, 0.50, 0.50, 1.0],
155///         }
156///     }
157///     fn to_byte(&self) -> u8   { match self { MyItem::Empty => 0, MyItem::Wood => 1, MyItem::Stone => 2 } }
158///     fn from_byte(b: u8) -> Self { match b { 1 => MyItem::Wood, 2 => MyItem::Stone, _ => MyItem::Empty } }
159///     fn is_empty(&self) -> bool { matches!(self, MyItem::Empty) }
160/// }
161/// ```
162pub trait ItemType: Copy + Clone + Default + Send + Sync + PartialEq + Eq + Hash + 'static {
163    /// Human-readable display name for this item (e.g. `"Iron Ore"`).
164    ///
165    /// Used by UI widgets such as the pickup notification overlay.
166    fn name(&self) -> &'static str;
167
168    /// Default RGBA display colour for this item, with components in `[0.0, 1.0]`.
169    ///
170    /// Used by hotbar and inventory UI as a fallback when no sprite is available,
171    /// and by the optional [`super::DropVisualPlugin`] for world drops.
172    fn color(&self) -> [f32; 4];
173
174    /// Encodes this item variant as a single byte for JSON persistence.
175    ///
176    /// The mapping must be stable across game versions; changing it will
177    /// corrupt existing save files.  The empty-sentinel variant should map
178    /// to `0`.
179    fn to_byte(&self) -> u8;
180
181    /// Decodes a single byte back into an item variant.
182    ///
183    /// Unknown byte values — for example from a future game version — **must**
184    /// return `Self::default()` rather than panicking so that save files from
185    /// newer versions degrade gracefully.
186    fn from_byte(b: u8) -> Self;
187
188    /// Returns `true` if this variant is the empty-slot sentinel.
189    ///
190    /// The default implementation returns `false`; override it for the variant
191    /// that represents "nothing here" (typically the `Default` variant).
192    fn is_empty(&self) -> bool {
193        false
194    }
195
196    /// Tool level provided when this item is the active hotbar selection.
197    ///
198    /// `0` = bare hands. Matched against [`crate::voxel::VoxelType::mining_level`]:
199    /// if `tool_level < voxel.mining_level()`, mining makes no progress.
200    ///
201    /// Default: `0`.
202    fn tool_level(&self) -> u8 {
203        0
204    }
205
206    /// Mining speed multiplier when this item is the active tool.
207    ///
208    /// The effective break time is divided by this value (`2.0` = twice as fast).
209    /// Default: `1.0`.
210    fn tool_speed(&self) -> f32 {
211        1.0
212    }
213}
214
215// ─── InventorySlot ────────────────────────────────────────────────────────────
216
217/// A single occupied inventory slot, holding a stack of one item type.
218///
219/// Slots are always non-empty — "no item" is represented by `None` at the
220/// [`Inventory::slots`] level rather than a zero-count `InventorySlot`.
221/// The `count` field is therefore always `>= 1` in practice; the drop systems
222/// never produce a zero-count slot.
223#[derive(Debug, Clone, PartialEq)]
224pub struct InventorySlot<I: ItemType> {
225    /// The item type stored in this slot.
226    pub item: I,
227    /// Number of items in the stack.  Always `>= 1` for a live slot.
228    pub count: u32,
229}
230
231// ─── Inventory ────────────────────────────────────────────────────────────────
232
233/// Fixed-capacity player inventory backed by a flat slot vector.
234///
235/// The inventory holds up to `capacity` stacks, each stored as
236/// `Option<`[`InventorySlot`]`<I>>`.  `None` denotes an empty slot.
237///
238/// Items of the same type are automatically stacked: [`Inventory::add`]
239/// fills existing stacks of the matching type before opening a new slot.
240/// [`Inventory::remove`] drains stacks in order and clears slots that reach
241/// zero.
242///
243/// The default capacity is 36 slots (4 rows × 9 columns), matching the
244/// standard Minecraft-style layout expected by the built-in hotbar and
245/// inventory UI widgets.
246///
247/// # Examples
248///
249/// ```rust,no_run
250/// use voxel_framework::items::{Inventory, DefaultItem};
251///
252/// let mut inv = Inventory::<DefaultItem>::new(9);
253/// inv.add(DefaultItem::IronOre, 5);
254/// assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
255/// ```
256#[derive(Resource, Debug, Clone)]
257pub struct Inventory<I: ItemType> {
258    /// The backing slot vector.  `None` at index `i` means slot `i` is empty.
259    ///
260    /// The length always equals `capacity`; slots are never removed from the
261    /// vector.
262    pub slots: Vec<Option<InventorySlot<I>>>,
263    /// Maximum number of distinct item stacks the inventory can hold.
264    ///
265    /// Set at construction time; cannot be changed after the fact without
266    /// rebuilding the inventory.
267    pub capacity: usize,
268}
269
270impl<I: ItemType> Inventory<I> {
271    /// Check publicly writable fields before transactional use or persistence.
272    pub(crate) fn validate_integrity(&self) -> Result<(), ContainerExchangeError> {
273        if self.capacity != self.slots.len() {
274            return Err(ContainerExchangeError::InvalidContainer);
275        }
276        let quantities: Vec<_> = self
277            .slots
278            .iter()
279            .flatten()
280            .map(|slot| (slot.item, slot.count))
281            .collect();
282        if quantities.iter().any(|(_, count)| *count == 0) {
283            return Err(ContainerExchangeError::InvalidContainer);
284        }
285        normalize_quantities(&quantities)
286            .map(|_| ())
287            .map_err(|_| ContainerExchangeError::InvalidContainer)
288    }
289
290    fn exchange_atomic(
291        &mut self,
292        remove: &[(I, u32)],
293        add: &[(I, u32)],
294    ) -> Result<(), ContainerExchangeError> {
295        let remove = normalize_quantities(remove)?;
296        let add = normalize_quantities(add)?;
297        self.validate_integrity()?;
298        if remove
299            .iter()
300            .any(|&(item, count)| self.count_of(item) < count)
301        {
302            return Err(ContainerExchangeError::InsufficientItems);
303        }
304        // Copy only private staging data: no extra Clone bound on item/container.
305        let mut staged = Self {
306            slots: self.slots.clone(),
307            capacity: self.capacity,
308        };
309        for (item, count) in remove {
310            if staged.remove(item, count) != count {
311                return Err(ContainerExchangeError::InsufficientItems);
312            }
313        }
314        for (item, count) in add {
315            if staged.add(item, count) != 0 {
316                return Err(ContainerExchangeError::CapacityExceeded);
317            }
318        }
319        self.slots = staged.slots;
320        Ok(())
321    }
322
323    /// Creates a new empty inventory with the given slot capacity.
324    pub fn new(capacity: usize) -> Self {
325        Self {
326            slots: vec![None; capacity],
327            capacity,
328        }
329    }
330
331    /// Adds `count` of `item` to the inventory.
332    ///
333    /// Items are stacked onto existing slots of the same type first, then into
334    /// empty slots. Returns the number of items that could **not** be added
335    /// because slot capacity or the per-item `u32` representational ceiling is
336    /// exceeded. This is not an author-configured stack limit. Invalid public
337    /// fields or positive default/empty sentinels are rejected without mutation.
338    pub fn add(&mut self, item: I, count: u32) -> u32 {
339        if count == 0 {
340            return 0;
341        }
342        if item == I::default() || item.is_empty() || self.validate_integrity().is_err() {
343            return count;
344        }
345        let accepted = count.min(u32::MAX - self.count_of(item));
346        let mut remaining = accepted;
347
348        // First pass: fill existing stacks.
349        for slot in self.slots.iter_mut().flatten() {
350            if remaining == 0 {
351                break;
352            }
353            if slot.item == item {
354                slot.count += remaining;
355                remaining = 0;
356            }
357        }
358
359        // Second pass: open new slots for leftovers.
360        if remaining > 0 {
361            for slot in self.slots.iter_mut() {
362                if remaining == 0 {
363                    break;
364                }
365                if slot.is_none() {
366                    *slot = Some(InventorySlot {
367                        item,
368                        count: remaining,
369                    });
370                    remaining = 0;
371                }
372            }
373        }
374
375        (count - accepted) + remaining
376    }
377
378    /// Removes up to `count` of `item` from the inventory.
379    ///
380    /// Returns the number of items that were actually removed (may be less than
381    /// `count` if the inventory held fewer).
382    pub fn remove(&mut self, item: I, count: u32) -> u32 {
383        let mut to_remove = count;
384        let mut removed = 0u32;
385
386        for slot in self.slots.iter_mut() {
387            if to_remove == 0 {
388                break;
389            }
390            if let Some(s) = slot {
391                if s.item == item {
392                    let take = s.count.min(to_remove);
393                    s.count -= take;
394                    to_remove -= take;
395                    removed += take;
396                    if s.count == 0 {
397                        *slot = None;
398                    }
399                }
400            }
401        }
402
403        removed
404    }
405
406    /// Returns the total number of `item`, defensively saturating for invalid
407    /// publicly modified fields rather than wrapping or panicking.
408    pub fn count_of(&self, item: I) -> u32 {
409        self.slots
410            .iter()
411            .flatten()
412            .filter(|s| s.item == item)
413            .fold(0u32, |total, slot| total.saturating_add(slot.count))
414    }
415
416    /// Returns `true` if every slot is occupied.
417    pub fn is_full(&self) -> bool {
418        self.slots.iter().all(|s| s.is_some())
419    }
420}
421
422impl<I: ItemType> Default for Inventory<I> {
423    /// Creates a default inventory with 36 slots (4 rows × 9 columns).
424    fn default() -> Self {
425        Self::new(36)
426    }
427}
428
429// ─── Container impl for Inventory ────────────────────────────────────────────
430
431impl<I: ItemType> Container<I> for Inventory<I> {
432    fn try_exchange_atomic(
433        &mut self,
434        remove: &[(I, u32)],
435        add: &[(I, u32)],
436    ) -> Option<Result<(), ContainerExchangeError>> {
437        Some(self.exchange_atomic(remove, add))
438    }
439
440    fn add(&mut self, item: I, count: u32) -> u32 {
441        Inventory::add(self, item, count)
442    }
443
444    fn remove(&mut self, item: I, count: u32) -> u32 {
445        Inventory::remove(self, item, count)
446    }
447
448    fn count_of(&self, item: I) -> u32 {
449        Inventory::count_of(self, item)
450    }
451
452    fn capacity(&self) -> usize {
453        self.capacity
454    }
455
456    fn is_full(&self) -> bool {
457        Inventory::is_full(self)
458    }
459
460    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
461        self.slots.iter().map(|s| s.as_ref())
462    }
463
464    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
465        self.slots.get(index).and_then(|s| s.as_ref())
466    }
467}
468
469// ─── ContainerComponent ───────────────────────────────────────────────────────
470
471/// Bevy [`Component`] newtype that wraps an [`Inventory<I>`] for use in the
472/// entity-based item pipeline.
473///
474/// Add this alongside [`PrimaryContainer`] on the player entity so the magnet,
475/// hotbar, and crafting systems can locate the player's inventory via ECS
476/// queries instead of a global resource.
477///
478/// # Examples
479///
480/// ```rust,no_run
481/// use bevy::prelude::*;
482/// use voxel_framework::items::{ContainerComponent, PrimaryContainer, DefaultItem};
483///
484/// fn spawn_player(mut commands: Commands) {
485///     commands.spawn((
486///         ContainerComponent::<DefaultItem>::new(36),
487///         PrimaryContainer,
488///     ));
489/// }
490/// ```
491#[derive(Component)]
492pub struct ContainerComponent<I: ItemType>(pub Inventory<I>);
493
494impl<I: ItemType> ContainerComponent<I> {
495    /// Creates a new `ContainerComponent` wrapping a fresh [`Inventory`] with
496    /// the given `capacity`.
497    pub fn new(capacity: usize) -> Self {
498        Self(Inventory::new(capacity))
499    }
500}
501
502impl<I: ItemType> Container<I> for ContainerComponent<I> {
503    fn try_exchange_atomic(
504        &mut self,
505        remove: &[(I, u32)],
506        add: &[(I, u32)],
507    ) -> Option<Result<(), ContainerExchangeError>> {
508        Container::try_exchange_atomic(&mut self.0, remove, add)
509    }
510
511    fn add(&mut self, item: I, count: u32) -> u32 {
512        self.0.add(item, count)
513    }
514
515    fn remove(&mut self, item: I, count: u32) -> u32 {
516        self.0.remove(item, count)
517    }
518
519    fn count_of(&self, item: I) -> u32 {
520        self.0.count_of(item)
521    }
522
523    fn capacity(&self) -> usize {
524        self.0.capacity
525    }
526
527    fn is_full(&self) -> bool {
528        self.0.is_full()
529    }
530
531    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
532        self.0.slots.iter().map(|s| s.as_ref())
533    }
534
535    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
536        self.0.slots.get(index).and_then(|s| s.as_ref())
537    }
538}
539
540// ─── PrimaryContainer marker ──────────────────────────────────────────────────
541
542/// Zero-size marker component that identifies the entity whose
543/// [`ContainerComponent`] is the player's primary backpack.
544///
545/// Exactly one entity should carry this marker at runtime.  If zero or more
546/// than one exist, the pickup and hotbar systems skip silently — no panic.
547#[derive(Component, Default)]
548pub struct PrimaryContainer;
549
550// ─── Messages ────────────────────────────────────────────────────────────────
551
552/// Message emitted when one or more items are successfully added to the inventory.
553///
554/// The magnet system in [`crate::items::drops`] writes this message after
555/// adding items to [`Inventory`].  UI systems — such as the pickup notification
556/// overlay — subscribe to this message to display transient feedback.
557///
558/// Note: this message is only written when at least one item was actually
559/// inserted (i.e. `count > 0`).  If the inventory was full the message is
560/// **not** written even though a pickup was attempted.
561#[derive(Message, Debug, Clone)]
562pub struct ItemPickedUp<I: ItemType> {
563    /// The item type that was picked up.
564    pub item: I,
565    /// Number of items that were successfully inserted.  Always `>= 1`.
566    pub count: u32,
567}
568
569// ─── DefaultItem ─────────────────────────────────────────────────────────────
570
571/// Built-in item type covering common mineral pickups.
572///
573/// `DefaultItem` is the item counterpart of [`crate::voxel::DefaultVoxel`]:
574/// it implements [`ItemType`] out of the box and is wired into the default
575/// [`crate::items::drops::DropTable`] entries provided by the framework.
576///
577/// `Empty` is the empty-slot sentinel returned by [`Default`] and by
578/// [`ItemType::from_byte`] for unknown byte values.  It should never appear
579/// as a real collectible.
580///
581/// # Examples
582///
583/// ```rust,no_run
584/// use voxel_framework::items::{DefaultItem, Inventory};
585///
586/// let mut inv = Inventory::<DefaultItem>::new(9);
587/// inv.add(DefaultItem::Crystal, 3);
588/// ```
589#[derive(
590    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
591)]
592pub enum DefaultItem {
593    /// Empty slot sentinel — not a real item; returned by [`Default`].
594    #[default]
595    Empty,
596    /// Dirt block; placeable Dirt voxel item (byte 2, matches DefaultTerrainVoxel::Dirt).
597    Dirt,
598    /// Sand block; placeable Sand voxel item (byte 4, matches DefaultTerrainVoxel::Sand).
599    Sand,
600    /// Wood log block; placeable Wood voxel item (byte 5, matches DefaultTerrainVoxel::Wood).
601    Wood,
602    /// Gravel block; placeable Gravel voxel item (byte 7, matches DefaultTerrainVoxel::Gravel).
603    Gravel,
604    /// Snow block; placeable Snow voxel item (byte 8, matches DefaultTerrainVoxel::Snow).
605    Snow,
606    /// Coal ore block; placeable CoalOre voxel item (byte 10, matches DefaultTerrainVoxel::CoalOre).
607    CoalOre,
608    /// Iron ore block; placeable IronOre voxel item (byte 11, matches DefaultTerrainVoxel::IronOre).
609    IronOre,
610    /// Cobblestone block; placeable Cobblestone voxel item (byte 12).
611    Cobblestone,
612    /// Sandstone block; placeable Sandstone voxel item (byte 13).
613    Sandstone,
614    /// Wooden planks block; placeable Planks voxel item (byte 14).
615    Planks,
616    /// Fired clay brick block; placeable Brick voxel item (byte 15).
617    Brick,
618    /// Coal lump; dropped from CoalOre voxels (byte 16).
619    Coal,
620    /// Smelted iron ingot; produced from IronOre (byte 17).
621    IronIngot,
622    /// Wood log; dropped from Wood voxels (byte 18).
623    Log,
624    /// Snowball; dropped from Snow voxels (byte 19).
625    Snowball,
626    /// Fragment of common rock; drops from Stone voxels (byte 20).
627    RockFragment,
628    /// Silicon crystal shard; drops from crystal voxels (byte 21).
629    Crystal,
630    /// Rare mineral node; drops from high-value voxels (byte 22).
631    RareMineral,
632    /// Wooden pickaxe — tool level 1, normal speed. Crafted from wood (byte 23).
633    WoodenPickaxe,
634    /// Stone pickaxe — tool level 1, 2× speed. Crafted from rock fragments (byte 24).
635    StonePickaxe,
636    /// Iron pickaxe — tool level 2, 4× speed. Crafted from iron ore (byte 25).
637    IronPickaxe,
638    /// Deprecated alias for IronOre block — maps to byte 11 on write, never returned by from_byte.
639    IronOreItem,
640}
641
642impl ItemType for DefaultItem {
643    fn name(&self) -> &'static str {
644        match self {
645            DefaultItem::Empty => "Empty",
646            DefaultItem::Dirt => "Dirt",
647            DefaultItem::Sand => "Sand",
648            DefaultItem::Wood => "Wood",
649            DefaultItem::Gravel => "Gravel",
650            DefaultItem::Snow => "Snow",
651            DefaultItem::CoalOre => "Coal Ore",
652            DefaultItem::IronOre => "Iron Ore",
653            DefaultItem::IronOreItem => "Iron Ore",
654            DefaultItem::Cobblestone => "Cobblestone",
655            DefaultItem::Sandstone => "Sandstone",
656            DefaultItem::Planks => "Planks",
657            DefaultItem::Brick => "Brick",
658            DefaultItem::Coal => "Coal",
659            DefaultItem::IronIngot => "Iron Ingot",
660            DefaultItem::Log => "Log",
661            DefaultItem::Snowball => "Snowball",
662            DefaultItem::RockFragment => "Rock Fragment",
663            DefaultItem::Crystal => "Crystal",
664            DefaultItem::RareMineral => "Rare Mineral",
665            DefaultItem::WoodenPickaxe => "Wooden Pickaxe",
666            DefaultItem::StonePickaxe => "Stone Pickaxe",
667            DefaultItem::IronPickaxe => "Iron Pickaxe",
668        }
669    }
670
671    fn color(&self) -> [f32; 4] {
672        match self {
673            DefaultItem::Empty => [0.0, 0.0, 0.0, 0.0],
674            // Block-items: delegate to the matching voxel color for visual consistency.
675            DefaultItem::Dirt
676            | DefaultItem::Sand
677            | DefaultItem::Wood
678            | DefaultItem::Gravel
679            | DefaultItem::Snow
680            | DefaultItem::CoalOre
681            | DefaultItem::IronOre
682            | DefaultItem::IronOreItem
683            | DefaultItem::Cobblestone
684            | DefaultItem::Sandstone
685            | DefaultItem::Planks
686            | DefaultItem::Brick => DefaultTerrainVoxel::from_byte(self.to_byte()).color(),
687            // Processed / dropped items — explicit colors.
688            DefaultItem::Coal => [0.15, 0.15, 0.15, 1.0],
689            DefaultItem::IronIngot => [0.75, 0.65, 0.55, 1.0],
690            DefaultItem::Log => [0.40, 0.28, 0.12, 1.0],
691            DefaultItem::Snowball => [0.92, 0.95, 1.00, 1.0],
692            DefaultItem::RockFragment => [0.35, 0.30, 0.28, 1.0],
693            DefaultItem::Crystal => [0.40, 0.50, 0.80, 1.0],
694            DefaultItem::RareMineral => [0.20, 0.85, 0.60, 1.0],
695            // Tools.
696            DefaultItem::WoodenPickaxe => [0.55, 0.35, 0.20, 1.0],
697            DefaultItem::StonePickaxe => [0.50, 0.50, 0.50, 1.0],
698            DefaultItem::IronPickaxe => [0.70, 0.75, 0.80, 1.0],
699        }
700    }
701
702    fn to_byte(&self) -> u8 {
703        match self {
704            DefaultItem::Empty => 0,
705            // Block-items: bytes match DefaultTerrainVoxel::to_byte()
706            DefaultItem::Dirt => 2,
707            DefaultItem::Sand => 4,
708            DefaultItem::Wood => 5,
709            DefaultItem::Gravel => 7,
710            DefaultItem::Snow => 8,
711            DefaultItem::CoalOre => 10,
712            DefaultItem::IronOre => 11,
713            DefaultItem::IronOreItem => 11, // deprecated alias; collapses to IronOre byte
714            DefaultItem::Cobblestone => 12,
715            DefaultItem::Sandstone => 13,
716            DefaultItem::Planks => 14,
717            DefaultItem::Brick => 15,
718            // Processed / dropped items
719            DefaultItem::Coal => 16,
720            DefaultItem::IronIngot => 17,
721            DefaultItem::Log => 18,
722            DefaultItem::Snowball => 19,
723            DefaultItem::RockFragment => 20,
724            DefaultItem::Crystal => 21,
725            DefaultItem::RareMineral => 22,
726            DefaultItem::WoodenPickaxe => 23,
727            DefaultItem::StonePickaxe => 24,
728            DefaultItem::IronPickaxe => 25,
729        }
730    }
731
732    fn from_byte(b: u8) -> Self {
733        match b {
734            // Block-items (bytes 2–15 mirror DefaultTerrainVoxel)
735            2 => DefaultItem::Dirt,
736            4 => DefaultItem::Sand,
737            5 => DefaultItem::Wood,
738            7 => DefaultItem::Gravel,
739            8 => DefaultItem::Snow,
740            10 => DefaultItem::CoalOre,
741            11 => DefaultItem::IronOre,
742            12 => DefaultItem::Cobblestone,
743            13 => DefaultItem::Sandstone,
744            14 => DefaultItem::Planks,
745            15 => DefaultItem::Brick,
746            // Processed / dropped items
747            16 => DefaultItem::Coal,
748            17 => DefaultItem::IronIngot,
749            18 => DefaultItem::Log,
750            19 => DefaultItem::Snowball,
751            20 => DefaultItem::RockFragment,
752            21 => DefaultItem::Crystal,
753            22 => DefaultItem::RareMineral,
754            23 => DefaultItem::WoodenPickaxe,
755            24 => DefaultItem::StonePickaxe,
756            25 => DefaultItem::IronPickaxe,
757            // Bytes 0, 1, 3, 6, 9 and anything else → Empty
758            _ => DefaultItem::Empty,
759        }
760    }
761
762    fn is_empty(&self) -> bool {
763        matches!(self, DefaultItem::Empty)
764    }
765
766    fn tool_level(&self) -> u8 {
767        match self {
768            DefaultItem::WoodenPickaxe => 1,
769            DefaultItem::StonePickaxe => 1,
770            DefaultItem::IronPickaxe => 2,
771            _ => 0,
772        }
773    }
774
775    fn tool_speed(&self) -> f32 {
776        match self {
777            DefaultItem::WoodenPickaxe => 1.0,
778            DefaultItem::StonePickaxe => 2.0,
779            DefaultItem::IronPickaxe => 4.0,
780            _ => 1.0,
781        }
782    }
783}
784
785// ─── Tests ───────────────────────────────────────────────────────────────────
786
787#[cfg(test)]
788mod tests {
789    use super::*;
790
791    // ── add ──────────────────────────────────────────────────────────────────
792
793    #[test]
794    fn test_inventory_add_and_count() {
795        let mut inv = Inventory::<DefaultItem>::new(9);
796        let leftover = inv.add(DefaultItem::IronOre, 5);
797        assert_eq!(leftover, 0);
798        assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
799    }
800
801    #[test]
802    fn test_inventory_add_stacks_same_type() {
803        let mut inv = Inventory::<DefaultItem>::new(9);
804        inv.add(DefaultItem::Crystal, 3);
805        inv.add(DefaultItem::Crystal, 7);
806        assert_eq!(inv.count_of(DefaultItem::Crystal), 10);
807        // Should occupy only one slot.
808        let filled = inv.slots.iter().filter(|s| s.is_some()).count();
809        assert_eq!(filled, 1);
810    }
811
812    // ── remove ───────────────────────────────────────────────────────────────
813
814    #[test]
815    fn test_inventory_remove() {
816        let mut inv = Inventory::<DefaultItem>::new(9);
817        inv.add(DefaultItem::RockFragment, 10);
818        let removed = inv.remove(DefaultItem::RockFragment, 4);
819        assert_eq!(removed, 4);
820        assert_eq!(inv.count_of(DefaultItem::RockFragment), 6);
821    }
822
823    #[test]
824    fn test_inventory_remove_more_than_held_returns_actual() {
825        let mut inv = Inventory::<DefaultItem>::new(9);
826        inv.add(DefaultItem::RareMineral, 3);
827        let removed = inv.remove(DefaultItem::RareMineral, 10);
828        assert_eq!(removed, 3);
829        assert_eq!(inv.count_of(DefaultItem::RareMineral), 0);
830    }
831
832    #[test]
833    fn test_inventory_remove_clears_slot() {
834        let mut inv = Inventory::<DefaultItem>::new(9);
835        inv.add(DefaultItem::IronOre, 2);
836        inv.remove(DefaultItem::IronOre, 2);
837        assert!(inv.slots[0].is_none());
838    }
839
840    // ── full ─────────────────────────────────────────────────────────────────
841
842    #[test]
843    fn test_inventory_full() {
844        let mut inv = Inventory::<DefaultItem>::new(2);
845        inv.add(DefaultItem::IronOre, 1);
846        inv.add(DefaultItem::Crystal, 1);
847        assert!(inv.is_full());
848
849        // Adding more should return a leftover.
850        let leftover = inv.add(DefaultItem::RockFragment, 5);
851        assert_eq!(leftover, 5);
852    }
853
854    // ── Container trait via Inventory ─────────────────────────────────────────
855
856    #[test]
857    fn container_trait_add_and_count() {
858        let mut inv = Inventory::<DefaultItem>::new(9);
859        let leftover = Container::add(&mut inv, DefaultItem::IronOre, 5);
860        assert_eq!(leftover, 0);
861        assert_eq!(Container::count_of(&inv, DefaultItem::IronOre), 5);
862    }
863
864    #[test]
865    fn container_slot_at_out_of_bounds_returns_none() {
866        let inv = Inventory::<DefaultItem>::new(9);
867        assert!(Container::slot_at(&inv, 100).is_none());
868    }
869
870    #[test]
871    fn container_iter_slots_yields_capacity_items() {
872        let inv = Inventory::<DefaultItem>::new(9);
873        assert_eq!(Container::iter_slots(&inv).count(), 9);
874    }
875
876    // ── ContainerComponent ───────────────────────────────────────────────────
877
878    #[test]
879    fn container_component_delegates_correctly() {
880        let mut cc = ContainerComponent::<DefaultItem>::new(9);
881        cc.add(DefaultItem::Crystal, 3);
882        assert_eq!(cc.count_of(DefaultItem::Crystal), 3);
883        assert_eq!(cc.0.count_of(DefaultItem::Crystal), 3);
884    }
885
886    #[test]
887    fn container_component_slot_at_oob_no_panic() {
888        let cc = ContainerComponent::<DefaultItem>::new(9);
889        assert!(cc.slot_at(100).is_none());
890    }
891
892    fn stack(item: DefaultItem, count: u32) -> Option<InventorySlot<DefaultItem>> {
893        Some(InventorySlot { item, count })
894    }
895
896    #[test]
897    fn exchange_normalizes_duplicates_and_uses_freed_capacity() {
898        let mut inv = Inventory::new(1);
899        inv.add(DefaultItem::IronOre, 4);
900        assert_eq!(
901            inv.try_exchange_atomic(
902                &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
903                &[(DefaultItem::Crystal, 1), (DefaultItem::Crystal, 2)],
904            ),
905            Some(Ok(()))
906        );
907        assert_eq!(inv.slots, vec![stack(DefaultItem::Crystal, 3)]);
908        assert_eq!(inv.capacity, 1);
909    }
910
911    #[test]
912    fn exchange_failure_preserves_exact_sparse_layout() {
913        let original = Inventory {
914            capacity: 4,
915            slots: vec![
916                stack(DefaultItem::IronOre, 2),
917                None,
918                stack(DefaultItem::IronOre, 1),
919                stack(DefaultItem::Crystal, 7),
920            ],
921        };
922        let requests = [
923            (
924                vec![(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
925                vec![],
926                ContainerExchangeError::InsufficientItems,
927            ),
928            (
929                vec![(DefaultItem::IronOre, 1)],
930                vec![(DefaultItem::Wood, 1), (DefaultItem::Sand, 1)],
931                ContainerExchangeError::CapacityExceeded,
932            ),
933            (
934                vec![(DefaultItem::IronOre, 1)],
935                vec![(DefaultItem::Crystal, u32::MAX)],
936                ContainerExchangeError::CapacityExceeded,
937            ),
938            (
939                vec![(DefaultItem::IronOre, u32::MAX), (DefaultItem::IronOre, 1)],
940                vec![],
941                ContainerExchangeError::InvalidRequest,
942            ),
943            (
944                vec![],
945                vec![(DefaultItem::Crystal, u32::MAX), (DefaultItem::Crystal, 1)],
946                ContainerExchangeError::InvalidRequest,
947            ),
948            (
949                vec![(DefaultItem::Empty, 1)],
950                vec![],
951                ContainerExchangeError::InvalidRequest,
952            ),
953            (
954                vec![],
955                vec![(DefaultItem::Empty, 1)],
956                ContainerExchangeError::InvalidRequest,
957            ),
958        ];
959        for (remove, add, error) in requests {
960            let mut inv = original.clone();
961            assert_eq!(inv.try_exchange_atomic(&remove, &add), Some(Err(error)));
962            assert_eq!(inv.slots, original.slots);
963            assert_eq!(inv.capacity, original.capacity);
964        }
965    }
966
967    #[test]
968    fn exchange_same_input_outputs_and_existing_duplicate_stacks() {
969        let mut inv = Inventory {
970            capacity: 4,
971            slots: vec![
972                stack(DefaultItem::IronOre, 2),
973                None,
974                stack(DefaultItem::IronOre, 3),
975                stack(DefaultItem::Crystal, 4),
976            ],
977        };
978        assert_eq!(
979            inv.try_exchange_atomic(
980                &[(DefaultItem::IronOre, 4)],
981                &[
982                    (DefaultItem::IronOre, 2),
983                    (DefaultItem::Crystal, 1),
984                    (DefaultItem::IronOre, 3)
985                ],
986            ),
987            Some(Ok(()))
988        );
989        assert_eq!(
990            inv.slots,
991            vec![
992                None,
993                None,
994                stack(DefaultItem::IronOre, 6),
995                stack(DefaultItem::Crystal, 5)
996            ]
997        );
998    }
999
1000    #[test]
1001    fn add_bounds_aggregate_headroom_and_returns_every_leftover() {
1002        let mut inv = Inventory {
1003            capacity: 3,
1004            slots: vec![
1005                stack(DefaultItem::Crystal, u32::MAX - 10),
1006                None,
1007                stack(DefaultItem::Crystal, 5),
1008            ],
1009        };
1010        assert_eq!(inv.add(DefaultItem::Crystal, 8), 3);
1011        assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
1012        assert_eq!(inv.slots[0], stack(DefaultItem::Crystal, u32::MAX - 5));
1013        assert_eq!(inv.slots[2], stack(DefaultItem::Crystal, 5));
1014        assert!(inv.slots[1].is_none());
1015        let before = inv.slots.clone();
1016        assert_eq!(inv.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
1017        assert_eq!(inv.slots, before);
1018        let mut full = Inventory::new(1);
1019        full.add(DefaultItem::IronOre, 1);
1020        assert_eq!(full.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
1021    }
1022
1023    #[test]
1024    fn malformed_sources_reject_exchange_and_add_without_mutation() {
1025        let invalid = [
1026            Inventory {
1027                capacity: 2,
1028                slots: vec![None],
1029            },
1030            Inventory {
1031                capacity: 0,
1032                slots: vec![None],
1033            },
1034            Inventory {
1035                capacity: 1,
1036                slots: vec![stack(DefaultItem::IronOre, 0)],
1037            },
1038            Inventory {
1039                capacity: 1,
1040                slots: vec![stack(DefaultItem::Empty, 1)],
1041            },
1042            Inventory {
1043                capacity: 2,
1044                slots: vec![
1045                    stack(DefaultItem::IronOre, u32::MAX),
1046                    stack(DefaultItem::IronOre, 1),
1047                ],
1048            },
1049        ];
1050        for mut inv in invalid {
1051            let before = inv.slots.clone();
1052            let capacity = inv.capacity;
1053            assert_eq!(
1054                inv.validate_integrity(),
1055                Err(ContainerExchangeError::InvalidContainer)
1056            );
1057            assert_eq!(
1058                inv.try_exchange_atomic(&[], &[]),
1059                Some(Err(ContainerExchangeError::InvalidContainer))
1060            );
1061            assert_eq!(inv.add(DefaultItem::Crystal, 5), 5);
1062            assert_eq!(inv.slots, before);
1063            assert_eq!(inv.capacity, capacity);
1064        }
1065    }
1066
1067    #[test]
1068    fn count_of_defensively_saturates_invalid_totals() {
1069        let inv = Inventory {
1070            capacity: 3,
1071            slots: vec![
1072                stack(DefaultItem::Crystal, u32::MAX),
1073                stack(DefaultItem::Crystal, u32::MAX),
1074                stack(DefaultItem::IronOre, 3),
1075            ],
1076        };
1077        assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
1078        assert_eq!(inv.count_of(DefaultItem::IronOre), 3);
1079    }
1080
1081    #[test]
1082    fn empty_lists_zero_quantities_and_zero_capacity_are_valid() {
1083        let mut inv = Inventory::<DefaultItem>::new(0);
1084        assert_eq!(inv.validate_integrity(), Ok(()));
1085        assert_eq!(inv.try_exchange_atomic(&[], &[]), Some(Ok(())));
1086        assert_eq!(
1087            inv.try_exchange_atomic(&[(DefaultItem::Empty, 0)], &[(DefaultItem::Empty, 0)]),
1088            Some(Ok(()))
1089        );
1090        assert_eq!(inv.add(DefaultItem::Empty, 0), 0);
1091        assert_eq!(inv.add(DefaultItem::Empty, 1), 1);
1092        assert_eq!(inv.add(DefaultItem::Crystal, 1), 1);
1093        assert!(inv.slots.is_empty());
1094    }
1095
1096    #[test]
1097    fn normalization_uses_equality_not_serialized_bytes_and_keeps_order() {
1098        assert_eq!(
1099            DefaultItem::IronOre.to_byte(),
1100            DefaultItem::IronOreItem.to_byte()
1101        );
1102        assert_ne!(DefaultItem::IronOre, DefaultItem::IronOreItem);
1103        assert_eq!(
1104            normalize_quantities(&[
1105                (DefaultItem::Empty, 0),
1106                (DefaultItem::IronOreItem, 1),
1107                (DefaultItem::Crystal, 0),
1108                (DefaultItem::IronOre, 2),
1109                (DefaultItem::IronOreItem, 3),
1110                (DefaultItem::Crystal, 5),
1111            ]),
1112            Ok(vec![
1113                (DefaultItem::IronOreItem, 4),
1114                (DefaultItem::IronOre, 2),
1115                (DefaultItem::Crystal, 5)
1116            ])
1117        );
1118    }
1119
1120    // Deliberately no Debug/Serialize derives and no is_empty override for Default.
1121    #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
1122    enum MinimalItem {
1123        #[default]
1124        DefaultSentinel,
1125        OtherSentinel,
1126        Live,
1127    }
1128
1129    impl ItemType for MinimalItem {
1130        fn name(&self) -> &'static str {
1131            "minimal"
1132        }
1133        fn color(&self) -> [f32; 4] {
1134            [1.0; 4]
1135        }
1136        fn to_byte(&self) -> u8 {
1137            1
1138        }
1139        fn from_byte(_: u8) -> Self {
1140            Self::default()
1141        }
1142        fn is_empty(&self) -> bool {
1143            *self == Self::OtherSentinel
1144        }
1145    }
1146
1147    #[test]
1148    fn exchange_requires_no_new_item_bounds_and_rejects_both_sentinels() {
1149        let mut inv = Inventory::<MinimalItem>::new(1);
1150        assert_eq!(inv.add(MinimalItem::DefaultSentinel, 1), 1);
1151        assert_eq!(inv.add(MinimalItem::OtherSentinel, 1), 1);
1152        assert_eq!(
1153            inv.try_exchange_atomic(&[], &[(MinimalItem::Live, 1)]),
1154            Some(Ok(()))
1155        );
1156        for sentinel in [MinimalItem::DefaultSentinel, MinimalItem::OtherSentinel] {
1157            assert_eq!(
1158                inv.try_exchange_atomic(&[(sentinel, 1)], &[]),
1159                Some(Err(ContainerExchangeError::InvalidRequest))
1160            );
1161            assert_eq!(
1162                inv.try_exchange_atomic(&[], &[(sentinel, 1)]),
1163                Some(Err(ContainerExchangeError::InvalidRequest))
1164            );
1165            assert_eq!(
1166                inv.try_exchange_atomic(&[(sentinel, 0)], &[(sentinel, 0)]),
1167                Some(Ok(()))
1168            );
1169            let invalid = Inventory {
1170                capacity: 1,
1171                slots: vec![Some(InventorySlot {
1172                    item: sentinel,
1173                    count: 1,
1174                })],
1175            };
1176            assert_eq!(
1177                invalid.validate_integrity(),
1178                Err(ContainerExchangeError::InvalidContainer)
1179            );
1180        }
1181        assert_eq!(inv.count_of(MinimalItem::Live), 1);
1182    }
1183
1184    #[test]
1185    fn component_atomic_exchange_matches_inventory_success_and_failure() {
1186        let mut inv = Inventory::new(1);
1187        inv.add(DefaultItem::IronOre, 4);
1188        let mut component = ContainerComponent(inv.clone());
1189        for (remove, add) in [
1190            (
1191                vec![(DefaultItem::IronOre, 4)],
1192                vec![(DefaultItem::Crystal, 3)],
1193            ),
1194            (vec![], vec![(DefaultItem::Wood, 1)]),
1195            (vec![(DefaultItem::Crystal, 4)], vec![]),
1196            (vec![], vec![(DefaultItem::Empty, 1)]),
1197        ] {
1198            assert_eq!(
1199                component.try_exchange_atomic(&remove, &add),
1200                inv.try_exchange_atomic(&remove, &add)
1201            );
1202            assert_eq!(component.0.slots, inv.slots);
1203            assert_eq!(component.capacity(), inv.capacity);
1204        }
1205        component.0.capacity = 2;
1206        let before = component.0.slots.clone();
1207        assert_eq!(
1208            component.try_exchange_atomic(&[], &[]),
1209            Some(Err(ContainerExchangeError::InvalidContainer))
1210        );
1211        assert_eq!(component.0.slots, before);
1212    }
1213}