),
29 | /// Dictionary training mode.
30 | /// 1st usize parameter here describes the desired number of samples
31 | /// (packets) to train on. Obviously, the more samples trained on, the
32 | /// better theoretical compression.
33 | Training(usize),
34 | }
35 |
--------------------------------------------------------------------------------
/shared/src/connection/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod ack_manager;
2 | pub mod bandwidth_monitor;
3 | pub mod base_connection;
4 | pub mod compression_config;
5 | pub mod connection_config;
6 | pub mod decoder;
7 | pub mod encoder;
8 | pub mod packet_notifiable;
9 | pub mod packet_type;
10 | pub mod ping_store;
11 | pub mod sequence_buffer;
12 | pub mod standard_header;
13 |
--------------------------------------------------------------------------------
/shared/src/connection/packet_notifiable.rs:
--------------------------------------------------------------------------------
1 | use crate::PacketIndex;
2 |
3 | /// Represents a manager that must be notified when packets have been dropped or
4 | /// delivered
5 | pub trait PacketNotifiable {
6 | /// Notifies the manager that a packet has been delivered
7 | fn notify_packet_delivered(&mut self, packet_index: PacketIndex);
8 | }
9 |
--------------------------------------------------------------------------------
/shared/src/constants.rs:
--------------------------------------------------------------------------------
1 | pub const FRAGMENTATION_LIMIT_BYTES: usize = 400;
2 | pub const FRAGMENTATION_LIMIT_BITS: u32 = (FRAGMENTATION_LIMIT_BYTES as u32) * 8;
3 |
--------------------------------------------------------------------------------
/shared/src/handshake/advanced/header.rs:
--------------------------------------------------------------------------------
1 | use naia_serde::SerdeInternal;
2 |
3 | #[derive(SerdeInternal, Debug, PartialEq, Eq, Clone)]
4 | pub enum HandshakeHeader {
5 | // An initial handshake message sent by the Client to the Server
6 | ClientChallengeRequest,
7 | // The Server's response to the Client's initial handshake message
8 | ServerChallengeResponse,
9 | // The handshake message validating the Client
10 | ClientValidateRequest,
11 | // The Server's response to the Client's validation request
12 | ServerValidateResponse,
13 | // The final handshake message sent by the Client
14 | ClientConnectRequest,
15 | // The final handshake message sent by the Server, indicating that the
16 | // connection has been established
17 | ServerConnectResponse,
18 | // Used to request a graceful Client disconnect from the Server
19 | Disconnect,
20 | }
21 |
--------------------------------------------------------------------------------
/shared/src/handshake/advanced/mod.rs:
--------------------------------------------------------------------------------
1 | mod header;
2 | pub use header::HandshakeHeader;
3 |
--------------------------------------------------------------------------------
/shared/src/handshake/mod.rs:
--------------------------------------------------------------------------------
1 | cfg_if! {
2 | if #[cfg(feature = "advanced_handshake")] {
3 | mod advanced;
4 | pub use advanced::*;
5 | } else {
6 | mod simple;
7 | pub use simple::*;
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/shared/src/handshake/simple/header.rs:
--------------------------------------------------------------------------------
1 | use naia_serde::SerdeInternal;
2 |
3 | #[derive(SerdeInternal, Debug, PartialEq, Eq, Clone)]
4 | pub enum HandshakeHeader {
5 | // An initial handshake message sent by the Client to the Server
6 | ClientIdentifyRequest,
7 | // The Server's response to the Client's initial handshake message
8 | ServerIdentifyResponse,
9 | // The handshake message sent by the Client to initiate a connection
10 | ClientConnectRequest,
11 | // The handshake message sent by the Server, indicating that the
12 | // connection has been established
13 | ServerConnectResponse,
14 | // Used to request a graceful Client disconnect from the Server
15 | Disconnect,
16 | }
17 |
--------------------------------------------------------------------------------
/shared/src/handshake/simple/mod.rs:
--------------------------------------------------------------------------------
1 | mod header;
2 | pub use header::HandshakeHeader;
3 |
--------------------------------------------------------------------------------
/shared/src/messages/channels/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod channel;
2 | pub mod channel_kinds;
3 | pub mod default_channels;
4 | pub mod receivers;
5 | pub mod senders;
6 | pub mod system_channel;
7 |
--------------------------------------------------------------------------------
/shared/src/messages/channels/receivers/channel_receiver.rs:
--------------------------------------------------------------------------------
1 | use naia_serde::{BitReader, SerdeErr};
2 | use naia_socket_shared::Instant;
3 |
4 | use crate::messages::channels::senders::request_sender::LocalRequestId;
5 | use crate::{
6 | messages::{message_container::MessageContainer, message_kinds::MessageKinds},
7 | world::remote::entity_waitlist::EntityWaitlist,
8 | LocalEntityAndGlobalEntityConverter, LocalResponseId,
9 | };
10 |
11 | pub trait ChannelReceiver: Send + Sync {
12 | /// Read messages from an internal buffer and return their content
13 | fn receive_messages(
14 | &mut self,
15 | message_kinds: &MessageKinds,
16 | now: &Instant,
17 | entity_waitlist: &mut EntityWaitlist,
18 | converter: &dyn LocalEntityAndGlobalEntityConverter,
19 | ) -> Vec
;
20 | }
21 |
22 | pub trait MessageChannelReceiver: ChannelReceiver {
23 | /// Read messages from raw bits, parse them and store then into an internal buffer
24 | fn read_messages(
25 | &mut self,
26 | message_kinds: &MessageKinds,
27 | entity_waitlist: &mut EntityWaitlist,
28 | converter: &dyn LocalEntityAndGlobalEntityConverter,
29 | reader: &mut BitReader,
30 | ) -> Result<(), SerdeErr>;
31 |
32 | fn receive_requests_and_responses(
33 | &mut self,
34 | ) -> (
35 | Vec<(LocalResponseId, MessageContainer)>,
36 | Vec<(LocalRequestId, MessageContainer)>,
37 | );
38 | }
39 |
--------------------------------------------------------------------------------
/shared/src/messages/channels/receivers/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod channel_receiver;
2 | pub mod fragment_receiver;
3 | pub mod indexed_message_reader;
4 | pub mod ordered_reliable_receiver;
5 | pub mod sequenced_reliable_receiver;
6 | pub mod sequenced_unreliable_receiver;
7 | pub mod unordered_reliable_receiver;
8 | pub mod unordered_unreliable_receiver;
9 |
10 | mod reliable_message_receiver;
11 | pub mod reliable_receiver;
12 |
--------------------------------------------------------------------------------
/shared/src/messages/channels/receivers/sequenced_reliable_receiver.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | messages::channels::receivers::reliable_message_receiver::{
3 | ReceiverArranger, ReliableMessageReceiver,
4 | },
5 | sequence_less_than,
6 | types::MessageIndex,
7 | MessageContainer,
8 | };
9 |
10 | pub type SequencedReliableReceiver = ReliableMessageReceiver;
11 |
12 | impl SequencedReliableReceiver {
13 | pub fn new() -> Self {
14 | Self::with_arranger(SequencedArranger {
15 | newest_received_message_index: 0,
16 | })
17 | }
18 | }
19 |
20 | // SequencedArranger
21 | pub struct SequencedArranger {
22 | newest_received_message_index: MessageIndex,
23 | }
24 |
25 | impl ReceiverArranger for SequencedArranger {
26 | fn process(
27 | &mut self,
28 | start_message_index: MessageIndex,
29 | end_message_index: MessageIndex,
30 | message: MessageContainer,
31 | ) -> Vec {
32 | let mut output = Vec::new();
33 | if !sequence_less_than(start_message_index, self.newest_received_message_index) {
34 | self.newest_received_message_index = end_message_index;
35 | output.push(message);
36 | }
37 | output
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/shared/src/messages/channels/receivers/unordered_reliable_receiver.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | messages::channels::receivers::reliable_message_receiver::{
3 | ReceiverArranger, ReliableMessageReceiver,
4 | },
5 | types::MessageIndex,
6 | MessageContainer,
7 | };
8 |
9 | pub type UnorderedReliableReceiver = ReliableMessageReceiver;
10 |
11 | impl UnorderedReliableReceiver {
12 | pub fn new() -> Self {
13 | Self::with_arranger(UnorderedArranger)
14 | }
15 | }
16 |
17 | // UnorderedArranger
18 | pub struct UnorderedArranger;
19 |
20 | impl ReceiverArranger for UnorderedArranger {
21 | fn process(
22 | &mut self,
23 | _start_message_index: MessageIndex,
24 | _end_message_index: MessageIndex,
25 | message: MessageContainer,
26 | ) -> Vec {
27 | let mut output = Vec::new();
28 | output.push(message);
29 | output
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/shared/src/messages/channels/senders/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod channel_sender;
2 | pub mod indexed_message_writer;
3 | pub mod message_fragmenter;
4 | pub mod reliable_message_sender;
5 | pub mod reliable_sender;
6 | pub mod request_sender;
7 | pub mod sequenced_unreliable_sender;
8 | pub mod unordered_unreliable_sender;
9 |
--------------------------------------------------------------------------------
/shared/src/messages/channels/system_channel.rs:
--------------------------------------------------------------------------------
1 | use crate::Channel;
2 |
3 | #[derive(Channel)]
4 | pub struct SystemChannel;
5 |
--------------------------------------------------------------------------------
/shared/src/messages/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod channels;
2 | pub mod fragment;
3 | pub mod message;
4 | pub mod message_container;
5 | pub mod message_kinds;
6 | pub mod message_manager;
7 | pub mod named;
8 | pub mod request;
9 |
10 | #[cfg(test)]
11 | mod tests;
12 |
--------------------------------------------------------------------------------
/shared/src/messages/named.rs:
--------------------------------------------------------------------------------
1 | pub trait Named {
2 | /// Gets the String representation of the Type of the Component, used for debugging
3 | fn name(&self) -> String;
4 | }
5 |
--------------------------------------------------------------------------------
/shared/src/messages/tests/mod.rs:
--------------------------------------------------------------------------------
1 | mod fragment;
2 |
--------------------------------------------------------------------------------
/shared/src/types.rs:
--------------------------------------------------------------------------------
1 | pub type PacketIndex = u16;
2 | pub type Tick = u16;
3 | pub type MessageIndex = u16;
4 | pub type ShortMessageIndex = u8;
5 |
6 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7 | pub enum HostType {
8 | Server,
9 | Client,
10 | }
11 |
--------------------------------------------------------------------------------
/shared/src/world/component/component_update.rs:
--------------------------------------------------------------------------------
1 | use naia_serde::{BitReader, OwnedBitReader, SerdeErr};
2 |
3 | use crate::{
4 | world::component::component_kinds::ComponentKind, ComponentKinds,
5 | LocalEntityAndGlobalEntityConverter, RemoteEntity,
6 | };
7 |
8 | pub struct ComponentUpdate {
9 | pub kind: ComponentKind,
10 | buffer: OwnedBitReader,
11 | }
12 |
13 | impl ComponentUpdate {
14 | pub fn new(kind: ComponentKind, buffer: OwnedBitReader) -> Self {
15 | Self { kind, buffer }
16 | }
17 |
18 | pub fn reader(&self) -> BitReader {
19 | self.buffer.borrow()
20 | }
21 |
22 | pub(crate) fn split_into_waiting_and_ready(
23 | self,
24 | converter: &dyn LocalEntityAndGlobalEntityConverter,
25 | component_kinds: &ComponentKinds,
26 | ) -> Result<
27 | (
28 | Option>,
29 | Option,
30 | ),
31 | SerdeErr,
32 | > {
33 | let kind = self.kind;
34 | component_kinds.split_update(converter, &kind, self)
35 | }
36 | }
37 |
38 | pub struct ComponentFieldUpdate {
39 | id: u8,
40 | buffer: OwnedBitReader,
41 | }
42 |
43 | impl ComponentFieldUpdate {
44 | pub fn new(id: u8, buffer: OwnedBitReader) -> Self {
45 | Self { id, buffer }
46 | }
47 |
48 | pub fn field_id(&self) -> u8 {
49 | self.id
50 | }
51 |
52 | pub fn reader(&self) -> BitReader {
53 | self.buffer.borrow()
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/shared/src/world/component/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod component_kinds;
2 | pub mod component_update;
3 | pub mod diff_mask;
4 | pub mod entity_property;
5 | pub mod property;
6 | pub mod property_mutate;
7 | pub mod replica_ref;
8 | pub mod replicate;
9 |
--------------------------------------------------------------------------------
/shared/src/world/delegation/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod auth_channel;
2 | pub mod entity_auth_status;
3 | pub mod host_auth_handler;
4 |
--------------------------------------------------------------------------------
/shared/src/world/entity/entity_action.rs:
--------------------------------------------------------------------------------
1 | use crate::world::component::component_kinds::ComponentKind;
2 |
3 | pub enum EntityAction {
4 | SpawnEntity(E, Vec),
5 | DespawnEntity(E),
6 | InsertComponent(E, ComponentKind),
7 | RemoveComponent(E, ComponentKind),
8 | Noop,
9 | }
10 |
11 | impl EntityAction {
12 | pub fn entity(&self) -> Option {
13 | match self {
14 | EntityAction::SpawnEntity(entity, _) => Some(*entity),
15 | EntityAction::DespawnEntity(entity) => Some(*entity),
16 | EntityAction::InsertComponent(entity, _) => Some(*entity),
17 | EntityAction::RemoveComponent(entity, _) => Some(*entity),
18 | EntityAction::Noop => None,
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/shared/src/world/entity/entity_action_type.rs:
--------------------------------------------------------------------------------
1 | use naia_serde::SerdeInternal;
2 |
3 | // Enum used as a shared network protocol, representing various message types
4 | // related to Entities/Components
5 | #[derive(Copy, PartialEq, Clone, SerdeInternal)]
6 | pub enum EntityActionType {
7 | // Action indicating an Entity to be created
8 | SpawnEntity,
9 | // Action indicating an Entity to be deleted
10 | DespawnEntity,
11 | // Action indicating a Component to be added to an Entity
12 | InsertComponent,
13 | // Action indicating a Component to be deleted
14 | RemoveComponent,
15 | // Action indicating a non-operation
16 | Noop,
17 | }
18 |
--------------------------------------------------------------------------------
/shared/src/world/entity/error.rs:
--------------------------------------------------------------------------------
1 | use std::error::Error;
2 |
3 | #[derive(Debug)]
4 | pub struct EntityDoesNotExistError;
5 | impl Error for EntityDoesNotExistError {}
6 | impl std::fmt::Display for EntityDoesNotExistError {
7 | fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
8 | write!(f, "Error while attempting to look-up an Entity value for conversion: Entity was not found!")
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/shared/src/world/entity/global_entity.rs:
--------------------------------------------------------------------------------
1 | use crate::BigMapKey;
2 | use naia_serde::{BitReader, BitWrite, Serde, SerdeErr};
3 |
4 | // GlobalEntity
5 | #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
6 | pub struct GlobalEntity(u64);
7 |
8 | impl BigMapKey for GlobalEntity {
9 | fn to_u64(&self) -> u64 {
10 | self.0
11 | }
12 |
13 | fn from_u64(value: u64) -> Self {
14 | GlobalEntity(value)
15 | }
16 | }
17 |
18 | impl Serde for GlobalEntity {
19 | fn ser(&self, _: &mut dyn BitWrite) {
20 | panic!("shouldn't call this");
21 | }
22 |
23 | fn de(_: &mut BitReader) -> Result {
24 | panic!("shouldn't call this");
25 | }
26 |
27 | fn bit_length(&self) -> u32 {
28 | panic!("shouldn't call this");
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/shared/src/world/entity/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod entity_action;
2 | pub mod entity_action_receiver;
3 | pub mod entity_action_type;
4 | pub mod entity_auth_event;
5 | pub mod entity_converters;
6 | pub mod error;
7 | pub mod global_entity;
8 | pub mod local_entity;
9 |
--------------------------------------------------------------------------------
/shared/src/world/host/entity_action_event.rs:
--------------------------------------------------------------------------------
1 | use crate::ComponentKind;
2 |
3 | #[derive(Clone, PartialEq, Eq)]
4 | pub enum EntityActionEvent {
5 | SpawnEntity(E, Vec),
6 | DespawnEntity(E),
7 | InsertComponent(E, ComponentKind),
8 | RemoveComponent(E, ComponentKind),
9 | }
10 |
--------------------------------------------------------------------------------
/shared/src/world/host/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod global_diff_handler;
2 | pub mod host_world_manager;
3 | pub mod host_world_writer;
4 | pub mod mut_channel;
5 | pub mod user_diff_handler;
6 | pub mod world_channel;
7 |
8 | mod entity_action_event;
9 | mod entity_channel;
10 |
--------------------------------------------------------------------------------
/shared/src/world/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod component;
2 | pub mod delegation;
3 | pub mod entity;
4 | pub mod host;
5 | pub mod local_entity_map;
6 | pub mod local_world_manager;
7 | pub mod remote;
8 | pub mod shared_global_world_manager;
9 | pub mod world_type;
10 |
--------------------------------------------------------------------------------
/shared/src/world/remote/entity_action_event.rs:
--------------------------------------------------------------------------------
1 | use crate::{ComponentKind, Replicate};
2 |
3 | pub enum EntityActionEvent {
4 | SpawnEntity(E),
5 | DespawnEntity(E),
6 | InsertComponent(E, ComponentKind),
7 | RemoveComponent(E, Box),
8 | }
9 |
--------------------------------------------------------------------------------
/shared/src/world/remote/entity_event.rs:
--------------------------------------------------------------------------------
1 | use crate::{ComponentKind, EntityAuthStatus, RemoteEntity, Replicate, Tick};
2 |
3 | pub enum EntityEvent {
4 | SpawnEntity(E),
5 | DespawnEntity(E),
6 | InsertComponent(E, ComponentKind),
7 | RemoveComponent(E, Box),
8 | UpdateComponent(Tick, E, ComponentKind),
9 | }
10 |
11 | pub enum EntityResponseEvent {
12 | SpawnEntity(E),
13 | DespawnEntity(E),
14 | InsertComponent(E, ComponentKind),
15 | RemoveComponent(E, ComponentKind),
16 | PublishEntity(E),
17 | UnpublishEntity(E),
18 | EnableDelegationEntity(E),
19 | EnableDelegationEntityResponse(E),
20 | DisableDelegationEntity(E),
21 | EntityRequestAuthority(E, RemoteEntity),
22 | EntityReleaseAuthority(E),
23 | EntityUpdateAuthority(E, EntityAuthStatus),
24 | EntityMigrateResponse(E, RemoteEntity),
25 | }
26 |
--------------------------------------------------------------------------------
/shared/src/world/remote/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod entity_action_event;
2 | pub mod entity_event;
3 | pub mod entity_waitlist;
4 | pub mod remote_world_manager;
5 | pub mod remote_world_reader;
6 |
--------------------------------------------------------------------------------
/shared/tests/derive_struct.rs:
--------------------------------------------------------------------------------
1 | mod some_struct {
2 | use naia_shared::Serde;
3 |
4 | #[derive(Clone, Debug, PartialEq, Serde)]
5 | pub struct SomeStruct {
6 | pub some_string: String,
7 | pub some_int: i16,
8 | pub some_bool: bool,
9 | }
10 | }
11 |
12 | use naia_shared::{BitReader, BitWriter, Serde};
13 |
14 | use some_struct::SomeStruct;
15 |
16 | #[test]
17 | fn read_write_struct() {
18 | // Write
19 | let mut writer = BitWriter::new();
20 |
21 | let in_1 = SomeStruct {
22 | some_string: "Hello world!".to_string(),
23 | some_int: 42,
24 | some_bool: true,
25 | };
26 | let in_2 = SomeStruct {
27 | some_string: "Goodbye world!".to_string(),
28 | some_int: -42,
29 | some_bool: false,
30 | };
31 |
32 | in_1.ser(&mut writer);
33 | in_2.ser(&mut writer);
34 |
35 | let bytes = writer.to_bytes();
36 |
37 | // Read
38 |
39 | let mut reader = BitReader::new(&bytes);
40 |
41 | let out_1 = Serde::de(&mut reader).unwrap();
42 | let out_2 = Serde::de(&mut reader).unwrap();
43 |
44 | assert_eq!(in_1, out_1);
45 | assert_eq!(in_2, out_2);
46 | }
47 |
--------------------------------------------------------------------------------
/shared/tests/derive_tuple_struct.rs:
--------------------------------------------------------------------------------
1 | mod some_struct {
2 | use naia_shared::Serde;
3 |
4 | #[derive(Clone, Debug, PartialEq, Serde)]
5 | pub struct SomeStruct(pub String, pub i16, pub bool);
6 | }
7 |
8 | use naia_shared::{BitReader, BitWriter, Serde};
9 | use some_struct::SomeStruct;
10 |
11 | #[test]
12 | fn read_write_tuple_struct() {
13 | // Write
14 | let mut writer = BitWriter::new();
15 |
16 | let in_1 = SomeStruct("Hello world!".to_string(), 42, true);
17 | let in_2 = SomeStruct("Goodbye world!".to_string(), -42, false);
18 |
19 | in_1.ser(&mut writer);
20 | in_2.ser(&mut writer);
21 |
22 | let bytes = writer.to_bytes();
23 |
24 | // Read
25 |
26 | let mut reader = BitReader::new(&bytes);
27 |
28 | let out_1 = Serde::de(&mut reader).unwrap();
29 | let out_2 = Serde::de(&mut reader).unwrap();
30 |
31 | assert_eq!(in_1, out_1);
32 | assert_eq!(in_2, out_2);
33 | }
34 |
--------------------------------------------------------------------------------
/shared/tests/derive_unit_struct.rs:
--------------------------------------------------------------------------------
1 | mod some_struct {
2 | use naia_shared::Serde;
3 |
4 | #[derive(Clone, Debug, PartialEq, Serde)]
5 | pub struct SomeStruct;
6 | }
7 |
8 | use naia_shared::{BitReader, BitWriter, Serde};
9 | use some_struct::SomeStruct;
10 |
11 | #[test]
12 | fn read_write_unit_struct() {
13 | // Write
14 | let mut writer = BitWriter::new();
15 |
16 | let in_1 = SomeStruct;
17 |
18 | in_1.ser(&mut writer);
19 |
20 | let bytes = writer.to_bytes();
21 |
22 | // Read
23 |
24 | let mut reader = BitReader::new(&bytes);
25 |
26 | let out_1 = Serde::de(&mut reader).unwrap();
27 |
28 | assert_eq!(in_1, out_1);
29 | }
30 |
--------------------------------------------------------------------------------
/socket/client/src/backends/miniquad/identity_receiver.rs:
--------------------------------------------------------------------------------
1 | use super::shared::ID_CELL;
2 | use crate::{identity_receiver::IdentityReceiver, IdentityReceiverResult};
3 |
4 | /// Handles receiving an IdentityToken from the Server through a given Client Socket
5 | #[derive(Clone)]
6 | pub struct IdentityReceiverImpl;
7 |
8 | impl IdentityReceiver for IdentityReceiverImpl {
9 | fn receive(&mut self) -> IdentityReceiverResult {
10 | unsafe {
11 | if let Some(id_cell) = &mut ID_CELL {
12 | if let Some(id_token) = id_cell.take() {
13 | return IdentityReceiverResult::Success(id_token);
14 | }
15 | }
16 | };
17 |
18 | IdentityReceiverResult::Waiting
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/socket/client/src/backends/miniquad/mod.rs:
--------------------------------------------------------------------------------
1 | mod shared;
2 |
3 | mod identity_receiver;
4 | mod packet_receiver;
5 | mod packet_sender;
6 | mod socket;
7 |
8 | pub use identity_receiver::IdentityReceiverImpl;
9 | pub use packet_receiver::PacketReceiverImpl;
10 | pub use packet_sender::PacketSenderImpl;
11 | pub use socket::Socket;
12 |
--------------------------------------------------------------------------------
/socket/client/src/backends/miniquad/packet_sender.rs:
--------------------------------------------------------------------------------
1 | use crate::{error::NaiaClientSocketError, packet_sender::PacketSender, ServerAddr};
2 |
3 | use super::shared::{
4 | naia_create_u8_array, naia_disconnect, naia_is_connected, naia_send, SERVER_ADDR,
5 | };
6 |
7 | /// Handles sending messages to the Server for a given Client Socket
8 | #[derive(Clone, Default)]
9 | pub struct PacketSenderImpl;
10 |
11 | impl PacketSender for PacketSenderImpl {
12 | /// Send a Packet to the Server
13 | fn send(&self, payload: &[u8]) -> Result<(), NaiaClientSocketError> {
14 | unsafe {
15 | let ptr = payload.as_ptr();
16 | let len = payload.len();
17 | let js_obj = naia_create_u8_array(ptr as _, len as _);
18 | return if naia_send(js_obj) {
19 | Ok(())
20 | } else {
21 | Err(NaiaClientSocketError::SendError)
22 | };
23 | }
24 | }
25 |
26 | /// Get the Server's Socket address
27 | fn server_addr(&self) -> ServerAddr {
28 | unsafe { SERVER_ADDR }
29 | }
30 |
31 | fn connected(&self) -> bool {
32 | unsafe {
33 | return naia_is_connected();
34 | }
35 | }
36 |
37 | fn disconnect(&mut self) {
38 | unsafe {
39 | naia_disconnect();
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/socket/client/src/backends/mod.rs:
--------------------------------------------------------------------------------
1 | mod socket;
2 |
3 | cfg_if! {
4 | if #[cfg(all(target_arch = "wasm32", feature = "wbindgen"))] {
5 | mod wasm_bindgen;
6 | pub use self::wasm_bindgen::*;
7 | }
8 | else if #[cfg(all(target_arch = "wasm32", feature = "mquad"))] {
9 | mod miniquad;
10 | pub use self::miniquad::*;
11 | }
12 | else {
13 | mod native;
14 | pub use self::native::*;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/socket/client/src/backends/native/identity_receiver.rs:
--------------------------------------------------------------------------------
1 | use std::sync::{Arc, Mutex};
2 |
3 | use tokio::sync::oneshot;
4 |
5 | use crate::{identity_receiver::IdentityReceiver, IdentityReceiverResult};
6 |
7 | /// Handles receiving an IdentityToken from the Server through a given Client Socket
8 | #[derive(Clone)]
9 | pub struct IdentityReceiverImpl {
10 | receiver_channel: Arc>>>,
11 | }
12 |
13 | impl IdentityReceiverImpl {
14 | /// Create a new IdentityReceiver, if supplied with the Server's address & a
15 | /// reference back to the parent Socket
16 | pub fn new(receiver_channel: oneshot::Receiver>) -> Self {
17 | Self {
18 | receiver_channel: Arc::new(Mutex::new(receiver_channel)),
19 | }
20 | }
21 | }
22 |
23 | impl IdentityReceiver for IdentityReceiverImpl {
24 | fn receive(&mut self) -> IdentityReceiverResult {
25 | if let Ok(mut receiver) = self.receiver_channel.lock() {
26 | if let Ok(recv_result) = receiver.try_recv() {
27 | match recv_result {
28 | Ok(identity_token) => IdentityReceiverResult::Success(identity_token),
29 | Err(error_code) => IdentityReceiverResult::ErrorResponseCode(error_code),
30 | }
31 | } else {
32 | IdentityReceiverResult::Waiting
33 | }
34 | } else {
35 | IdentityReceiverResult::Waiting
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/socket/client/src/backends/native/mod.rs:
--------------------------------------------------------------------------------
1 | mod identity_receiver;
2 | mod packet_receiver;
3 | mod packet_sender;
4 | mod runtime;
5 | mod socket;
6 |
7 | pub use identity_receiver::IdentityReceiverImpl;
8 | pub use packet_receiver::PacketReceiverImpl;
9 | pub use packet_sender::PacketSenderImpl;
10 | pub use socket::Socket;
11 |
--------------------------------------------------------------------------------
/socket/client/src/backends/native/runtime.rs:
--------------------------------------------------------------------------------
1 | use std::{future, thread};
2 |
3 | use once_cell::sync::Lazy;
4 | use tokio::runtime::{Builder, Handle};
5 |
6 | /// TODO: make description
7 | pub fn get_runtime() -> Handle {
8 | static GLOBAL: Lazy = Lazy::new(|| {
9 | let runtime = Builder::new_multi_thread()
10 | .enable_all()
11 | .build()
12 | .expect("was not able to build the runtime");
13 |
14 | let runtime_handle = runtime.handle().clone();
15 |
16 | thread::Builder::new()
17 | .name("tokio-main".to_string())
18 | .spawn(move || {
19 | let _guard = runtime.enter();
20 | runtime.block_on(future::pending::<()>());
21 | })
22 | .expect("cannot spawn executor thread");
23 |
24 | let _guard = runtime_handle.enter();
25 |
26 | runtime_handle
27 | });
28 |
29 | Lazy::::force(&GLOBAL).clone()
30 | }
31 |
--------------------------------------------------------------------------------
/socket/client/src/backends/socket.rs:
--------------------------------------------------------------------------------
1 | use naia_socket_shared::SocketConfig;
2 |
3 | use crate::{
4 | identity_receiver::IdentityReceiver, packet_receiver::PacketReceiver,
5 | packet_sender::PacketSender,
6 | };
7 |
8 | /// Used to send packets from the Client Socket
9 | #[allow(dead_code)]
10 | pub trait SocketTrait {
11 | fn connect(
12 | server_session_url: &str,
13 | config: &SocketConfig,
14 | ) -> (
15 | Box,
16 | Box,
17 | Box,
18 | );
19 | fn connect_with_auth(
20 | server_session_url: &str,
21 | config: &SocketConfig,
22 | auth_bytes: Vec,
23 | ) -> (
24 | Box,
25 | Box,
26 | Box,
27 | );
28 | }
29 |
--------------------------------------------------------------------------------
/socket/client/src/backends/wasm_bindgen/addr_cell.rs:
--------------------------------------------------------------------------------
1 | use std::{
2 | net::SocketAddr,
3 | sync::{Arc, Mutex},
4 | };
5 |
6 | use crate::{server_addr::ServerAddr, wasm_utils::candidate_to_addr};
7 |
8 | // MaybeAddr
9 | struct MaybeAddr(pub(crate) ServerAddr);
10 |
11 | // AddrCell
12 | #[derive(Clone)]
13 | pub struct AddrCell {
14 | cell: Arc>,
15 | }
16 |
17 | impl AddrCell {
18 | pub fn new() -> Self {
19 | AddrCell {
20 | cell: Arc::new(Mutex::new(MaybeAddr(ServerAddr::Finding))),
21 | }
22 | }
23 |
24 | pub fn receive_candidate(&self, candidate_str: &str) {
25 | self.cell
26 | .lock()
27 | .expect("This should never happen, receive_candidate() should only be called once ever during the session initialization")
28 | .0 = candidate_to_addr(candidate_str);
29 | }
30 |
31 | pub fn get(&self) -> ServerAddr {
32 | match self.cell.try_lock() {
33 | Ok(addr) => addr.0,
34 | Err(_) => ServerAddr::Finding,
35 | }
36 | }
37 |
38 | pub fn set_addr(&mut self, addr: &SocketAddr) {
39 | self.cell.lock().expect("cannot borrow AddrCell.cell!").0 = ServerAddr::Found(addr.clone());
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/socket/client/src/backends/wasm_bindgen/mod.rs:
--------------------------------------------------------------------------------
1 | mod addr_cell;
2 | mod data_channel;
3 | mod data_port;
4 |
5 | mod identity_receiver;
6 | mod packet_receiver;
7 | mod packet_sender;
8 | mod socket;
9 |
10 | pub use data_channel::DataChannel;
11 | pub use data_port::DataPort;
12 | pub use identity_receiver::IdentityReceiverImpl;
13 | pub use packet_receiver::PacketReceiverImpl;
14 | pub use packet_sender::PacketSenderImpl;
15 | pub use socket::Socket;
16 |
--------------------------------------------------------------------------------
/socket/client/src/error.rs:
--------------------------------------------------------------------------------
1 | use std::{error::Error, fmt};
2 |
3 | /// An Error type specifically related to the Naia Client Socket
4 | /// This is under construction and needs to be cleaned up
5 | #[derive(Debug)]
6 | pub enum NaiaClientSocketError {
7 | /// A simple error message
8 | Message(String),
9 | /// An error indicating an inability to send to the given address
10 | SendError,
11 | }
12 |
13 | impl fmt::Display for NaiaClientSocketError {
14 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
15 | match self {
16 | NaiaClientSocketError::Message(msg) => write!(f, "Naia Client Socket Error: {}", msg),
17 | NaiaClientSocketError::SendError => write!(f, "Naia Client Socket Send Error"),
18 | }
19 | }
20 | }
21 |
22 | impl Error for NaiaClientSocketError {}
23 |
--------------------------------------------------------------------------------
/socket/client/src/identity_receiver.rs:
--------------------------------------------------------------------------------
1 | use naia_socket_shared::IdentityToken;
2 |
3 | pub enum IdentityReceiverResult {
4 | Waiting,
5 | Success(IdentityToken),
6 | ErrorResponseCode(u16),
7 | }
8 |
9 | /// Used to receive an IdentityToken from the Client Socket
10 | pub trait IdentityReceiver: IdentityReceiverClone + Send + Sync {
11 | /// Receives an IdentityToken from the Client Socket
12 | fn receive(&mut self) -> IdentityReceiverResult;
13 | }
14 |
15 | /// Used to clone Box
16 | pub trait IdentityReceiverClone {
17 | /// Clone the boxed IdentityReceiver
18 | fn clone_box(&self) -> Box;
19 | }
20 |
21 | impl IdentityReceiverClone for T {
22 | fn clone_box(&self) -> Box {
23 | Box::new(self.clone())
24 | }
25 | }
26 |
27 | impl Clone for Box {
28 | fn clone(&self) -> Box {
29 | IdentityReceiverClone::clone_box(self.as_ref())
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/socket/client/src/packet_receiver.rs:
--------------------------------------------------------------------------------
1 | use super::{error::NaiaClientSocketError, server_addr::ServerAddr};
2 |
3 | /// Used to receive packets from the Client Socket
4 | pub trait PacketReceiver: PacketReceiverClone + Send + Sync {
5 | /// Receives a packet from the Client Socket
6 | fn receive(&mut self) -> Result