use std::collections::HashMap;
use std::marker::PhantomData;
use bevy::prelude::*;
use crate::world::VoxelBroken;
use super::inventory::{ContainerComponent, ItemPickedUp, ItemType, PrimaryContainer};
#[derive(Resource, Debug, Clone)]
pub struct DropTable<I: ItemType> {
entries: HashMap<u8, (I, u32, u32)>,
}
impl<I: ItemType> DropTable<I> {
pub fn new() -> Self {
Self {
entries: HashMap::new(),
}
}
pub fn register(&mut self, voxel_byte: u8, item: I, min: u32, max: u32) {
self.entries.insert(voxel_byte, (item, min, max));
}
pub fn iter_entries(&self) -> impl Iterator<Item = (u8, I, u32, u32)> + '_ {
self.entries
.iter()
.map(|(&voxel_byte, &(item, min, max))| (voxel_byte, item, min, max))
}
pub fn get_drop(&self, voxel_byte: u8, seed: u64) -> Option<(I, u32)> {
if let Some(&(item, min, max)) = self.entries.get(&voxel_byte) {
let count = if min == max {
min
} else {
let range = (max - min + 1) as u64;
min + (seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407)
% range) as u32
};
return Some((item, count));
}
let item = I::from_byte(voxel_byte);
if item.to_byte() != 0 {
Some((item, 1))
} else {
None
}
}
}
impl<I: ItemType> Default for DropTable<I> {
fn default() -> Self {
Self::new()
}
}
#[derive(Resource, Debug, Clone)]
pub struct MagnetConfig {
pub radius: f32,
pub force: f32,
}
impl Default for MagnetConfig {
fn default() -> Self {
Self {
radius: 4.0,
force: 8.0,
}
}
}
#[derive(Component, Debug, Clone)]
pub struct DroppedItem<I: ItemType> {
pub item: I,
pub count: u32,
pub velocity: Vec3,
pub lifetime: f32,
}
#[derive(Component, Default)]
pub struct ItemCollector;
fn spawn_drops_system<I: ItemType>(
mut broken_reader: MessageReader<VoxelBroken>,
drop_table: Res<DropTable<I>>,
mut commands: Commands,
) {
for event in broken_reader.read() {
let seed = {
let x = event.world_pos.x.to_bits() as u64;
let y = event.world_pos.y.to_bits() as u64;
let z = event.world_pos.z.to_bits() as u64;
x.wrapping_mul(1000003)
.wrapping_add(y.wrapping_mul(1000033))
.wrapping_add(z)
};
let voxel_byte = derive_voxel_byte(event);
if let Some((item, count)) = drop_table.get_drop(voxel_byte, seed) {
commands.spawn(DroppedItem {
item,
count,
velocity: Vec3::new(0.0, 2.0, 0.0),
lifetime: 60.0,
});
}
}
}
fn derive_voxel_byte(event: &VoxelBroken) -> u8 {
let (x, y, z) = event.local;
((x as u32)
.wrapping_mul(73856093)
.wrapping_add((y as u32).wrapping_mul(19349663))
.wrapping_add((z as u32).wrapping_mul(83492791))
& 0xFF) as u8
}
fn magnet_system<I: ItemType>(
time: Res<Time>,
config: Res<MagnetConfig>,
collector_query: Query<&Transform, With<ItemCollector>>,
mut item_query: Query<(Entity, &mut DroppedItem<I>, Option<&Transform>)>,
mut container_query: Query<&mut ContainerComponent<I>, With<PrimaryContainer>>,
mut pickup_writer: MessageWriter<ItemPickedUp<I>>,
mut commands: Commands,
) {
let Ok(collector_transform) = collector_query.single() else {
return;
};
let collector_pos = collector_transform.translation;
let dt = time.delta_secs();
for (entity, mut dropped, transform_opt) in item_query.iter_mut() {
dropped.lifetime -= dt;
if dropped.lifetime <= 0.0 {
commands.entity(entity).despawn();
continue;
}
let Some(transform) = transform_opt else {
continue;
};
let item_pos = transform.translation;
let diff = collector_pos - item_pos;
let dist = diff.length();
if dist < 0.5 {
let Ok(mut container) = container_query.single_mut() else {
continue;
};
let added = dropped.count - container.0.add(dropped.item, dropped.count);
if added > 0 {
pickup_writer.write(ItemPickedUp {
item: dropped.item,
count: added,
});
}
commands.entity(entity).despawn();
} else if dist < config.radius {
let dir = diff / dist;
dropped.velocity += dir * config.force * dt;
}
}
}
pub struct DropsPlugin<I: ItemType> {
_marker: PhantomData<I>,
}
impl<I: ItemType> DropsPlugin<I> {
pub fn new() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<I: ItemType> Default for DropsPlugin<I> {
fn default() -> Self {
Self::new()
}
}
impl<I: ItemType> Plugin for DropsPlugin<I> {
fn build(&self, app: &mut App) {
app.init_resource::<DropTable<I>>();
app.init_resource::<MagnetConfig>();
app.add_message::<ItemPickedUp<I>>();
app.add_systems(Update, spawn_drops_system::<I>);
app.add_systems(Update, magnet_system::<I>);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::items::DefaultItem;
#[test]
fn test_drop_table_get_drop() {
let mut table = DropTable::<DefaultItem>::new();
table.register(1, DefaultItem::RockFragment, 1, 3);
let result = table.get_drop(1, 0);
assert!(result.is_some());
let (item, count) = result.unwrap();
assert_eq!(item, DefaultItem::RockFragment);
assert!((1..=3).contains(&count));
}
#[test]
fn test_drop_table_no_entry_returns_none() {
let table = DropTable::<DefaultItem>::new();
assert!(table.get_drop(99, 42).is_none());
}
#[test]
fn test_drop_table_fixed_count() {
let mut table = DropTable::<DefaultItem>::new();
table.register(2, DefaultItem::IronOre, 5, 5);
let (_, count) = table.get_drop(2, 12345).unwrap();
assert_eq!(count, 5);
}
#[test]
fn test_drop_table_identity_fallback_with_other_entries() {
let mut table = DropTable::<DefaultItem>::new();
table.register(2, DefaultItem::Dirt, 1, 1);
let (item, count) = table.get_drop(11, 0).unwrap();
assert_eq!(item, DefaultItem::IronOre);
assert_eq!(count, 1);
}
}