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
use std::io::{Cursor, Write};

use actix::Message as ActixMessage;
use libflate::zlib::Encoder;
use prost::Message as ProstMesssage;

use crate::libs::{Ndarray, Vec3};

/// Protocol buffers generated by `prost.rs`.
pub mod protocols {
    include!(concat!(env!("OUT_DIR"), "/protocol.rs"));
}

pub use protocols::Message;

pub type MessageType = protocols::message::Type;

impl ActixMessage for Message {
    type Result = ();
}

impl Message {
    /// Create a new protobuf message with the idiomatic Builder pattern.
    pub fn new(r#type: &MessageType) -> MessageBuilder {
        MessageBuilder {
            r#type: r#type.to_owned(),
            ..Default::default()
        }
    }
}

/// Encode message into protocol buffers.
pub fn encode_message(message: &Message) -> Vec<u8> {
    let mut buf = Vec::new();

    buf.reserve(message.encoded_len());
    message.encode(&mut buf).unwrap();

    if buf.len() > 1024 {
        let mut encoder = Encoder::new(Vec::new()).unwrap();
        encoder.write_all(buf.as_slice()).unwrap();
        buf = encoder.finish().into_result().unwrap();
    }

    buf
}

/// Decode protocol buffers into a message struct.
pub fn decode_message(buf: &[u8]) -> Result<Message, prost::DecodeError> {
    Message::decode(&mut Cursor::new(buf))
}

/// Protocol buffer compatible geometry data structure.
#[derive(Debug, Clone, Default)]
pub struct Geometry {
    pub positions: Vec<f32>,
    pub indices: Vec<i32>,
    pub uvs: Vec<f32>,
    pub lights: Vec<i32>,
}

/// Protocol buffer compatible mesh data structure.
#[derive(Debug, Clone, Default)]
pub struct MeshProtocol {
    pub level: i32,
    pub opaque: Option<Geometry>,
    pub transparent: Option<Geometry>,
}

/// Protocol buffer compatible chunk data structure.
#[derive(Debug, Clone, Default)]
pub struct ChunkProtocol {
    pub x: i32,
    pub z: i32,
    pub id: String,
    pub meshes: Vec<MeshProtocol>,
    pub voxels: Option<Ndarray<u32>>,
    pub lights: Option<Ndarray<u32>>,
}

/// Protocol buffer compatible peer data structure.
#[derive(Debug, Clone, Default)]
pub struct PeerProtocol {
    pub id: String,
    pub username: String,
    pub metadata: String,
}

/// Protobuf buffer compatible update data structure.
#[derive(Debug, Clone, Default)]
pub struct UpdateProtocol {
    pub vx: i32,
    pub vy: i32,
    pub vz: i32,
    pub voxel: u32,
    pub light: u32,
}

/// Protocol buffer compatible entity data structure.
#[derive(Debug, Clone, Default)]
pub struct EntityProtocol {
    pub id: String,
    pub r#type: String,
    pub metadata: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct ChatMessageProtocol {
    pub r#type: String,
    pub sender: String,
    pub body: String,
}

#[derive(Debug, Clone, Default)]
pub struct EventProtocol {
    pub name: String,
    pub payload: String,
}

/// Builder for a protocol buffer message.
#[derive(Default)]
pub struct MessageBuilder {
    r#type: MessageType,

    json: Option<String>,
    text: Option<String>,

    chat: Option<ChatMessageProtocol>,

    peers: Option<Vec<PeerProtocol>>,
    entities: Option<Vec<EntityProtocol>>,
    events: Option<Vec<EventProtocol>>,
    chunks: Option<Vec<ChunkProtocol>>,
    updates: Option<Vec<UpdateProtocol>>,
}

/// Convert a `Vec3` to protocol buffer `Vector3`.
fn vec3_to_vector3(vec3: &Option<Vec3<f32>>) -> Option<protocols::Vector3> {
    vec3.as_ref().map(|vec3| protocols::Vector3 {
        x: vec3.0,
        y: vec3.1,
        z: vec3.2,
    })
}

impl MessageBuilder {
    /// Configure the json data of the protocol.
    pub fn json(mut self, json: &str) -> Self {
        self.json = Some(json.to_owned());
        self
    }

    /// Configure the text data of the protocol.
    pub fn text(mut self, text: &str) -> Self {
        self.text = Some(text.to_owned());
        self
    }

    /// Configure the peers data of the protocol.
    pub fn peers(mut self, peers: &[PeerProtocol]) -> Self {
        self.peers = Some(peers.to_vec());
        self
    }

    /// Configure the entities data of the protocol.
    pub fn entities(mut self, entities: &[EntityProtocol]) -> Self {
        self.entities = Some(entities.to_vec());
        self
    }

    /// Configure the set of events to send in this message.
    pub fn events(mut self, events: &[EventProtocol]) -> Self {
        self.events = Some(events.to_vec());
        self
    }

    /// Configure the chunks data of the protocol.
    pub fn chunks(mut self, chunks: &[ChunkProtocol]) -> Self {
        self.chunks = Some(chunks.to_vec());
        self
    }

    /// Configure the voxel update data of the protocol.
    pub fn updates(mut self, updates: &[UpdateProtocol]) -> Self {
        self.updates = Some(updates.to_vec());
        self
    }

    /// Configure the chat data of the protocol.
    pub fn chat(mut self, chat: ChatMessageProtocol) -> Self {
        self.chat = Some(chat);
        self
    }

    /// Create a protocol buffer message.
    pub fn build(self) -> Message {
        let mut message = protocols::Message {
            r#type: self.r#type as i32,
            ..Default::default()
        };

        message.json = self.json.unwrap_or_default();
        message.text = self.text.unwrap_or_default();

        if let Some(peers) = self.peers {
            message.peers = peers
                .into_iter()
                .map(|peer| protocols::Peer {
                    id: peer.id,
                    username: peer.username,
                    metadata: peer.metadata,
                })
                .collect();
        }

        if let Some(entities) = self.entities {
            message.entities = entities
                .into_iter()
                .map(|entity| protocols::Entity {
                    id: entity.id,
                    r#type: entity.r#type,
                    metadata: entity.metadata.unwrap_or_default(),
                })
                .collect();
        }

        if let Some(events) = self.events {
            message.events = events
                .into_iter()
                .map(|event| protocols::Event {
                    name: event.name,
                    payload: event.payload,
                })
                .collect()
        }

        if let Some(chunks) = self.chunks {
            message.chunks = chunks
                .into_iter()
                .map(|chunk| protocols::Chunk {
                    id: chunk.id,
                    meshes: chunk
                        .meshes
                        .into_iter()
                        .map(|mesh| {
                            let opaque = mesh.opaque.as_ref();
                            let transparent = mesh.transparent.as_ref();

                            protocols::Mesh {
                                level: mesh.level,
                                opaque: opaque.map(|opaque| protocols::Geometry {
                                    indices: opaque.indices.to_owned(),
                                    positions: opaque.positions.to_owned(),
                                    lights: opaque.lights.to_owned(),
                                    uvs: opaque.uvs.to_owned(),
                                }),
                                transparent: transparent.map(|transparent| protocols::Geometry {
                                    indices: transparent.indices.to_owned(),
                                    positions: transparent.positions.to_owned(),
                                    lights: transparent.lights.to_owned(),
                                    uvs: transparent.uvs.to_owned(),
                                }),
                            }
                        })
                        .collect(),
                    lights: chunk.lights.unwrap_or_default().data,
                    voxels: chunk.voxels.unwrap_or_default().data,
                    x: chunk.x,
                    z: chunk.z,
                })
                .collect();
        }

        if let Some(updates) = self.updates {
            message.updates = updates
                .into_iter()
                .map(|update| protocols::Update {
                    vx: update.vx,
                    vy: update.vy,
                    vz: update.vz,
                    light: update.light,
                    voxel: update.voxel,
                })
                .collect()
        }

        if let Some(chat) = self.chat {
            message.chat = Some(protocols::ChatMessage {
                body: chat.body,
                sender: chat.sender,
                r#type: chat.r#type,
            });
        }

        message
    }
}