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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use std::{hash::Hash, net::SocketAddr};

use naia_serde::{BitWriter, Serde};
use naia_socket_shared::Instant;

use crate::world::local_world_manager::LocalWorldManager;
use crate::{
    backends::Timer,
    messages::{channels::channel_kinds::ChannelKinds, message_manager::MessageManager},
    types::{HostType, PacketIndex},
    world::entity::entity_converters::GlobalWorldManagerType,
    EntityConverter, EntityEvent, EntityHandleConverter, HostWorldManager, MessageKinds, Protocol,
    RemoteWorldManager, WorldMutType, WorldRefType,
};

use super::{
    ack_manager::AckManager, connection_config::ConnectionConfig,
    packet_notifiable::PacketNotifiable, packet_type::PacketType, standard_header::StandardHeader,
};

/// Represents a connection to a remote host, and provides functionality to
/// manage the connection and the communications to it
pub struct BaseConnection<E: Copy + Eq + Hash + Send + Sync> {
    pub message_manager: MessageManager,
    pub host_world_manager: HostWorldManager<E>,
    pub remote_world_manager: RemoteWorldManager,
    pub local_world_manager: LocalWorldManager<E>,
    heartbeat_timer: Timer,
    timeout_timer: Timer,
    ack_manager: AckManager,
}

impl<E: Copy + Eq + Hash + Send + Sync> BaseConnection<E> {
    /// Create a new BaseConnection, given the appropriate underlying managers
    pub fn new(
        address: &Option<SocketAddr>,
        host_type: HostType,
        connection_config: &ConnectionConfig,
        channel_kinds: &ChannelKinds,
        global_world_manager: &dyn GlobalWorldManagerType<E>,
    ) -> Self {
        BaseConnection {
            heartbeat_timer: Timer::new(connection_config.heartbeat_interval),
            timeout_timer: Timer::new(connection_config.disconnection_timeout_duration),
            ack_manager: AckManager::new(),
            message_manager: MessageManager::new(host_type, channel_kinds),
            host_world_manager: HostWorldManager::new(address, global_world_manager),
            remote_world_manager: RemoteWorldManager::new(),
            local_world_manager: LocalWorldManager::new(),
        }
    }

    // Heartbeats

    /// Record that a message has been sent (to prevent needing to send a
    /// heartbeat)
    pub fn mark_sent(&mut self) {
        self.heartbeat_timer.reset()
    }

    /// Returns whether a heartbeat message should be sent
    pub fn should_send_heartbeat(&self) -> bool {
        self.heartbeat_timer.ringing()
    }

    // Timeouts

    /// Record that a message has been received from a remote host (to prevent
    /// disconnecting from the remote host)
    pub fn mark_heard(&mut self) {
        self.timeout_timer.reset()
    }

    /// Returns whether this connection should be dropped as a result of a
    /// timeout
    pub fn should_drop(&self) -> bool {
        self.timeout_timer.ringing()
    }

    // Acks & Headers

    /// Process an incoming packet, pulling out the packet index number to keep
    /// track of the current RTT, and sending the packet to the AckManager to
    /// handle packet notification events
    pub fn process_incoming_header(
        &mut self,
        header: &StandardHeader,
        packet_notifiables: &mut [&mut dyn PacketNotifiable],
    ) {
        self.ack_manager.process_incoming_header(
            header,
            &mut self.message_manager,
            &mut self.host_world_manager,
            &mut self.local_world_manager,
            packet_notifiables,
        );
    }

    /// Given a packet payload, start tracking the packet via it's index, attach
    /// the appropriate header, and return the packet's resulting underlying
    /// bytes
    pub fn write_outgoing_header(&mut self, packet_type: PacketType, writer: &mut BitWriter) {
        // Add header onto message!
        self.ack_manager
            .next_outgoing_packet_header(packet_type)
            .ser(writer);
    }

    /// Get the next outgoing packet's index
    pub fn next_packet_index(&self) -> PacketIndex {
        self.ack_manager.next_sender_packet_index()
    }

    pub fn has_outgoing_messages(&self) -> bool {
        self.message_manager.has_outgoing_messages()
            || self.host_world_manager.has_outgoing_messages()
    }

    pub fn collect_outgoing_messages(
        &mut self,
        now: &Instant,
        rtt_millis: &f32,
        handle_converter: &dyn EntityHandleConverter<E>,
        message_kinds: &MessageKinds,
    ) {
        let converter = EntityConverter::new(handle_converter, &self.local_world_manager);
        self.host_world_manager.collect_outgoing_messages(
            now,
            rtt_millis,
            &converter,
            message_kinds,
            &mut self.message_manager,
        );
        self.message_manager
            .collect_outgoing_messages(now, rtt_millis);
    }

    fn write_messages(
        &mut self,
        protocol: &Protocol,
        handle_converter: &dyn EntityHandleConverter<E>,
        writer: &mut BitWriter,
        packet_index: PacketIndex,
        has_written: &mut bool,
    ) {
        let converter = EntityConverter::new(handle_converter, &self.local_world_manager);
        self.message_manager.write_messages(
            protocol,
            &converter,
            writer,
            packet_index,
            has_written,
        );
    }

    pub fn write_outgoing_packet<W: WorldRefType<E>>(
        &mut self,
        protocol: &Protocol,
        now: &Instant,
        writer: &mut BitWriter,
        packet_index: PacketIndex,
        world: &W,
        global_world_manager: &dyn GlobalWorldManagerType<E>,
        has_written: &mut bool,
        write_world_events: bool,
    ) {
        // write messages
        {
            self.write_messages(
                &protocol,
                global_world_manager.to_handle_converter(),
                writer,
                packet_index,
                has_written,
            );

            // finish messages
            false.ser(writer);
            writer.release_bits(1);
        }

        if write_world_events {
            // write entity updates
            {
                self.host_world_manager.write_updates(
                    &protocol.component_kinds,
                    now,
                    writer,
                    &packet_index,
                    world,
                    global_world_manager,
                    &self.local_world_manager,
                    has_written,
                );

                // finish updates
                false.ser(writer);
                writer.release_bits(1);
            }

            // write entity actions
            {
                self.host_world_manager.write_actions(
                    &protocol.component_kinds,
                    now,
                    writer,
                    &packet_index,
                    world,
                    global_world_manager,
                    &self.local_world_manager,
                    has_written,
                );

                // finish actions
                false.ser(writer);
                writer.release_bits(1);
            }
        }
    }

    pub fn despawn_all_remote_entities<W: WorldMutType<E>>(
        &mut self,
        global_world_manager: &mut dyn GlobalWorldManagerType<E>,
        world: &mut W,
    ) -> Vec<EntityEvent<E>> {
        let mut output = Vec::new();

        let remote_entities = self.local_world_manager.remote_entities();

        for entity in remote_entities {
            // Generate remove event for each component, handing references off just in
            // case
            for component_kind in world.component_kinds(&entity) {
                if let Some(component) = world.remove_component_of_kind(&entity, &component_kind) {
                    output.push(EntityEvent::<E>::RemoveComponent(entity, component));
                }
            }

            // Despawn from global world manager
            global_world_manager.despawn(&entity);

            // Generate despawn event
            output.push(EntityEvent::DespawnEntity(entity));

            // Despawn entity
            world.despawn_entity(&entity);
        }

        output
    }
}