Convert distribution to observers

And only distribute your own components
This commit is contained in:
Michael Bradley 2025-10-18 17:49:07 -04:00
parent 1ba4b96863
commit af11fa97fb
Signed by: MichaelBradley
SSH key fingerprint: SHA256:BKO2eI2LPsCbQS3n3i5SdwZTAIV3F1lHezR07qP+Ob0

View file

@ -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>);
}