optic_core/network.rs
1/// Unique identifier for a connected peer.
2///
3/// Peer IDs are assigned by the host during connection. The host itself
4/// always has [`PeerId::SERVER`] (0).
5#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
6pub struct PeerId(pub u64);
7
8impl PeerId {
9 /// The host/server always has this ID.
10 pub const SERVER: PeerId = PeerId(0);
11}
12
13/// Whether a [`NetworkConfig`] acts as a host or client.
14#[derive(Clone, Debug)]
15pub enum NetworkMode {
16 /// Bind and listen on a port, accepting incoming connections.
17 Host { port: u16 },
18 /// Connect to a remote host at the given address.
19 Client { addr: String },
20}
21
22/// Configuration for the networking subsystem.
23///
24/// Used with [`GameBuilder::with_network`].
25#[derive(Clone, Debug)]
26pub struct NetworkConfig {
27 pub mode: NetworkMode,
28 pub max_peers: u32,
29}
30
31impl Default for NetworkConfig {
32 fn default() -> Self {
33 Self {
34 mode: NetworkMode::Host { port: 7777 },
35 max_peers: 8,
36 }
37 }
38}
39
40impl NetworkConfig {
41 /// Convenience: host on a given port with default max peers.
42 pub fn host(port: u16) -> Self {
43 Self { mode: NetworkMode::Host { port }, max_peers: 8 }
44 }
45
46 /// Convenience: connect to a remote address with default max peers.
47 pub fn client(addr: impl Into<String>) -> Self {
48 Self { mode: NetworkMode::Client { addr: addr.into() }, max_peers: 8 }
49 }
50}
51
52/// Per-frame network events, drained from the background network thread.
53///
54/// These vectors are populated once per frame by [`NetworkHandle::poll()`]
55/// and auto-cleared at the start of the next poll cycle. This mirrors the
56/// one-frame lifecycle of button press/release events.
57#[derive(Clone, Debug, Default)]
58pub struct NetworkEvents {
59 pub peers_connected: Vec<PeerId>,
60 pub peers_disconnected: Vec<PeerId>,
61 pub packets: Vec<(PeerId, Vec<u8>)>,
62}