bevy_sync 0.19.1

Plugin for synchronizing entities and components between server and its clients.
Documentation
use super::{Message, send_initial_sync};
use crate::{
    commands::{
        ComponentNameUpdated, ComponentUpdated, CreateEntity, DeleteEntity, ReparentEntity,
        UpdateStandardMaterial,
    },
    logging::{Who, log_message_received},
};
use bevy_connect::{ClientId, events::MessageReceivedEvent};
use bevy_ecs::{message::MessageReader, system::Commands, world::World};
use tracing::debug;

pub(crate) fn process_messages(
    mut commands: Commands,
    mut events: MessageReader<MessageReceivedEvent<Message>>,
) {
    for e in events.read() {
        server_received_a_message(e.message.as_ref(), &mut commands);
    }
}

#[allow(clippy::too_many_arguments)]
fn server_received_a_message(msg: &Message, cmd: &mut Commands) {
    log_message_received(Who::Server, msg);
    match msg {
        Message::EntitySpawn { uuid } => {
            cmd.queue(CreateEntity::from(*uuid));
        }
        Message::EntityParented {
            entity_uuid: entity_id,
            parent_uuid: parent_id,
        } => {
            cmd.queue(ReparentEntity::from((*entity_id, *parent_id)));
        }
        Message::EntityDelete { uuid } => {
            cmd.queue(DeleteEntity::from(*uuid));
        }
        Message::ComponentUpdated { uuid, name, data } => {
            // This command will take care to repeat the message since it is
            // conditional of the component being updated or not, to avoid
            // infinite network loops.
            cmd.queue(ComponentUpdated::new(*uuid, name.clone(), data.clone()));
        }
        Message::StandardMaterialUpdated { uuid, material } => {
            cmd.queue(UpdateStandardMaterial::from((*uuid, material.clone())));
        }
        Message::RequestInitialSync { from_uuid } => {
            let from_uuid = ClientId(*from_uuid);
            debug!("Sending initial sync to client id: {}", from_uuid);
            cmd.queue(move |world: &mut World| send_initial_sync(from_uuid, world));
        }
        Message::FinishedInitialSync => (),
        Message::ComponentNameUpdated { uuid, data } => {
            cmd.queue(ComponentNameUpdated::new(*uuid, data.clone()));
        }
    }
}