2019-04-10 23:16:29 +00:00
|
|
|
use std::collections::HashMap;
|
2019-03-03 22:02:38 +00:00
|
|
|
use specs::Entity as EcsEntity;
|
|
|
|
use common::{
|
2019-03-04 22:05:37 +00:00
|
|
|
comp,
|
2019-04-19 19:32:47 +00:00
|
|
|
msg::{ServerMsg, ClientMsg, ClientState},
|
2019-03-03 22:02:38 +00:00
|
|
|
net::PostBox,
|
|
|
|
};
|
2019-03-04 19:50:26 +00:00
|
|
|
use crate::Error;
|
2019-03-03 22:02:38 +00:00
|
|
|
|
|
|
|
pub struct Client {
|
2019-04-19 19:32:47 +00:00
|
|
|
pub client_state: ClientState,
|
2019-03-03 22:02:38 +00:00
|
|
|
pub postbox: PostBox<ServerMsg, ClientMsg>,
|
|
|
|
pub last_ping: f64,
|
|
|
|
}
|
2019-03-04 19:50:26 +00:00
|
|
|
|
2019-04-10 17:23:27 +00:00
|
|
|
impl Client {
|
|
|
|
pub fn notify(&mut self, msg: ServerMsg) {
|
2019-04-11 22:26:43 +00:00
|
|
|
self.postbox.send_message(msg);
|
2019-04-10 17:23:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-04 19:50:26 +00:00
|
|
|
pub struct Clients {
|
2019-04-10 23:16:29 +00:00
|
|
|
clients: HashMap<EcsEntity, Client>,
|
2019-03-04 19:50:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Clients {
|
|
|
|
pub fn empty() -> Self {
|
|
|
|
Self {
|
2019-04-10 23:16:29 +00:00
|
|
|
clients: HashMap::new(),
|
2019-03-04 19:50:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-10 23:16:29 +00:00
|
|
|
pub fn add(&mut self, entity: EcsEntity, client: Client) {
|
|
|
|
self.clients.insert(entity, client);
|
2019-03-04 19:50:26 +00:00
|
|
|
}
|
|
|
|
|
2019-04-10 23:16:29 +00:00
|
|
|
pub fn remove_if<F: FnMut(EcsEntity, &mut Client) -> bool>(&mut self, mut f: F) {
|
|
|
|
self.clients.retain(|entity, client| !f(*entity, client));
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn notify(&mut self, entity: EcsEntity, msg: ServerMsg) {
|
|
|
|
if let Some(client) = self.clients.get_mut(&entity) {
|
|
|
|
client.notify(msg);
|
|
|
|
}
|
2019-03-04 19:50:26 +00:00
|
|
|
}
|
|
|
|
|
2019-04-10 17:23:27 +00:00
|
|
|
pub fn notify_connected(&mut self, msg: ServerMsg) {
|
2019-04-10 23:16:29 +00:00
|
|
|
for client in self.clients.values_mut() {
|
2019-04-19 19:32:47 +00:00
|
|
|
if client.client_state != ClientState::Disconnected {
|
2019-04-10 23:16:29 +00:00
|
|
|
client.notify(msg.clone());
|
2019-04-10 17:23:27 +00:00
|
|
|
}
|
2019-03-04 19:50:26 +00:00
|
|
|
}
|
|
|
|
}
|
2019-03-04 22:05:37 +00:00
|
|
|
|
2019-04-10 23:16:29 +00:00
|
|
|
pub fn notify_connected_except(&mut self, except_entity: EcsEntity, msg: ServerMsg) {
|
|
|
|
for (entity, client) in self.clients.iter_mut() {
|
2019-04-19 19:32:47 +00:00
|
|
|
if client.client_state != ClientState::Disconnected && *entity != except_entity {
|
2019-04-10 23:16:29 +00:00
|
|
|
client.notify(msg.clone());
|
2019-03-04 22:05:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-03-04 19:50:26 +00:00
|
|
|
}
|