Create generic distribution system

Still incredibly basic and only handles initial distribution and spawning with no relationships or anything.
This commit is contained in:
Michael Bradley 2025-07-06 18:29:58 -04:00
parent d76afe92f0
commit 4db82f328b
Signed by: MichaelBradley
SSH key fingerprint: SHA256:o/aaeYtRubILK7OYYjYP12DmU7BsPUhKji1AgaQ+ge4
5 changed files with 66 additions and 8 deletions

49
src/net/distribution.rs Normal file
View file

@ -0,0 +1,49 @@
use bevy::prelude::*;
use super::{
packet::{InboundPacket, OutboundPacket, Packet},
peer::Peer,
state::NetworkState,
};
fn spawner<T: TryFrom<Vec<u8>> + Component>(
mut inbound: EventReader<InboundPacket>,
mut commands: Commands,
) {
for packet in inbound.read() {
if let Ok(entity) = T::try_from(packet.0.message.clone()) {
commands.spawn(entity);
}
}
}
fn sender<T: Into<Vec<u8>> + Component + Clone>(
peers: Query<&Peer, Added<Peer>>,
entities: Query<&T>,
mut outbound: EventWriter<OutboundPacket>,
) {
for peer in peers {
for entity in entities {
outbound.write(OutboundPacket(Packet::new(
(*entity).clone().into(),
peer.uuid,
)));
}
}
}
pub trait Networked: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone {
fn register(app: &mut App);
}
impl<T> Networked for T
where
T: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone,
{
fn register(app: &mut App) {
app.add_systems(
FixedUpdate,
(sender::<T>, spawner::<T>).run_if(in_state(NetworkState::MultiPlayer)),
);
}
}