veloren/common/src/event.rs

49 lines
1.0 KiB
Rust
Raw Normal View History

2019-08-15 22:19:54 +00:00
use parking_lot::Mutex;
2019-08-07 15:39:16 +00:00
use specs::Entity as EcsEntity;
2019-08-15 22:19:54 +00:00
use std::{collections::VecDeque, ops::DerefMut};
2019-08-07 15:39:16 +00:00
use vek::*;
pub enum Event {
LandOnGround { entity: EcsEntity, vel: Vec3<f32> },
2019-08-07 17:17:04 +00:00
Explosion { pos: Vec3<f32>, radius: f32 },
2019-08-07 15:39:16 +00:00
}
#[derive(Default)]
pub struct EventBus {
queue: Mutex<VecDeque<Event>>,
}
impl EventBus {
pub fn emitter(&self) -> Emitter {
Emitter {
bus: self,
events: VecDeque::new(),
}
}
2019-08-07 17:17:04 +00:00
pub fn emit(&self, event: Event) {
2019-08-15 22:19:54 +00:00
self.queue.lock().push_front(event);
2019-08-07 17:17:04 +00:00
}
2019-08-07 15:39:16 +00:00
pub fn recv_all(&self) -> impl ExactSizeIterator<Item = Event> {
2019-08-15 22:19:54 +00:00
std::mem::replace(self.queue.lock().deref_mut(), VecDeque::new()).into_iter()
2019-08-07 15:39:16 +00:00
}
}
pub struct Emitter<'a> {
bus: &'a EventBus,
events: VecDeque<Event>,
}
impl<'a> Emitter<'a> {
pub fn emit(&mut self, event: Event) {
self.events.push_front(event);
}
}
impl<'a> Drop for Emitter<'a> {
fn drop(&mut self) {
2019-08-15 22:19:54 +00:00
self.bus.queue.lock().append(&mut self.events);
2019-08-07 15:39:16 +00:00
}
}