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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
mod models;
mod session;

use std::time::{Duration, Instant};

use actix::{
    Actor, AsyncContext, Context, Handler, Message as ActixMessage, MessageResult, Recipient,
};
use fern::colors::{Color, ColoredLevelConfig};
use hashbrown::HashMap;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use log::{info, warn};
use nanoid::nanoid;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;

use crate::{
    errors::AddWorldError,
    world::{Registry, World, WorldConfig},
    ChunkStatus, Mesher, MessageQueue, Stats,
};

pub use models::*;
pub use session::*;

#[derive(Serialize, Deserialize)]
pub struct OnJoinRequest {
    world: String,
    username: String,
}

#[derive(Serialize, Deserialize)]
struct OnActionRequest {
    action: String,
    data: Value,
}

type ServerInfoHandle = fn(&Server) -> Value;

fn default_info_handle(server: &Server) -> Value {
    let mut info = HashMap::new();

    info.insert(
        "lost_sessions".to_owned(),
        json!(server.lost_sessions.len()),
    );

    let mut connections = HashMap::new();

    for (id, (_, world)) in server.connections.iter() {
        connections.insert(id.to_owned(), json!(world));
    }

    info.insert("connections".to_owned(), json!(connections));

    let mut transports = vec![];

    for (id, _) in server.transport_sessions.iter() {
        transports.push(id.to_owned());
    }

    info.insert("transports".to_owned(), json!(transports));

    let mut worlds = HashMap::new();

    for (name, world) in server.worlds.iter() {
        let mut world_info = HashMap::new();

        {
            let clients = world.clients();
            world_info.insert(
                "clients".to_owned(),
                json!(clients
                    .values()
                    .map(|client| json!({
                        "id": client.id.to_owned(),
                        "username": client.username.to_owned(),
                    }))
                    .collect::<Vec<_>>()),
            );
        }

        {
            let config = world.config();
            world_info.insert("config".to_owned(), json!(*config));
        }

        {
            let stats = world.read_resource::<Stats>();
            let mut stats_info = HashMap::new();

            stats_info.insert("tick".to_owned(), json!(stats.tick));
            stats_info.insert("delta".to_owned(), json!(stats.delta));

            world_info.insert("stats".to_owned(), json!(stats_info));
        }

        {
            let chunks = world.chunks();
            let pipeline = world.pipeline();
            let mesher = world.read_resource::<Mesher>();

            let mut generating: i32 = 0;
            let mut meshing: i32 = 0;
            let mut ready: i32 = 0;

            for chunk in chunks.map.values() {
                match chunk.status {
                    ChunkStatus::Generating(_) => generating += 1,
                    ChunkStatus::Meshing => meshing += 1,
                    ChunkStatus::Ready => ready += 1,
                }
            }

            world_info.insert(
                "chunks".to_owned(),
                json!({
                    "count": chunks.map.len(),
                    "generating": generating,
                    "meshing": meshing,
                    "ready": ready,
                    "pipeline_chunks": pipeline.chunks,
                    "pipeline_queue": pipeline.queue,
                    "mesher_chunks": mesher.map,
                    "mesher_queue": mesher.queue,
                    "active_voxels": chunks.active_voxels.len()
                }),
            );
        }

        {
            let pipeline = world.pipeline();

            let pipeline_info = json!({
                "count": json!(pipeline.chunks.len()),
                "stages": json!(
                    pipeline
                        .stages
                        .iter()
                        .map(|stage| json!(stage.name()))
                        .collect::<Vec<_>>()
                )
            });

            world_info.insert("pipeline".to_owned(), pipeline_info);
        }

        worlds.insert(name.to_owned(), json!(world_info));
    }

    info.insert("worlds".to_owned(), json!(worlds));

    serde_json::to_value(info).unwrap()
}

/// A websocket server for Voxelize, holds all worlds data, and runs as a background
/// system service.
pub struct Server {
    /// The port that this voxelize server is running on.
    pub port: u16,

    /// The address that this voxelize server is running on.
    pub addr: String,

    /// Whether or not if the socket server has started as a system service.
    pub started: bool,

    /// Static folder to serve from.
    pub serve: String,

    /// Whether the server should show debug information.
    pub debug: bool,

    /// Interval to tick the server at.
    pub interval: u64,

    /// A secret to join the server.
    pub secret: Option<String>,

    /// A map of all the worlds.
    pub worlds: HashMap<String, World>,

    /// Registry of the server.
    pub registry: Registry,

    /// Session IDs and addresses who haven't connected to a world.
    pub lost_sessions: HashMap<String, Recipient<EncodedMessage>>,

    /// Transport sessions, not connect to any particular world.
    pub transport_sessions: HashMap<String, Recipient<EncodedMessage>>,

    /// What world each client ID is connected to, client ID <-> world ID.
    pub connections: HashMap<String, (Recipient<EncodedMessage>, String)>,

    /// The information sent to the client when requested.
    info_handle: ServerInfoHandle,

    /// The handler for `Action`s.
    action_handles: HashMap<String, Arc<dyn Fn(Value, &mut Server)>>,
}

impl Server {
    /// Create a new Voxelize server instance used to host all the worlds.
    pub fn new() -> ServerBuilder {
        ServerBuilder::new()
    }

    /// Add a world instance to the server. Different worlds have different configurations, and can hold
    /// their own set of clients within. If the server has already started, the added world will be
    /// started right away.
    pub fn add_world(&mut self, mut world: World) -> Result<&mut World, AddWorldError> {
        let name = world.name.clone();

        let saving = world.config().saving;
        let save_dir = world.config().save_dir.clone();

        world.ecs_mut().insert(self.registry.clone());

        if self.worlds.insert(name.to_owned(), world).is_some() {
            return Err(AddWorldError);
        };

        info!(
            "🌎 World created: {} ({})",
            name,
            if saving {
                format!("on-disk @ {}", save_dir)
            } else {
                "in-memory".to_owned()
            }
        );

        Ok(self.worlds.get_mut(&name).unwrap())
    }

    /// Create a world in the server. Different worlds have different configurations, and can hold
    /// their own set of clients within. If the server has already started, the added world will be
    /// started right away.
    pub fn create_world(
        &mut self,
        name: &str,
        config: &WorldConfig,
    ) -> Result<&mut World, AddWorldError> {
        let mut world = World::new(name, config);
        world.ecs_mut().insert(self.registry.clone());
        self.add_world(world)
    }

    /// Get a world reference by name.
    pub fn get_world(&self, world_name: &str) -> Option<&World> {
        self.worlds.get(world_name)
    }

    /// Get a mutable world reference by name.
    pub fn get_world_mut(&mut self, world_name: &str) -> Option<&mut World> {
        self.worlds.get_mut(world_name)
    }

    /// Get the information of the server
    pub fn get_info(&mut self) -> Value {
        (self.info_handle)(self)
    }

    /// Handler for client's message.
    pub(crate) fn on_request(&mut self, id: &str, data: Message) -> Option<String> {
        if data.r#type == MessageType::Join as i32 {
            let json: OnJoinRequest = serde_json::from_str(&data.json)
                .expect("`on_join` error. Could not read JSON string.");

            if !self.lost_sessions.contains_key(id) {
                return Some(format!(
                    "Client at {} is already in world: {}",
                    id, json.world
                ));
            }

            if let Some(world) = self.worlds.get_mut(&json.world) {
                if let Some(addr) = self.lost_sessions.remove(id) {
                    world.add_client(id, &json.username, &addr);
                    self.connections.insert(id.to_owned(), (addr, json.world));
                    return None;
                }

                return Some("Something went wrong with joining. Maybe you called .join twice on the client?".to_owned());
            }

            return Some(format!(
                "ID {} is attempting to connect to a non-existent world!",
                id
            ));
        } else if data.r#type == MessageType::Leave as i32 {
            if let Some(world) = self.worlds.get_mut(&data.text) {
                let (addr, _) = self.connections.remove(id).unwrap();
                self.lost_sessions.insert(id.to_owned(), addr);

                world.remove_client(id);
            }

            return None;
        } else if data.r#type == MessageType::Action as i32 {
            self.on_action(id, &data);

            return None;
        } else if data.r#type == MessageType::Transport as i32
            || self.transport_sessions.contains_key(id)
        {
            if !self.transport_sessions.contains_key(id) {
                return Some(
                    "Someone who isn't a transport server is attempting to transport.".to_owned(),
                );
            }

            if let Some(world) = self.get_world_mut(&data.text) {
                world.on_request(id, data);

                return None;
            } else {
                return Some(
                    "Transport message did not have a world. Use the 'text' field.".to_owned(),
                );
            }
        }

        let connection = self.connections.get(id);
        if connection.is_none() {
            return Some("You are not connected to a world!".to_owned());
        }

        let (_, world_name) = connection.unwrap().to_owned();

        if let Some(world) = self.get_world_mut(&world_name) {
            world.on_request(id, data);
        }

        None
    }
    /// Prepare all worlds on the server to start.
    pub fn prepare(&mut self) {
        for world in self.worlds.values_mut() {
            world.prepare();
        }

        self.preload();
    }

    /// Preload all the worlds.
    pub(crate) fn preload(&mut self) {
        let m = MultiProgress::new();
        let sty = ProgressStyle::with_template(
            "[{elapsed_precise}] [{bar:40.cyan/blue}] {msg} {spinner:.green} {percent:>7}%",
        )
        .unwrap()
        .progress_chars("#>-");

        let mut bars = vec![];

        for world in self.worlds.values_mut() {
            if !world.config().preload {
                bars.push(None);
                continue;
            }

            world.preload();

            let bar = m.insert_from_back(0, ProgressBar::new(100));
            bar.set_message(world.name.clone());
            bar.set_style(sty.clone());
            bar.set_position(0);
            bars.push(Some(bar));
        }

        let start = Instant::now();

        loop {
            let mut done = true;

            for (i, world) in self.worlds.values_mut().enumerate() {
                if bars[i].is_none() || !world.config().preload {
                    continue;
                }

                let bar = bars[i].as_mut().unwrap();

                if !world.preloading || world.preload_progress >= 1.0 {
                    bar.finish_and_clear();
                    continue;
                }

                world.tick();

                let at = (world.preload_progress * 100.0) as u64;

                done = false;
                bar.set_position(at);
            }

            if done {
                m.clear().unwrap();
                break;
            }
        }

        let preload_len = self
            .worlds
            .values()
            .filter(|world| world.config().preload)
            .collect::<Vec<&World>>()
            .len();

        info!(
            "✅ Total of {} world{} preloaded in {}s",
            preload_len,
            if preload_len == 1 { "" } else { "s" },
            (Instant::now() - start).as_millis() as f64 / 1000.0
        );
    }

    /// Tick every world on this server.
    pub(crate) fn tick(&mut self) {
        for world in self.worlds.values_mut() {
            world.tick();
        }
    }

    /// Setup Fern for debug logging.
    fn setup_logger() {
        fern::Dispatch::new()
            .format(|out, message, record| {
                let colors = ColoredLevelConfig::new().info(Color::Green);

                out.finish(format_args!(
                    "{} [{}] [{}]: {}",
                    chrono::Local::now().format("[%H:%M:%S]"),
                    colors.color(record.level()),
                    record.target(),
                    message
                ))
            })
            .level(log::LevelFilter::Debug)
            .level_for("tungstenite", log::LevelFilter::Info)
            .chain(std::io::stdout())
            .apply()
            .expect("Fern did not run successfully");
    }

    pub fn set_action_handle<F: Fn(Value, &mut Server) + 'static>(
        &mut self,
        action: &str,
        handle: F,
    ) {
        self.action_handles
            .insert(action.to_lowercase(), Arc::new(handle));
    }

    /// Handler for `Action` type messages.
    fn on_action(&mut self, _: &str, data: &Message) {
        let json: OnActionRequest = serde_json::from_str(&data.json)
            .expect("`on_action` error. Could not read JSON string.");
        let action = json.action.to_lowercase();

        info!("{:?}", &self.action_handles.keys());
        info!("{:?}", &action);

        if !self.action_handles.contains_key(&action) {
            warn!("`Action` type messages received, but no action handler set.");
            return;
        }

        let handle = self.action_handles.get(&action).unwrap().to_owned();

        handle(json.data, self);
    }
}

/// New chat session is created
#[derive(ActixMessage)]
#[rtype(result = "String")]
pub struct Connect {
    pub id: Option<String>,
    pub is_transport: bool,
    pub addr: Recipient<EncodedMessage>,
}

#[derive(ActixMessage, Clone)]
#[rtype(result = "()")]
pub struct EncodedMessage(pub Vec<u8>);

/// Session is disconnected
#[derive(ActixMessage)]
#[rtype(result = "()")]
pub struct Disconnect {
    pub id: String,
}

#[derive(ActixMessage)]
#[rtype(result = "Value")]
pub struct Info;

#[derive(ActixMessage)]
#[rtype(result = "f32")]
pub struct Time(pub String);

/// Send message to specific world
#[derive(ActixMessage)]
#[rtype(result = "Option<String>")]
pub struct ClientMessage {
    /// Id of the client session
    pub id: String,

    /// Protobuf message
    pub data: Message,
}

/// Make actor from `ChatServer`
impl Actor for Server {
    /// We are going to use simple Context, we just need ability to communicate
    /// with other actors.
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        ctx.run_interval(Duration::from_millis(self.interval), |act, _| {
            act.tick();
        });
    }
}

/// Handler for Connect message.
///
/// Register new session and assign unique id to this session
impl Handler<Connect> for Server {
    type Result = MessageResult<Connect>;

    fn handle(&mut self, msg: Connect, _: &mut Context<Self>) -> Self::Result {
        // notify all users in same room
        // self.send_message("Main", "Someone joined", 0);

        // register session with random id
        let id = if msg.id.is_none() {
            nanoid!()
        } else {
            msg.id.unwrap()
        };

        if msg.is_transport {
            // Send init messages of the worlds to the transport.
            self.worlds
                .values_mut()
                .for_each(|world| world.add_transport(&id, &msg.addr));

            self.transport_sessions.insert(id.to_owned(), msg.addr);

            return MessageResult(id);
        }

        if self.lost_sessions.contains_key(&id) {
            return MessageResult(nanoid!());
        }

        self.lost_sessions.insert(id.to_owned(), msg.addr);

        // send id back
        MessageResult(id)
    }
}

/// Handler for Disconnect message.
impl Handler<Disconnect> for Server {
    type Result = ();

    fn handle(&mut self, msg: Disconnect, _: &mut Context<Self>) {
        if let Some((_, world_name)) = self.connections.remove(&msg.id) {
            if let Some(world) = self.worlds.get_mut(&world_name) {
                world.remove_client(&msg.id);
            }
        }

        if let Some(_) = self.transport_sessions.remove(&msg.id) {
            self.worlds.values_mut().for_each(|world| {
                world.remove_transport(&msg.id);
            });

            info!("A transport server connection has ended.")
        }

        self.lost_sessions.remove(&msg.id);
    }
}

/// Handler for server info request.
impl Handler<Info> for Server {
    type Result = MessageResult<Info>;

    fn handle(&mut self, _: Info, _: &mut Context<Self>) -> Self::Result {
        MessageResult(self.get_info())
    }
}

impl Handler<Time> for Server {
    type Result = MessageResult<Time>;

    fn handle(&mut self, Time(world_name): Time, _: &mut Context<Self>) -> Self::Result {
        let world = self.worlds.get(&world_name);

        if world.is_none() {
            return MessageResult(0.0);
        }

        let world = world.unwrap();

        MessageResult(world.read_resource::<Stats>().time)
    }
}

/// Handler for Message message.
impl Handler<ClientMessage> for Server {
    type Result = Option<String>;

    fn handle(&mut self, msg: ClientMessage, _: &mut Context<Self>) -> Self::Result {
        self.on_request(&msg.id, msg.data)
    }
}

const DEFAULT_DEBUG: bool = true;
const DEFAULT_PORT: u16 = 4000;
const DEFAULT_ADDR: &str = "0.0.0.0";
const DEFAULT_SERVE: &str = "";
const DEFAULT_INTERVAL: u64 = 8;

/// Builder for a voxelize server.
pub struct ServerBuilder {
    port: u16,
    debug: bool,
    addr: String,
    serve: String,
    interval: u64,
    secret: Option<String>,
    registry: Option<Registry>,
}

impl ServerBuilder {
    /// Create a new server builder instance.
    pub fn new() -> Self {
        Self {
            debug: DEFAULT_DEBUG,
            port: DEFAULT_PORT,
            addr: DEFAULT_ADDR.to_owned(),
            serve: DEFAULT_SERVE.to_owned(),
            interval: DEFAULT_INTERVAL,
            secret: None,
            registry: None,
        }
    }

    /// Configure the port to the voxelize server.
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Configure the address of the voxelize server.
    pub fn addr(mut self, addr: &str) -> Self {
        self.addr = addr.to_owned();
        self
    }

    /// Configure whether or not the voxelize server should be in debug mode.
    pub fn debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }

    /// Configure the static folder to serve.
    pub fn serve(mut self, serve: &str) -> Self {
        self.serve = serve.to_owned();
        self
    }

    /// Configure the interval for the server to tick at.
    pub fn interval(mut self, interval: u64) -> Self {
        self.interval = interval;
        self
    }

    /// Configure the secret for the server to be able to join.
    pub fn secret(mut self, secret: &str) -> Self {
        self.secret = Some(secret.to_owned());
        self
    }

    /// Configure the block registry of the server. Once a registry is configured, mutating it wouldn't
    /// change the server's block list.
    pub fn registry(mut self, registry: &Registry) -> Self {
        self.registry = Some(registry.to_owned());
        self
    }

    /// Instantiate a voxelize server instance.
    pub fn build(self) -> Server {
        let mut registry = self.registry.unwrap_or(Registry::new());
        registry.generate();

        if self.debug {
            Server::setup_logger();
        }

        Server {
            port: self.port,
            addr: self.addr,
            serve: self.serve,
            debug: self.debug,
            interval: self.interval,
            secret: self.secret,

            registry,

            started: false,

            connections: HashMap::default(),
            lost_sessions: HashMap::default(),
            transport_sessions: HashMap::default(),
            worlds: HashMap::default(),
            info_handle: default_info_handle,
            action_handles: HashMap::default(),
        }
    }
}