Skip to main content

voxel_framework/items/
drops.rs

1//! Drop table, world-entity lifecycle, and magnet pickup systems.
2//!
3//! When a voxel is destroyed the mining subsystem emits a
4//! [`crate::world::VoxelBroken`] message.  This module listens to that message
5//! and drives the full item-drop pipeline:
6//!
7//! 1. **Spawn** — `spawn_drops_system` consults [`DropTable`] and spawns a
8//!    [`DroppedItem`] entity at the broken voxel's world position.
9//! 2. **Attract** — `magnet_system` applies a configurable acceleration toward
10//!    any entity tagged with [`ItemCollector`] once the item is within
11//!    [`MagnetConfig::radius`] world units.
12//! 3. **Collect** — when the item reaches within 0.5 units of the collector,
13//!    `magnet_system` calls [`crate::items::inventory::Inventory::add`], emits
14//!    [`crate::items::inventory::ItemPickedUp`], and despawns the entity.
15//! 4. **Expire** — items that are never collected despawn automatically after
16//!    their [`DroppedItem::lifetime`] reaches zero (default 60 seconds).
17//!
18//! # Plugin registration
19//!
20//! [`DropsPlugin`] is intentionally **not** bundled inside
21//! [`crate::VoxelPlugin`] because it is generic over `I: `[`ItemType`].
22//! Add it explicitly in game code, alongside
23//! [`crate::generator::GeneratorPlugin`]:
24//!
25//! ```rust,no_run
26//! use bevy::prelude::*;
27//! use voxel_framework::items::{DefaultItem, DropsPlugin};
28//!
29//! App::new().add_plugins(DropsPlugin::<DefaultItem>::new());
30//! ```
31
32use std::collections::HashMap;
33use std::marker::PhantomData;
34
35use bevy::prelude::*;
36
37use crate::world::VoxelBroken;
38
39use super::inventory::{ContainerComponent, ItemPickedUp, ItemType, PrimaryContainer};
40
41// ─── DropTable ────────────────────────────────────────────────────────────────
42
43/// One runtime drop entry for a voxel byte.
44///
45/// This is the runtime counterpart of
46/// [`crate::content::BlockDropDefinition`]. It is intentionally keyed by voxel
47/// byte because [`DropsPlugin`] reacts to [`crate::world::VoxelBroken`] events,
48/// and those events carry the destroyed voxel byte.
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct DropTableEntry<I: ItemType> {
51    /// Item produced by this entry.
52    pub item: I,
53    /// Minimum count, inclusive.
54    pub min_count: u32,
55    /// Maximum count, inclusive.
56    pub max_count: u32,
57    /// Probability in `0.0..=1.0`.
58    pub chance: f32,
59}
60
61impl<I: ItemType> DropTableEntry<I> {
62    /// Creates a guaranteed drop entry.
63    pub fn new(item: I, min_count: u32, max_count: u32) -> Self {
64        Self::with_chance(item, min_count, max_count, 1.0)
65    }
66
67    /// Creates a drop entry with an explicit probability.
68    pub fn with_chance(item: I, min_count: u32, max_count: u32, chance: f32) -> Self {
69        Self {
70            item,
71            min_count: min_count.min(max_count),
72            max_count: min_count.max(max_count),
73            chance: chance.clamp(0.0, 1.0),
74        }
75    }
76}
77
78/// Mapping from voxel byte IDs to item drop definitions.
79///
80/// Each entry associates a voxel byte value (the `u8` returned by
81/// [`crate::voxel::VoxelType::to_byte`]) with an item type and a drop-count
82/// range `[min, max]`. Runtime entries may also carry a chance, and a voxel may
83/// have multiple entries. When a matching voxel is broken,
84/// `spawn_drops_system` queries this table and selects counts/chance outcomes
85/// using deterministic pseudo-random values seeded from the voxel's world
86/// position. If `min == max` the count is always fixed.
87///
88/// [`DropTable`] is initialized empty; register entries before the first
89/// [`crate::world::VoxelBroken`] message is processed.  It is available as a
90/// Bevy [`Resource`] after [`DropsPlugin`] is added.
91///
92/// # Examples
93///
94/// ```rust,no_run
95/// use voxel_framework::items::{DropTable, DefaultItem};
96///
97/// let mut table = DropTable::<DefaultItem>::new();
98/// // Voxel byte 1 drops 1–3 rock fragments.
99/// table.register(1, DefaultItem::RockFragment, 1, 3);
100/// // Voxel byte 2 always drops exactly 1 iron ore.
101/// table.register(2, DefaultItem::IronOre, 1, 1);
102/// // Voxel byte 3 can produce multiple runtime entries.
103/// table.add_entry(3, voxel_framework::items::DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
104/// table.add_entry(3, voxel_framework::items::DropTableEntry::with_chance(DefaultItem::Coal, 1, 2, 0.25));
105/// ```
106#[derive(Resource, Debug, Clone)]
107pub struct DropTable<I: ItemType> {
108    /// Internal map: `voxel_byte` → runtime drop entries.
109    entries: HashMap<u8, Vec<DropTableEntry<I>>>,
110}
111
112impl<I: ItemType> DropTable<I> {
113    /// Creates an empty drop table.
114    pub fn new() -> Self {
115        Self {
116            entries: HashMap::new(),
117        }
118    }
119
120    /// Registers a drop for the given voxel byte.
121    ///
122    /// When a voxel with `voxel_byte` is broken, between `min` and `max` items
123    /// (inclusive) of `item` will be dropped. If `min == max` the count is
124    /// always fixed.
125    ///
126    /// This replaces any previous runtime entries for the voxel byte, preserving
127    /// the historical one-entry behavior of [`DropTable::register`]. Use
128    /// [`DropTable::add_entry`] when a voxel should produce multiple drops.
129    pub fn register(&mut self, voxel_byte: u8, item: I, min: u32, max: u32) {
130        self.replace_entries(voxel_byte, [DropTableEntry::new(item, min, max)]);
131    }
132
133    /// Registers a single probabilistic drop for the given voxel byte.
134    ///
135    /// Like [`DropTable::register`], this replaces any previous entries for the
136    /// voxel byte.
137    pub fn register_with_chance(
138        &mut self,
139        voxel_byte: u8,
140        item: I,
141        min: u32,
142        max: u32,
143        chance: f32,
144    ) {
145        self.replace_entries(
146            voxel_byte,
147            [DropTableEntry::with_chance(item, min, max, chance)],
148        );
149    }
150
151    /// Appends one runtime entry without removing existing entries for the same
152    /// voxel byte.
153    pub fn add_entry(&mut self, voxel_byte: u8, entry: DropTableEntry<I>) {
154        self.entries.entry(voxel_byte).or_default().push(entry);
155    }
156
157    /// Replaces all runtime entries for one voxel byte.
158    pub fn replace_entries(
159        &mut self,
160        voxel_byte: u8,
161        entries: impl IntoIterator<Item = DropTableEntry<I>>,
162    ) {
163        self.entries
164            .insert(voxel_byte, entries.into_iter().collect());
165    }
166
167    /// Iterates over all explicitly registered drop entries.
168    ///
169    /// Yields `(voxel_byte, item, min_count, max_count)` for each registration.
170    /// Identity-fallback entries (not explicitly registered) are not included.
171    pub fn iter_entries(&self) -> impl Iterator<Item = (u8, I, u32, u32)> + '_ {
172        self.iter_drop_entries()
173            .map(|(voxel_byte, entry)| (voxel_byte, entry.item, entry.min_count, entry.max_count))
174    }
175
176    /// Iterates over all explicitly registered runtime drop entries, including
177    /// chance metadata.
178    pub fn iter_drop_entries(&self) -> impl Iterator<Item = (u8, &DropTableEntry<I>)> + '_ {
179        self.entries
180            .iter()
181            .flat_map(|(&voxel_byte, entries)| entries.iter().map(move |entry| (voxel_byte, entry)))
182    }
183
184    /// Returns the drop for `voxel_byte`, using `seed` for deterministic count
185    /// selection within `[min, max]`.
186    ///
187    /// Explicit registrations always win. If no entry is registered for
188    /// `voxel_byte`, falls back to the identity mapping: `I::from_byte(voxel_byte)`
189    /// with count 1. If the resulting item is the empty sentinel (i.e.
190    /// `item.to_byte() == 0`), returns `None` — meaning no drop.
191    pub fn get_drop(&self, voxel_byte: u8, seed: u64) -> Option<(I, u32)> {
192        self.get_drops(voxel_byte, seed).into_iter().next()
193    }
194
195    /// Returns all drops produced for `voxel_byte` with deterministic chance
196    /// rolls and count selection.
197    pub fn get_drops(&self, voxel_byte: u8, seed: u64) -> Vec<(I, u32)> {
198        if let Some(entries) = self.entries.get(&voxel_byte) {
199            return entries
200                .iter()
201                .enumerate()
202                .filter_map(|(index, entry)| entry.roll(seed, index as u64))
203                .collect();
204        }
205
206        // Identity fallback: try mapping the voxel byte directly to an item.
207        let item = I::from_byte(voxel_byte);
208        if !item.is_empty() {
209            vec![(item, 1)]
210        } else {
211            Vec::new()
212        }
213    }
214}
215
216impl<I: ItemType> DropTableEntry<I> {
217    fn roll(&self, seed: u64, salt: u64) -> Option<(I, u32)> {
218        if self.item.is_empty() || self.max_count == 0 || self.chance <= 0.0 {
219            return None;
220        }
221
222        let chance_roll = unit_interval(seed, salt);
223        if chance_roll > self.chance {
224            return None;
225        }
226
227        let count = if self.min_count == self.max_count {
228            self.min_count
229        } else {
230            let range = (self.max_count - self.min_count + 1) as u64;
231            self.min_count + (lcg(seed, salt.wrapping_add(1)) % range) as u32
232        };
233
234        (count > 0).then_some((self.item, count))
235    }
236}
237
238fn lcg(seed: u64, salt: u64) -> u64 {
239    seed.wrapping_add(salt.wrapping_mul(0x9E37_79B9_7F4A_7C15))
240        .wrapping_mul(6364136223846793005)
241        .wrapping_add(1442695040888963407)
242}
243
244fn unit_interval(seed: u64, salt: u64) -> f32 {
245    let value = lcg(seed, salt) >> 40;
246    value as f32 / ((1u64 << 24) - 1) as f32
247}
248
249impl<I: ItemType> Default for DropTable<I> {
250    fn default() -> Self {
251        Self::new()
252    }
253}
254
255// ─── MagnetConfig ─────────────────────────────────────────────────────────────
256
257/// Configuration for the magnetic item-attraction system.
258///
259/// This resource is inserted by [`DropsPlugin`] with [`Default`] values and
260/// can be overwritten after plugin registration to tune pickup feel.
261///
262/// # Examples
263///
264/// ```rust,no_run
265/// use bevy::prelude::*;
266/// use voxel_framework::items::MagnetConfig;
267///
268/// fn setup(mut config: ResMut<MagnetConfig>) {
269///     config.radius = 8.0;
270///     config.force  = 16.0;
271/// }
272/// ```
273#[derive(Resource, Debug, Clone)]
274pub struct MagnetConfig {
275    /// Distance (in world units) within which [`DroppedItem`] entities are
276    /// attracted toward the [`ItemCollector`].
277    ///
278    /// Items outside this radius are neither attracted nor collected.
279    /// Default: `4.0`.
280    pub radius: f32,
281    /// Acceleration magnitude applied toward the collector each second
282    /// (world units/sec²).
283    ///
284    /// Higher values make items snap to the player faster.  Default: `8.0`.
285    pub force: f32,
286}
287
288impl Default for MagnetConfig {
289    fn default() -> Self {
290        Self {
291            radius: 4.0,
292            force: 8.0,
293        }
294    }
295}
296
297// ─── Components ───────────────────────────────────────────────────────────────
298
299/// Component on a world entity representing an uncollected item drop.
300///
301/// `DroppedItem` entities are spawned by `spawn_drops_system` in response to
302/// [`crate::world::VoxelBroken`] messages and despawned by `magnet_system`
303/// when either collected or expired.
304///
305/// The plugin spawns each drop with a [`Transform`] at the broken voxel's
306/// world-space center, ready for spatial magnet logic. Manually spawned drops
307/// must also provide a [`Transform`] to participate in spatial attraction.
308///
309/// # Lifecycle
310///
311/// 1. Spawned with `velocity` set to `(0, 2, 0)` (small upward bounce).
312/// 2. Attracted toward the [`ItemCollector`] once within [`MagnetConfig::radius`].
313/// 3. Collected when within 0.5 world units of the collector. A full inventory
314///    that accepts no items leaves the drop available until pickup or expiry.
315///    Partial pickups leave the unaccepted remainder in the world.
316/// 4. Despawned after `lifetime` seconds regardless of collection.
317#[derive(Component, Debug, Clone)]
318pub struct DroppedItem<I: ItemType> {
319    /// The item type carried by this drop entity.
320    pub item: I,
321    /// Number of items in this drop stack.  Always `>= 1`.
322    pub count: u32,
323    /// Current velocity in world space (units/sec).
324    ///
325    /// The magnet system accelerates drops inside the attraction radius and
326    /// advances their position by velocity times elapsed time while a collector
327    /// is available. Outside the radius, existing velocity is preserved.
328    /// Game code can modify velocity for custom gravity or bounce; it should
329    /// not integrate the same movement a second time.
330    pub velocity: Vec3,
331    /// Seconds remaining before the entity is automatically despawned.
332    ///
333    /// Decremented each frame.  Default: `60.0`.
334    pub lifetime: f32,
335}
336
337/// Tag component marking the entity that attracts and collects nearby [`DroppedItem`] entities.
338///
339/// Add this component to the player entity after spawning it.  Only one
340/// collector entity is supported; `magnet_system` uses
341/// [`bevy::ecs::query::QuerySingleError`] and silently skips collection if
342/// zero or more than one entity carries this tag.
343///
344/// # Examples
345///
346/// ```rust,no_run
347/// use bevy::prelude::*;
348/// use voxel_framework::items::ItemCollector;
349///
350/// fn spawn_player(mut commands: Commands) {
351///     commands.spawn((Transform::default(), ItemCollector));
352/// }
353/// ```
354#[derive(Component, Default)]
355pub struct ItemCollector;
356
357// ─── Systems ─────────────────────────────────────────────────────────────────
358
359/// Reads [`VoxelBroken`] messages and spawns [`DroppedItem`] entities using
360/// [`DropTable`].
361fn spawn_drops_system<I: ItemType>(
362    mut broken_reader: MessageReader<VoxelBroken>,
363    drop_table: Res<DropTable<I>>,
364    mut commands: Commands,
365) {
366    for event in broken_reader.read() {
367        // Use world position bits as a deterministic seed.
368        let seed = {
369            let x = event.world_pos.x.to_bits() as u64;
370            let y = event.world_pos.y.to_bits() as u64;
371            let z = event.world_pos.z.to_bits() as u64;
372            x.wrapping_mul(1000003)
373                .wrapping_add(y.wrapping_mul(1000033))
374                .wrapping_add(z)
375        };
376
377        for (item, count) in drop_table.get_drops(event.voxel_byte, seed) {
378            commands.spawn((
379                DroppedItem {
380                    item,
381                    count,
382                    velocity: Vec3::new(0.0, 2.0, 0.0),
383                    lifetime: 60.0,
384                },
385                Transform::from_translation(event.world_pos),
386            ));
387        }
388    }
389}
390
391/// Applies magnet force toward [`ItemCollector`] and picks up items within
392/// pickup range, adding them to the [`ContainerComponent`] on the
393/// [`PrimaryContainer`] entity and emitting [`ItemPickedUp`].
394fn magnet_system<I: ItemType>(
395    time: Res<Time>,
396    config: Res<MagnetConfig>,
397    collector_query: Query<&Transform, (With<ItemCollector>, Without<DroppedItem<I>>)>,
398    mut item_query: Query<(Entity, &mut DroppedItem<I>, Option<&mut Transform>)>,
399    mut container_query: Query<&mut ContainerComponent<I>, With<PrimaryContainer>>,
400    mut pickup_writer: MessageWriter<ItemPickedUp<I>>,
401    mut commands: Commands,
402) {
403    let Ok(collector_transform) = collector_query.single() else {
404        return;
405    };
406    let collector_pos = collector_transform.translation;
407    let dt = time.delta_secs();
408
409    for (entity, mut dropped, transform_opt) in item_query.iter_mut() {
410        // Tick lifetime.
411        dropped.lifetime -= dt;
412        if dropped.lifetime <= 0.0 {
413            commands.entity(entity).despawn();
414            continue;
415        }
416
417        // If entity has no transform we can't do spatial logic — skip.
418        let Some(mut transform) = transform_opt else {
419            continue;
420        };
421
422        let item_pos = transform.translation;
423        let diff = collector_pos - item_pos;
424        let dist = diff.length();
425
426        if dist < 0.5 {
427            // Close enough — pick up via PrimaryContainer entity.
428            let Ok(mut container) = container_query.single_mut() else {
429                continue;
430            };
431            let added = dropped.count - container.0.add(dropped.item, dropped.count);
432            if added == 0 {
433                continue;
434            }
435            dropped.count -= added;
436            pickup_writer.write(ItemPickedUp {
437                item: dropped.item,
438                count: added,
439            });
440            if dropped.count == 0 {
441                commands.entity(entity).despawn();
442            }
443            continue;
444        } else if dist < config.radius {
445            // Apply attraction force.
446            let dir = diff / dist;
447            dropped.velocity += dir * config.force * dt;
448        }
449        transform.translation += dropped.velocity * dt;
450    }
451}
452
453// ─── DropsPlugin ─────────────────────────────────────────────────────────────
454
455/// Plugin that wires up the full item-drop pipeline for item type `I`.
456///
457/// Registering this plugin inserts the following resources (with defaults) and
458/// systems into the Bevy [`App`]:
459///
460/// | Resource | Purpose |
461/// |---|---|
462/// | [`DropTable<I>`] | Empty table; populate it in a `Startup` system |
463/// | [`MagnetConfig`] | Tunable attraction radius and force |
464/// | [`crate::items::inventory::Inventory<I>`] | Player's item storage |
465///
466/// It also registers the [`crate::items::inventory::ItemPickedUp<I>`] message
467/// type and adds `spawn_drops_system` and `magnet_system` to the `Update`
468/// schedule.
469///
470/// **This plugin is NOT included in [`crate::VoxelPlugin`]** — because it is
471/// generic over `I: `[`ItemType`], it must be added separately by game code.
472/// Add it alongside [`crate::generator::GeneratorPlugin`]:
473///
474/// ```rust,no_run
475/// use bevy::prelude::*;
476/// use voxel_framework::items::{DefaultItem, DropsPlugin};
477///
478/// App::new().add_plugins(DropsPlugin::<DefaultItem>::new());
479/// ```
480pub struct DropsPlugin<I: ItemType> {
481    _marker: PhantomData<I>,
482}
483
484impl<I: ItemType> DropsPlugin<I> {
485    /// Creates a new `DropsPlugin`.
486    pub fn new() -> Self {
487        Self {
488            _marker: PhantomData,
489        }
490    }
491}
492
493impl<I: ItemType> Default for DropsPlugin<I> {
494    fn default() -> Self {
495        Self::new()
496    }
497}
498
499impl<I: ItemType> Plugin for DropsPlugin<I> {
500    fn build(&self, app: &mut App) {
501        app.init_resource::<DropTable<I>>();
502        app.init_resource::<MagnetConfig>();
503        app.add_message::<ItemPickedUp<I>>();
504        app.add_systems(Update, spawn_drops_system::<I>);
505        app.add_systems(Update, magnet_system::<I>);
506    }
507}
508
509// ─── Tests ───────────────────────────────────────────────────────────────────
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514    use crate::items::DefaultItem;
515
516    #[test]
517    fn broken_voxel_spawns_one_mapped_drop_at_world_position() {
518        let mut app = App::new();
519        app.init_resource::<Time>()
520            .add_message::<VoxelBroken>()
521            .add_plugins(DropsPlugin::<DefaultItem>::new());
522        app.world_mut()
523            .resource_mut::<DropTable<DefaultItem>>()
524            .register(1, DefaultItem::RockFragment, 1, 1);
525        let position = Vec3::new(18.5, -12.5, 36.5);
526        app.world_mut().write_message(VoxelBroken {
527            chunk_coord: IVec3::new(1, -1, 2),
528            local: (2, 3, 4),
529            world_pos: position,
530            voxel_byte: 1,
531        });
532
533        app.update();
534
535        let world = app.world_mut();
536        let mut query = world.query::<(&DroppedItem<DefaultItem>, Option<&Transform>)>();
537        let drops: Vec<_> = query.iter(world).collect();
538        assert_eq!(drops.len(), 1);
539        assert_eq!(drops[0].0.item, DefaultItem::RockFragment);
540        assert_eq!(drops[0].0.count, 1);
541        assert_eq!(
542            drops[0]
543                .1
544                .expect("spawned drop must have a world position")
545                .translation,
546            position
547        );
548    }
549
550    #[test]
551    fn nearby_drop_moves_and_is_collected_once_without_attracting_distant_drop() {
552        let mut app = App::new();
553        app.init_resource::<Time>()
554            .add_message::<VoxelBroken>()
555            .add_plugins(DropsPlugin::<DefaultItem>::new());
556        let player = app
557            .world_mut()
558            .spawn((
559                Transform::default(),
560                ItemCollector,
561                PrimaryContainer,
562                ContainerComponent::<DefaultItem>::new(9),
563            ))
564            .id();
565        let spawn_drop = |world: &mut World, position| {
566            world
567                .spawn((
568                    DroppedItem {
569                        item: DefaultItem::RockFragment,
570                        count: 1,
571                        velocity: Vec3::ZERO,
572                        lifetime: 60.0,
573                    },
574                    Transform::from_translation(position),
575                ))
576                .id()
577        };
578        let nearby = spawn_drop(app.world_mut(), Vec3::new(2.0, 0.0, 0.0));
579        let distant_position = Vec3::new(8.0, 0.0, 0.0);
580        let distant = spawn_drop(app.world_mut(), distant_position);
581        app.world_mut()
582            .resource_mut::<Time>()
583            .advance_by(std::time::Duration::from_millis(100));
584
585        app.update();
586        assert!(
587            app.world()
588                .get::<Transform>(nearby)
589                .unwrap()
590                .translation
591                .length()
592                < 2.0,
593            "nearby drop must move toward the collector"
594        );
595
596        let mut pickups = Vec::new();
597        for _ in 0..30 {
598            app.world_mut()
599                .resource_mut::<Time>()
600                .advance_by(std::time::Duration::from_millis(100));
601            app.update();
602            pickups.extend(
603                app.world_mut()
604                    .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
605                    .drain(),
606            );
607        }
608        assert!(app.world().get_entity(nearby).is_err());
609        assert_eq!(
610            app.world()
611                .get::<ContainerComponent<DefaultItem>>(player)
612                .unwrap()
613                .0
614                .count_of(DefaultItem::RockFragment),
615            1
616        );
617        assert_eq!(pickups.len(), 1);
618        assert_eq!(pickups[0].item, DefaultItem::RockFragment);
619        assert_eq!(pickups[0].count, 1);
620        assert_eq!(
621            app.world().get::<Transform>(distant).unwrap().translation,
622            distant_position
623        );
624        assert_eq!(
625            app.world()
626                .get::<DroppedItem<DefaultItem>>(distant)
627                .unwrap()
628                .velocity,
629            Vec3::ZERO
630        );
631    }
632
633    #[test]
634    fn partial_pickup_retains_remainder_until_inventory_has_room() {
635        let mut app = App::new();
636        app.init_resource::<Time>()
637            .add_message::<VoxelBroken>()
638            .add_plugins(DropsPlugin::<DefaultItem>::new());
639        let item = DefaultItem::RockFragment;
640        let mut container = ContainerComponent::<DefaultItem>::new(1);
641        assert_eq!(container.0.add(item, u32::MAX - 1), 0);
642        let player = app
643            .world_mut()
644            .spawn((
645                Transform::default(),
646                ItemCollector,
647                PrimaryContainer,
648                container,
649            ))
650            .id();
651        let drop = app
652            .world_mut()
653            .spawn((
654                DroppedItem {
655                    item,
656                    count: 3,
657                    velocity: Vec3::ZERO,
658                    lifetime: 60.0,
659                },
660                Transform::from_xyz(0.25, 0.0, 0.0),
661            ))
662            .id();
663
664        for expected_pickup in [1, 0, 2] {
665            if expected_pickup == 2 {
666                assert_eq!(
667                    app.world_mut()
668                        .get_mut::<ContainerComponent<DefaultItem>>(player)
669                        .unwrap()
670                        .0
671                        .remove(item, 2),
672                    2
673                );
674            }
675            app.update();
676            assert_eq!(
677                app.world()
678                    .get::<ContainerComponent<DefaultItem>>(player)
679                    .unwrap()
680                    .0
681                    .count_of(item),
682                u32::MAX
683            );
684            if expected_pickup == 2 {
685                assert!(app.world().get_entity(drop).is_err());
686            } else {
687                let retained = app
688                    .world()
689                    .get::<DroppedItem<DefaultItem>>(drop)
690                    .expect("partial pickup must preserve the remainder");
691                assert_eq!(retained.item, item);
692                assert_eq!(retained.count, 2);
693            }
694            let pickups: Vec<_> = app
695                .world_mut()
696                .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
697                .drain()
698                .collect();
699            if expected_pickup == 0 {
700                assert!(pickups.is_empty());
701            } else {
702                assert_eq!(pickups.len(), 1);
703                assert_eq!(pickups[0].item, item);
704                assert_eq!(pickups[0].count, expected_pickup);
705            }
706        }
707    }
708
709    #[test]
710    fn full_inventory_retains_drop_without_reporting_pickup() {
711        let mut app = App::new();
712        app.init_resource::<Time>()
713            .add_message::<VoxelBroken>()
714            .add_plugins(DropsPlugin::<DefaultItem>::new());
715        let mut container = ContainerComponent::<DefaultItem>::new(1);
716        assert_eq!(container.0.add(DefaultItem::IronOre, 1), 0);
717        let player = app
718            .world_mut()
719            .spawn((
720                Transform::default(),
721                ItemCollector,
722                PrimaryContainer,
723                container,
724            ))
725            .id();
726        let drop = app
727            .world_mut()
728            .spawn((
729                DroppedItem {
730                    item: DefaultItem::RockFragment,
731                    count: 3,
732                    velocity: Vec3::ZERO,
733                    lifetime: 60.0,
734                },
735                Transform::from_xyz(0.25, 0.0, 0.0),
736            ))
737            .id();
738
739        for _ in 0..3 {
740            app.world_mut()
741                .resource_mut::<Time>()
742                .advance_by(std::time::Duration::from_millis(100));
743            app.update();
744            let retained = app
745                .world()
746                .get::<DroppedItem<DefaultItem>>(drop)
747                .expect("full inventory must retain the unaccepted drop");
748            assert_eq!(retained.item, DefaultItem::RockFragment);
749            assert_eq!(retained.count, 3);
750            let inventory = &app
751                .world()
752                .get::<ContainerComponent<DefaultItem>>(player)
753                .unwrap()
754                .0;
755            assert_eq!(inventory.count_of(DefaultItem::IronOre), 1);
756            assert_eq!(inventory.count_of(DefaultItem::RockFragment), 0);
757            assert_eq!(
758                app.world_mut()
759                    .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
760                    .drain()
761                    .count(),
762                0
763            );
764        }
765    }
766
767    #[test]
768    fn test_drop_table_get_drop() {
769        let mut table = DropTable::<DefaultItem>::new();
770        table.register(1, DefaultItem::RockFragment, 1, 3);
771
772        // With seed 0: deterministic count should be in [1, 3].
773        let result = table.get_drop(1, 0);
774        assert!(result.is_some());
775        let (item, count) = result.unwrap();
776        assert_eq!(item, DefaultItem::RockFragment);
777        assert!((1..=3).contains(&count));
778    }
779
780    #[test]
781    fn test_drop_table_no_entry_returns_none() {
782        let table = DropTable::<DefaultItem>::new();
783        assert!(table.get_drop(99, 42).is_none());
784    }
785
786    #[test]
787    fn test_drop_table_fixed_count() {
788        let mut table = DropTable::<DefaultItem>::new();
789        table.register(2, DefaultItem::IronOre, 5, 5);
790        let (_, count) = table.get_drop(2, 12345).unwrap();
791        assert_eq!(count, 5);
792    }
793
794    #[test]
795    fn test_drop_table_identity_fallback_with_other_entries() {
796        let mut table = DropTable::<DefaultItem>::new();
797        table.register(2, DefaultItem::Dirt, 1, 1);
798        let (item, count) = table.get_drop(11, 0).unwrap();
799        assert_eq!(item, DefaultItem::IronOre);
800        assert_eq!(count, 1);
801    }
802
803    #[test]
804    fn drop_table_supports_multiple_runtime_entries() {
805        let mut table = DropTable::<DefaultItem>::new();
806        table.add_entry(3, DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
807        table.add_entry(3, DropTableEntry::new(DefaultItem::Coal, 2, 2));
808
809        let drops = table.get_drops(3, 123);
810        assert_eq!(drops.len(), 2);
811        assert_eq!(drops[0], (DefaultItem::Cobblestone, 1));
812        assert_eq!(drops[1], (DefaultItem::Coal, 2));
813    }
814
815    #[test]
816    fn register_preserves_single_entry_replacement_behavior() {
817        let mut table = DropTable::<DefaultItem>::new();
818        table.add_entry(3, DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
819        table.add_entry(3, DropTableEntry::new(DefaultItem::Coal, 1, 1));
820
821        table.register(3, DefaultItem::IronOre, 1, 1);
822
823        let drops = table.get_drops(3, 0);
824        assert_eq!(drops, vec![(DefaultItem::IronOre, 1)]);
825    }
826
827    #[test]
828    fn drop_table_entry_chance_can_disable_a_drop() {
829        let mut table = DropTable::<DefaultItem>::new();
830        table.add_entry(
831            3,
832            DropTableEntry::with_chance(DefaultItem::Cobblestone, 1, 1, 0.0),
833        );
834        table.add_entry(3, DropTableEntry::with_chance(DefaultItem::Coal, 1, 1, 1.0));
835
836        let drops = table.get_drops(3, 0);
837        assert_eq!(drops, vec![(DefaultItem::Coal, 1)]);
838    }
839
840    #[test]
841    fn iter_drop_entries_includes_chance_metadata() {
842        let mut table = DropTable::<DefaultItem>::new();
843        table.register_with_chance(3, DefaultItem::Cobblestone, 1, 2, 0.25);
844
845        let entries: Vec<_> = table.iter_drop_entries().collect();
846        assert_eq!(entries.len(), 1);
847        assert_eq!(entries[0].0, 3);
848        assert_eq!(entries[0].1.item, DefaultItem::Cobblestone);
849        assert_eq!(entries[0].1.min_count, 1);
850        assert_eq!(entries[0].1.max_count, 2);
851        assert_eq!(entries[0].1.chance, 0.25);
852    }
853}