1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*!
# Bevy engine network synchronization
**state is in development**

Wire up server and clients to synchronize their entities, components and assets,
mainly intended for collaborative editing combined with `bevy_editor_pls` crate.

Networking is through UDP (renet standard) and changes are sent through a ordered+reliable channel
with idempotent messages.

Uses:
  - `bevy`
  - `bevy_renet`
  - `serde` & `bincode`

## Example

```rust
use std::net::Ipv4Addr;
use bevy::{prelude::*, MinimalPlugins,};
use bevy_sync::{ServerPlugin, SyncComponent, SyncMark, SyncPlugin};

let mut app = App::new();
app.add_plugins(MinimalPlugins);

// Either one of these two, if being server or client
app.add_plugin(ServerPlugin { ip: Ipv4Addr::LOCALHOST.into(), port: 5555 });
//app.add_plugin(ClientPlugin { ip: Ipv4Addr::LOCALHOST.into(), port: 5555 });

// Setup sync mechanics and which components will be synced
app.add_plugin(SyncPlugin);
app.sync_component::<Transform>();

// Mark entity for sync with SyncMark component
app.world.spawn(Transform::default()).insert(SyncMark {});
```

*/

mod bundle_fix;
mod client;
mod lib_priv;
mod mesh_serde;
mod networking;
mod proto;
mod proto_serde;
mod server;

pub mod prelude {
    pub use super::{
        ClientPlugin, ClientState, ServerPlugin, ServerState, SyncComponent, SyncDown, SyncExclude,
        SyncMark, SyncPlugin, SyncUp,
    };
}

use std::{marker::PhantomData, net::IpAddr};

use bevy::{prelude::*, reflect::*};

#[derive(Debug, Clone, Eq, PartialEq, Hash, Default, States)]
pub enum ServerState {
    Connected,
    #[default]
    Disconnected,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Default, States)]
pub enum ClientState {
    ConnectedInitialSync,
    Connected,
    Connecting,
    #[default]
    Disconnected,
}

#[derive(Component, Reflect, Default)]
#[reflect(Component)]
pub struct SyncMark;

#[derive(Component, Default)]
pub struct SyncExclude<T>
where
    T: Component,
{
    marker: PhantomData<T>,
}

pub struct SyncPlugin;

pub struct ServerPlugin {
    pub port: u16,
    pub ip: IpAddr,
}

pub struct ClientPlugin {
    pub ip: IpAddr,
    pub port: u16,
}

#[derive(Component)]
pub struct SyncDown {}

#[derive(Component)]
pub struct SyncUp {
    pub server_entity_id: Entity,
}

pub trait SyncComponent {
    fn sync_component<T: Component + Reflect + FromReflect + GetTypeRegistration>(
        &mut self,
    ) -> &mut Self;
    fn sync_materials(&mut self, enable: bool);
    fn sync_meshes(&mut self, enable: bool);
}