naia_shared/messages/channels/
channel.rs

1// Channel Trait
2pub trait Channel: 'static {}
3
4// ChannelSettings
5#[derive(Clone)]
6pub struct ChannelSettings {
7    pub mode: ChannelMode,
8    pub direction: ChannelDirection,
9}
10
11impl ChannelSettings {
12    pub fn new(mode: ChannelMode, direction: ChannelDirection) -> Self {
13        if mode.tick_buffered() && direction != ChannelDirection::ClientToServer {
14            panic!("TickBuffered Messages are only allowed to be sent from Client to Server");
15        }
16
17        Self { mode, direction }
18    }
19
20    pub fn reliable(&self) -> bool {
21        match &self.mode {
22            ChannelMode::UnorderedUnreliable => false,
23            ChannelMode::SequencedUnreliable => false,
24            ChannelMode::UnorderedReliable(_) => true,
25            ChannelMode::SequencedReliable(_) => true,
26            ChannelMode::OrderedReliable(_) => true,
27            ChannelMode::TickBuffered(_) => false,
28        }
29    }
30
31    pub fn tick_buffered(&self) -> bool {
32        self.mode.tick_buffered()
33    }
34
35    pub fn can_send_to_server(&self) -> bool {
36        match &self.direction {
37            ChannelDirection::ClientToServer => true,
38            ChannelDirection::ServerToClient => false,
39            ChannelDirection::Bidirectional => true,
40        }
41    }
42
43    pub fn can_send_to_client(&self) -> bool {
44        match &self.direction {
45            ChannelDirection::ClientToServer => false,
46            ChannelDirection::ServerToClient => true,
47            ChannelDirection::Bidirectional => true,
48        }
49    }
50
51    pub fn can_request_and_respond(&self) -> bool {
52        self.reliable() && self.can_send_to_server() && self.can_send_to_client()
53    }
54}
55
56#[derive(Clone)]
57pub struct ReliableSettings {
58    pub rtt_resend_factor: f32,
59}
60
61impl ReliableSettings {
62    pub const fn default() -> Self {
63        Self {
64            rtt_resend_factor: 1.5,
65        }
66    }
67}
68
69#[derive(Clone)]
70pub struct TickBufferSettings {
71    /// Describes a maximum of messages that may be kept in the buffer.
72    /// Oldest messages are pruned out first.
73    pub message_capacity: usize,
74}
75
76impl TickBufferSettings {
77    pub const fn default() -> Self {
78        Self {
79            message_capacity: 64,
80        }
81    }
82}
83
84// ChannelMode
85#[derive(Clone)]
86pub enum ChannelMode {
87    UnorderedUnreliable,
88    SequencedUnreliable,
89    UnorderedReliable(ReliableSettings),
90    SequencedReliable(ReliableSettings),
91    OrderedReliable(ReliableSettings),
92    TickBuffered(TickBufferSettings),
93}
94
95impl ChannelMode {
96    pub fn tick_buffered(&self) -> bool {
97        matches!(self, ChannelMode::TickBuffered(_))
98    }
99}
100
101// ChannelDirection
102#[derive(Clone, Eq, PartialEq)]
103pub enum ChannelDirection {
104    ClientToServer,
105    ServerToClient,
106    Bidirectional,
107}