veloren/common/src/event.rs
2019-08-07 16:39:16 +01:00

43 lines
909 B
Rust

use specs::Entity as EcsEntity;
use std::{collections::VecDeque, ops::DerefMut, sync::Mutex};
use vek::*;
pub enum Event {
LandOnGround { entity: EcsEntity, vel: Vec3<f32> },
}
#[derive(Default)]
pub struct EventBus {
queue: Mutex<VecDeque<Event>>,
}
impl EventBus {
pub fn emitter(&self) -> Emitter {
Emitter {
bus: self,
events: VecDeque::new(),
}
}
pub fn recv_all(&self) -> impl ExactSizeIterator<Item = Event> {
std::mem::replace(self.queue.lock().unwrap().deref_mut(), VecDeque::new()).into_iter()
}
}
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) {
self.bus.queue.lock().unwrap().append(&mut self.events);
}
}