Convert distribution to observers
And only distribute your own components
This commit is contained in:
parent
1ba4b96863
commit
af11fa97fb
1 changed files with 29 additions and 10 deletions
|
|
@ -2,32 +2,51 @@ use bevy::prelude::*;
|
|||
|
||||
use super::{
|
||||
packet::{InboundPacket, OutboundPacket, Packet},
|
||||
peer::{Peer, PeerID},
|
||||
peer::PeerID,
|
||||
};
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct PeerOwned;
|
||||
|
||||
fn spawner<T: TryFrom<Vec<u8>> + Component>(
|
||||
mut inbound: MessageReader<InboundPacket>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for InboundPacket(packet) in inbound.read() {
|
||||
if let Ok(entity) = T::try_from(packet.message.clone()) {
|
||||
commands.spawn(entity);
|
||||
if let Ok(component) = T::try_from(packet.message.clone()) {
|
||||
commands.spawn((component, PeerOwned));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sender<T: Into<Vec<u8>> + Component + Clone>(
|
||||
peers: Query<&PeerID, Added<Peer>>,
|
||||
entities: Query<&T>,
|
||||
fn new_peer<T: Into<Vec<u8>> + Component + Clone>(
|
||||
add: On<Add, PeerID>,
|
||||
peers: Query<&PeerID>,
|
||||
components: Query<&T, Without<PeerOwned>>,
|
||||
mut outbound: MessageWriter<OutboundPacket>,
|
||||
) -> Result {
|
||||
let peer = peers.get(add.entity)?;
|
||||
for component in components {
|
||||
outbound.write(Packet::create(component.clone().into(), peer.id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_entity<T: Into<Vec<u8>> + Component + Clone>(
|
||||
add: On<Add, T>,
|
||||
peers: Query<&PeerID>,
|
||||
components: Query<&T, Without<PeerOwned>>,
|
||||
mut outbound: MessageWriter<OutboundPacket>,
|
||||
) {
|
||||
for peer in peers {
|
||||
for entity in entities {
|
||||
outbound.write(Packet::create((*entity).clone().into(), peer.id));
|
||||
if let Ok(component) = components.get(add.entity) {
|
||||
for peer in peers {
|
||||
outbound.write(Packet::create(component.clone().into(), peer.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn distribution_plugin<T: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone>(app: &mut App) {
|
||||
app.add_systems(FixedUpdate, (sender::<T>, spawner::<T>));
|
||||
app.add_systems(FixedUpdate, spawner::<T>)
|
||||
.add_observer(new_peer::<T>)
|
||||
.add_observer(new_entity::<T>);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue