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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use crate::{
    global::{CallbackReturn, EntityId},
    internal::{conversion::FromBindgen, executor::EXECUTOR, wit},
};

#[cfg(any(feature = "client", feature = "server"))]
use crate::internal::conversion::IntoBindgen;

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
/// Where a message came from.
pub enum Source {
    /// This message came from the runtime.
    Runtime,
    /// This message came from the corresponding serverside module.
    #[cfg(feature = "client")]
    Server,
    /// This message came from the corresponding clientside module and was sent from `user_id`.
    #[cfg(feature = "server")]
    Client {
        /// The user that sent this message.
        user_id: String,
    },
    /// This message came from another module on this side.
    Local(EntityId),
}
impl Source {
    /// Is this message from the runtime?
    pub fn runtime(self) -> bool {
        matches!(self, Source::Runtime)
    }

    #[cfg(feature = "server")]
    /// The user that sent this message, if any.
    pub fn client_user_id(self) -> Option<String> {
        if let Source::Client { user_id } = self {
            Some(user_id)
        } else {
            None
        }
    }

    #[cfg(feature = "server")]
    /// The entity ID of the player that sent this message, if any.
    pub fn client_entity_id(self) -> Option<EntityId> {
        let Some(user_id) = self.client_user_id() else { return None; };
        let Some(player_id) = crate::player::get_by_user_id(&user_id) else { return None; };
        Some(player_id)
    }

    /// The module on this side that sent this message, if any.
    pub fn local(self) -> Option<EntityId> {
        match self {
            Source::Local(id) => Some(id),
            _ => None,
        }
    }
}
impl FromBindgen for wit::guest::Source {
    type Item = Source;

    fn from_bindgen(self) -> Self::Item {
        match self {
            wit::guest::Source::Runtime => Source::Runtime,
            #[cfg(feature = "client")]
            wit::guest::Source::Server => Source::Server,
            #[cfg(feature = "server")]
            wit::guest::Source::Client(user_id) => Source::Client { user_id },
            wit::guest::Source::Local(entity_id) => Source::Local(entity_id.from_bindgen()),

            // cover the other features
            #[cfg(not(feature = "client"))]
            wit::guest::Source::Server => unreachable!(),
            #[cfg(not(feature = "server"))]
            wit::guest::Source::Client(_user_id) => unreachable!(),
        }
    }
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
/// The target for a originating message.
pub enum Target {
    /// A message to all other modules running on this side.
    LocalBroadcast,
    /// A message to a specific module running on this side.
    Local(EntityId),

    // Client
    /// An unreliable transmission to the server.
    ///
    /// Not guaranteed to be received, and must be below one kilobyte.
    #[cfg(feature = "client")]
    ServerUnreliable,
    /// A reliable transmission to the server (guaranteed to be received).
    #[cfg(feature = "client")]
    ServerReliable,

    // Server
    /// An unreliable transmission to all clients.
    ///
    /// Not guaranteed to be received, and must be below one kilobyte.
    #[cfg(feature = "server")]
    ClientBroadcastUnreliable,
    /// A reliable transmission to all clients (guaranteed to be received).
    #[cfg(feature = "server")]
    ClientBroadcastReliable,
    /// An unreliable transmission to a specific client.
    ///
    /// Not guaranteed to be received, and must be below one kilobyte.
    #[cfg(feature = "server")]
    ClientTargetedUnreliable(
        /// The user to send to.
        String,
    ),
    /// A reliable transmission to a specific client (guaranteed to be received).
    #[cfg(feature = "server")]
    ClientTargetedReliable(
        /// The user to send to.
        String,
    ),
}

#[cfg(feature = "client")]
impl IntoBindgen for Target {
    type Item = wit::client_message::Target;

    fn into_bindgen(self) -> Self::Item {
        match self {
            Target::ServerUnreliable => Self::Item::ServerUnreliable,
            Target::ServerReliable => Self::Item::ServerReliable,
            Target::LocalBroadcast => Self::Item::LocalBroadcast,
            Target::Local(id) => Self::Item::Local(id.into_bindgen()),
            #[cfg(feature = "server")]
            _ => unreachable!(),
        }
    }
}

#[cfg(feature = "server")]
impl<'a> IntoBindgen for &'a Target {
    type Item = wit::server_message::Target<'a>;

    fn into_bindgen(self) -> Self::Item {
        match self {
            Target::ClientBroadcastUnreliable => Self::Item::ClientBroadcastUnreliable,
            Target::ClientBroadcastReliable => Self::Item::ClientBroadcastReliable,
            Target::ClientTargetedUnreliable(user_id) => {
                Self::Item::ClientTargetedUnreliable(user_id.as_str())
            }
            Target::ClientTargetedReliable(user_id) => {
                Self::Item::ClientTargetedReliable(user_id.as_str())
            }
            Target::LocalBroadcast => Self::Item::LocalBroadcast,
            Target::Local(id) => Self::Item::Local(id.into_bindgen()),
            #[cfg(feature = "client")]
            _ => unreachable!(),
        }
    }
}

/// Send a message from this module to a specific `target`.
pub fn send<T: Message>(target: Target, data: &T) {
    #[cfg(all(feature = "client", not(feature = "server")))]
    wit::client_message::send(
        target.into_bindgen(),
        T::id(),
        &data.serialize_message().unwrap(),
    );
    #[cfg(all(feature = "server", not(feature = "client")))]
    wit::server_message::send(
        target.into_bindgen(),
        T::id(),
        &data.serialize_message().unwrap(),
    );
    #[cfg(any(
        all(not(feature = "server"), not(feature = "client")),
        all(feature = "server", feature = "client")
    ))]
    let _ = (target, data);
}

/// Handle to a message listener that can be used to stop listening.
pub struct Listener(String, u128);
impl Listener {
    /// Stops listening.
    pub fn stop(self) {
        EXECUTOR.unregister_callback(&self.0, self.1);
    }
}

/// Subscribes to a message.
#[allow(clippy::collapsible_else_if)]
pub fn subscribe<R: CallbackReturn, T: Message>(
    mut callback: impl FnMut(Source, T) -> R + 'static,
) -> Listener {
    let id = T::id();
    wit::message::subscribe(id);
    Listener(
        id.to_string(),
        EXECUTOR.register_callback(
            id.to_string(),
            Box::new(move |source, data| {
                callback(source.clone().from_bindgen(), T::deserialize_message(data)?)
                    .into_result()?;
                Ok(())
            }),
        ),
    )
}

/// Implemented by all messages that can be sent between modules.
pub trait ModuleMessage: Message {
    /// Sends this [Message] to `target`. Wrapper around [self::send].
    fn send(&self, target: Target) {
        self::send(target, self)
    }

    /// Sends a message to every module on this side.
    fn send_local_broadcast(&self) {
        self.send(Target::LocalBroadcast)
    }

    /// Sends a message to a specific module on this side.
    fn send_local(&self, module_id: EntityId) {
        self.send(Target::Local(module_id))
    }

    #[cfg(feature = "client")]
    /// Sends an unreliable message to the server.
    ///
    /// See [Target::ServerUnreliable] for specifics.
    fn send_server_unreliable(&self) {
        self.send(Target::ServerUnreliable)
    }

    #[cfg(feature = "client")]
    /// Sends a reliable message to the server.
    ///
    /// See [Target::ServerReliable] for specifics.
    fn send_server_reliable(&self) {
        self.send(Target::ServerReliable)
    }

    #[cfg(feature = "server")]
    /// Sends an unreliable message to all clients.
    ///
    /// See [Target::ClientBroadcastUnreliable] for specifics.
    fn send_client_broadcast_unreliable(&self) {
        self.send(Target::ClientBroadcastUnreliable)
    }

    #[cfg(feature = "server")]
    /// Sends a reliable message to all clients.
    ///
    /// See [Target::ClientBroadcastReliable] for specifics.
    fn send_client_broadcast_reliable(&self) {
        self.send(Target::ClientBroadcastReliable)
    }

    #[cfg(feature = "server")]
    /// Sends an unreliable message to a specific client.
    ///
    /// See [Target::ClientTargetedUnreliable] for specifics.
    fn send_client_targeted_unreliable(&self, user_id: String) {
        self.send(Target::ClientTargetedUnreliable(user_id))
    }

    #[cfg(feature = "server")]
    /// Sends a reliable message to a specific client.
    ///
    /// See [Target::ClientTargetedReliable] for specifics.
    fn send_client_targeted_reliable(&self, user_id: String) {
        self.send(Target::ClientTargetedReliable(user_id))
    }

    /// Subscribes to this [Message]. Wrapper around [self::subscribe].
    fn subscribe<R: CallbackReturn>(callback: impl FnMut(Source, Self) -> R + 'static) -> Listener {
        self::subscribe(callback)
    }
}

/// Implemented by all messages sent from the runtime.
pub trait RuntimeMessage: Message {
    /// Subscribes to this [Message]. Wrapper around [self::subscribe].
    fn subscribe<R: CallbackReturn>(mut callback: impl FnMut(Self) -> R + 'static) -> Listener {
        self::subscribe(move |_source, msg| callback(msg))
    }
}

mod serde {
    pub use ambient_project_rt::message_serde::*;

    use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

    use crate::global::EntityId;

    impl MessageSerde for EntityId {
        fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
            output.write_u64::<BigEndian>(self.id0)?;
            output.write_u64::<BigEndian>(self.id1)?;
            Ok(())
        }

        fn deserialize_message_part(
            input: &mut dyn std::io::Read,
        ) -> Result<Self, MessageSerdeError> {
            let (id0, id1) = (
                input.read_u64::<BigEndian>()?,
                input.read_u64::<BigEndian>()?,
            );
            Ok(Self { id0, id1 })
        }
    }
}
pub use serde::*;