use crate::entity::EntityId;
use std::any::TypeId;
#[derive(Clone, Debug)]
pub enum EntityEvent {
Spawned(EntityId),
Despawned(EntityId),
ComponentAdded(EntityId, TypeId),
ComponentRemoved(EntityId, TypeId),
Custom(String, EntityId, Vec<u8>),
}
impl EntityEvent {
pub fn entity_id(&self) -> EntityId {
match self {
EntityEvent::Spawned(id) => *id,
EntityEvent::Despawned(id) => *id,
EntityEvent::ComponentAdded(id, _) => *id,
EntityEvent::ComponentRemoved(id, _) => *id,
EntityEvent::Custom(_, id, _) => *id,
}
}
pub fn event_type(&self) -> &str {
match self {
EntityEvent::Spawned(_) => "Spawned",
EntityEvent::Despawned(_) => "Despawned",
EntityEvent::ComponentAdded(_, _) => "ComponentAdded",
EntityEvent::ComponentRemoved(_, _) => "ComponentRemoved",
EntityEvent::Custom(name, _, _) => name,
}
}
}
pub struct EventQueue {
events: std::collections::VecDeque<EntityEvent>,
capacity: usize,
}
impl EventQueue {
pub fn new() -> Self {
Self {
events: std::collections::VecDeque::new(),
capacity: 1024,
}
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
events: std::collections::VecDeque::with_capacity(capacity),
capacity,
}
}
pub fn push(&mut self, event: EntityEvent) {
if self.events.len() < self.capacity {
self.events.push_back(event);
} else {
eprintln!("Event queue overflow! Capacity: {}", self.capacity);
}
}
pub fn pop(&mut self) -> Option<EntityEvent> {
self.events.pop_front()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn clear(&mut self) {
self.events.clear();
}
pub fn len(&self) -> usize {
self.events.len()
}
}
impl Default for EventQueue {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::world::World;
#[derive(Clone, Copy, Debug)]
struct TestComponent;
#[test]
fn test_event_queue_push_pop() {
let mut queue = EventQueue::new();
let mut world = World::new();
let id = world.spawn_entity((TestComponent,));
queue.push(EntityEvent::Spawned(id));
assert!(!queue.is_empty());
let event = queue.pop();
assert!(event.is_some());
assert!(queue.is_empty());
}
#[test]
fn test_event_entity_id() {
let mut world = World::new();
let id = world.spawn_entity((TestComponent,));
let event = EntityEvent::Spawned(id);
assert_eq!(event.entity_id(), id);
}
}