diff --git a/src/client.rs b/src/client.rs index a014ab8..cbec75f 100644 --- a/src/client.rs +++ b/src/client.rs @@ -23,9 +23,9 @@ struct HandlerManager(Arc>); /// A [Connection] to a remote server. #[derive(Resource)] -pub struct Connection(tcp::Connection); +pub struct ServerConnection(tcp::Connection); -impl Connection { +impl ServerConnection { /// Connects to a remote server. pub fn connect(addr: A) -> io::Result { Ok(Self(tcp::Connection::connect(addr)?)) @@ -42,7 +42,7 @@ impl Connection { #[cfg(feature = "sync")] /// An event that comes from the server. #[derive(Deref)] -pub struct PacketEvent { +pub struct FromServer { /// The event. pub event: E, } @@ -50,18 +50,18 @@ pub struct PacketEvent { #[cfg(feature = "sync")] /// Mark an [Entity] as synced by the server. #[derive(Component)] -pub struct Synced(Entity); +pub struct ServerEntity(Entity); /// A plugin that manage the network [Connection]s. -pub struct NetworkPlugin; +pub struct ClientPlugin; -impl NetworkPlugin { +impl ClientPlugin { #[cfg(feature = "client")] /// Handles a received [Packet] on the server. pub fn handle_packets(world: &mut World) { // Get all received packets let mut packets = Vec::new(); - if let Some(connection) = world.get_resource::() { + if let Some(connection) = world.get_resource::() { while let Some(mut packet) = connection.0.recv() { if packet.len() < 8 { println!("Invalid packet received: {:?}", packet); @@ -88,24 +88,24 @@ impl NetworkPlugin { #[cfg(feature = "client")] /// Remove [Connection] if it's disconnected. - pub fn remove_disconnected(mut commands: Commands, connection: Option>) { + pub fn remove_disconnected(mut commands: Commands, connection: Option>) { if let Some(connection) = connection { if connection.0.closed() { - commands.remove_resource::(); + commands.remove_resource::(); } } } #[cfg(feature = "sync")] /// Removes [ServerEntity] when disconnected. - fn remove_synced(mut commands: Commands, entities: Query>) { + fn remove_synced(mut commands: Commands, entities: Query>) { for entity in entities.iter() { commands.entity(entity).despawn(); } } } -impl Plugin for NetworkPlugin { +impl Plugin for ClientPlugin { fn build(&self, app: &mut App) { app.insert_resource(HandlerManager(Arc::new(HashMap::new()))); app.add_system(Self::handle_packets); @@ -117,19 +117,19 @@ impl Plugin for NetworkPlugin { match bincode::deserialize::(&data) { Ok(entity) => { if let Some((local_entity, _)) = world - .query::<(Entity, &Synced)>() + .query::<(Entity, &ServerEntity)>() .iter(world) .find(|(_, server_entity)| server_entity.0 == entity) { world.despawn(local_entity); } else { - world.spawn(Synced(entity)); + world.spawn(ServerEntity(entity)); } } Err(_) => println!("Failed to deserialize packet: {}", type_name::()), } }); - app.add_system(Self::remove_synced.run_if(resource_removed::())); + app.add_system(Self::remove_synced.run_if(resource_removed::())); } } } @@ -162,9 +162,9 @@ impl NetworkExt for App { #[cfg(feature = "sync")] fn sync_server_event(&mut self) -> &mut Self { - self.add_event::>() + self.add_event::>() .add_packet_handler::(|data, world| match bincode::deserialize::(&data) { - Ok(event) => world.send_event(PacketEvent { event }), + Ok(event) => world.send_event(FromServer { event }), Err(_) => println!("Failed to deserialize packet: {}", type_name::()), }) } @@ -172,7 +172,7 @@ impl NetworkExt for App { #[cfg(feature = "sync")] fn sync_client_event(&mut self) -> &mut Self { self.add_event::().add_system( - |mut events: EventReader, connection: Option>| { + |mut events: EventReader, connection: Option>| { if let Some(connection) = connection { for event in events.iter() { connection.send(event); @@ -188,7 +188,7 @@ impl NetworkExt for App { match bincode::deserialize::<(Entity, C)>(&data) { Ok((entity, component)) => { if let Some((local_entity, _)) = world - .query::<(Entity, &Synced)>() + .query::<(Entity, &ServerEntity)>() .iter(world) .find(|(_, server_entity)| server_entity.0 == entity) { @@ -213,7 +213,7 @@ impl NetworkExt for App { |data, world| match bincode::deserialize::<(Entity, PhantomData)>(&data) { Ok((entity, _)) => { if let Some((local_entity, _)) = world - .query::<(Entity, &Synced)>() + .query::<(Entity, &ServerEntity)>() .iter(world) .find(|(_, server_entity)| server_entity.0 == entity) { diff --git a/src/server.rs b/src/server.rs index e6d3d05..381227a 100644 --- a/src/server.rs +++ b/src/server.rs @@ -10,11 +10,14 @@ use ::{ /// A trait for a handler function. pub trait PacketHandlerFn: - Fn(Entity, Connection, Vec, &mut World) + Send + Sync + 'static + Fn(Entity, ClientConnection, Vec, &mut World) + Send + Sync + 'static { } -impl, &mut World) + Send + Sync + 'static> PacketHandlerFn for T {} +impl, &mut World) + Send + Sync + 'static> PacketHandlerFn + for T +{ +} /// A function that handle a received [Packet]s. type PacketHandler = Box; @@ -36,9 +39,9 @@ impl Listener { /// A [Connection] to a remote client. #[derive(Component)] -pub struct Connection(Arc); +pub struct ClientConnection(Arc); -impl Connection { +impl ClientConnection { /// Sends a packet through this connection. pub fn send(&self, packet: &P) { let mut data = bincode::serialize(packet).expect("Failed to serialize packet"); @@ -49,19 +52,19 @@ impl Connection { #[cfg(feature = "sync")] /// An event that comes from a client. -pub struct PacketEvent { +pub struct FromClient { /// The entity of the [Connection] that sent the event. pub entity: Entity, /// The [Connection] that sent the event. - pub connection: Connection, + pub connection: ClientConnection, /// The event. pub event: E, } #[cfg(feature = "sync")] -impl Deref for PacketEvent { +impl Deref for FromClient { type Target = E; fn deref(&self) -> &Self::Target { @@ -75,14 +78,14 @@ impl Deref for PacketEvent { pub struct Synced; /// A plugin that manage the network [Connection]s. -pub struct NetworkPlugin; +pub struct ServerPlugin; -impl NetworkPlugin { +impl ServerPlugin { /// Accept new [Connection]s. fn accept_connections(mut commands: Commands, listener: Option>) { if let Some(listener) = listener { if let Some(connection) = listener.0.accept() { - commands.spawn(Connection(Arc::new(connection))); + commands.spawn(ClientConnection(Arc::new(connection))); } } } @@ -91,7 +94,7 @@ impl NetworkPlugin { fn handle_packets(world: &mut World) { // Get all received packets let mut packets = Vec::new(); - for (entity, connection) in world.query::<(Entity, &Connection)>().iter(world) { + for (entity, connection) in world.query::<(Entity, &ClientConnection)>().iter(world) { while let Some(mut packet) = connection.0.recv() { if packet.len() < 8 { println!("Invalid packet received: {:?}", packet); @@ -100,7 +103,7 @@ impl NetworkPlugin { let packet_id = u64::from_be_bytes(id_buffer.try_into().unwrap()); packets.push(( entity, - Connection(Arc::clone(&connection.0)), + ClientConnection(Arc::clone(&connection.0)), packet_id, packet, )); @@ -120,17 +123,23 @@ impl NetworkPlugin { } /// Remove disconnected [Connection]s. - fn remove_disconnected(mut commands: Commands, connections: Query<(Entity, &Connection)>) { + fn remove_disconnected( + mut commands: Commands, + connections: Query<(Entity, &ClientConnection)>, + ) { for (entity, connection) in connections.iter() { if connection.0.closed() { - commands.entity(entity).remove::(); + commands.entity(entity).remove::(); } } } #[cfg(feature = "sync")] /// Send to clients the [Synced] entity that has been added to the server. - fn send_added(added_entities: Query>, connections: Query<&Connection>) { + fn send_added( + added_entities: Query>, + connections: Query<&ClientConnection>, + ) { for entity in added_entities.iter() { for connection in connections.iter() { connection.send(&entity); @@ -142,7 +151,7 @@ impl NetworkPlugin { /// Send [Synced] entities to new clients. fn send_synced( synced_entities: Query>, - new_connections: Query<&Connection, Added>, + new_connections: Query<&ClientConnection, Added>, ) { for entity in synced_entities.iter() { for connection in new_connections.iter() { @@ -155,7 +164,7 @@ impl NetworkPlugin { /// Send to clients the [Synced] entity that has been removed. fn send_removed( mut removed_entities: RemovedComponents, - connections: Query<&Connection>, + connections: Query<&ClientConnection>, ) { for entity in removed_entities.iter() { for connection in connections.iter() { @@ -165,7 +174,7 @@ impl NetworkPlugin { } } -impl Plugin for NetworkPlugin { +impl Plugin for ServerPlugin { fn build(&self, app: &mut App) { app.insert_resource(HandlerManager(Arc::new(HashMap::new()))); app.add_system(Self::handle_packets); @@ -210,7 +219,7 @@ impl NetworkExt for App { #[cfg(feature = "sync")] fn sync_server_event(&mut self) -> &mut Self { self.add_event::().add_system( - |mut events: EventReader, connections: Query<&Connection>| { + |mut events: EventReader, connections: Query<&ClientConnection>| { for event in events.iter() { for connection in connections.iter() { connection.send(event); @@ -222,10 +231,10 @@ impl NetworkExt for App { #[cfg(feature = "sync")] fn sync_client_event(&mut self) -> &mut Self { - self.add_event::>() + self.add_event::>() .add_packet_handler::( |entity, connection, data, world| match bincode::deserialize::(&data) { - Ok(event) => world.send_event(PacketEvent { + Ok(event) => world.send_event(FromClient { entity, connection, event, @@ -239,7 +248,7 @@ impl NetworkExt for App { fn sync_component(&mut self) -> &mut Self { let update_components = |changed_components: Query<(Entity, &C), (Changed, With)>, - connections: Query<&Connection>| { + connections: Query<&ClientConnection>| { for (entity, component) in changed_components.iter() { for connection in connections.iter() { connection.send(&(entity, component.clone())); @@ -248,26 +257,27 @@ impl NetworkExt for App { }; let send_components = |components: Query<(Entity, &C), With>, - new_connections: Query<&Connection, Added>| { + new_connections: Query<&ClientConnection, Added>| { for (entity, component) in components.iter() { for connection in new_connections.iter() { connection.send(&(entity, component.clone())); } } }; - let remove_components = |mut removed_components: RemovedComponents, - synced_entities: Query>, - connections: Query<&Connection>| { - for entity in removed_components.iter() { - if synced_entities.contains(entity) { - for connection in connections.iter() { - connection.send(&(entity, PhantomData::)); + let remove_components = + |mut removed_components: RemovedComponents, + synced_entities: Query>, + connections: Query<&ClientConnection>| { + for entity in removed_components.iter() { + if synced_entities.contains(entity) { + for connection in connections.iter() { + connection.send(&(entity, PhantomData::)); + } } } - } - }; - self.add_system(update_components.after(NetworkPlugin::send_added)) - .add_system(send_components.after(NetworkPlugin::send_synced)) + }; + self.add_system(update_components.after(ServerPlugin::send_added)) + .add_system(send_components.after(ServerPlugin::send_synced)) .add_system(remove_components.after(update_components)) } }