-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.sunder
525 lines (449 loc) · 19 KB
/
main.sunder
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
import "c";
import "std";
import "bubby";
import "nbnet";
import "raylib";
import "util.sunder";
import "shared.sunder";
import "server.sunder";
import "client.sunder";
struct local_client_message_sender {
# Server state immediately updated from client messages.
var server: *server_state;
# Server connection passed to the function updating server state from
# client messages. Required for the server to send responses.
var connection: *connection;
func send(self: *local_client_message_sender, message: *client_message, reliability: reliability) void {
# Reliability of the message delivery is ignored.
reliability;
# Serialize and deserialize the message as if it were being sent over a
# non-local connection. Ensures to/from bubby routines work correctly.
var message = message.*.to_bubby();
defer message.fini();
#std::print_format_line(std::err(), "INCOMING LOCAL CLIENT MESSAGE STRING: {}", (:[]std::formatter)[std::formatter::init[[bubby::value]](&message)]);
var message = client_message::init_from_bubby(&message);
defer message.fini();
# Update the local server based on the deserialized client message.
self.*.server.*.update_from_client_message(&message, self.*.connection);
}
}
struct local_server_message_sender {
# Client state immediately updated from server messages.
var client: *client_state;
func send(self: *local_server_message_sender, message: *server_message, reliability: reliability) void {
# Reliability of the message delivery is ignored.
reliability;
# Serialize and deserialize the message as if it were being sent over a
# non-local connection. Ensures to/from bubby routines work correctly.
var message = message.*.to_bubby();
defer message.fini();
#std::print_format_line(std::err(), "INCOMING LOCAL SERVER MESSAGE STRING: {}", (:[]std::formatter)[std::formatter::init[[bubby::value]](&message)]);
var message = server_message::init_from_bubby(&message);
defer message.fini();
# Update the local client based on the deserialized server message.
self.*.client.*.update_from_server_message(&message);
}
}
struct nbnet_client_message_sender {
var connected: bool;
func init() nbnet_client_message_sender {
return (:nbnet_client_message_sender){
.connected = false,
};
}
func send(self: *nbnet_client_message_sender, message: *client_message, reliability: reliability) void {
if not self.*.connected {
std::print_line(std::err(), "error: failed to send client message (not connected to server)");
return;
}
var value = message.*.to_bubby();
defer value.fini();
var string = std::string::init();
defer string.fini();
var writer = std::writer::init[[std::string]](&string);
std::print_format(writer, "{}", (:[]std::formatter)[std::formatter::init[[bubby::value]](&value)]);
var data = string.data();
var count = string.count();
#std::print_format_line(std::err(), "CLIENT MESSAGE STRING: {}", (:[]std::formatter)[std::formatter::init[[[]byte]](&data)]);
#std::print_format_line(std::err(), "CLIENT MESSAGE LENGTH: {}", (:[]std::formatter)[std::formatter::init[[usize]](&count)]);
var outgoing = ::message::create();
outgoing.*.len = (:uint)count;
std::slice[[byte]]::copy(outgoing.*.buf[0:count], data);
var err: sint = uninit;
switch reliability {
::reliability::RELIABILE {
err = NBN_GameClient_SendReliableMessage(::message::TYPE, (:*any)outgoing);
}
::reliability::UNRELIABILE {
err = NBN_GameClient_SendUnreliableMessage(::message::TYPE, (:*any)outgoing);
}
}
if err < 0 {
std::print_line(std::err(), "error: failed to send client message");
}
}
}
struct nbnet_server_message_sender {
var handle: NBN_ConnectionHandle; # Client handle (zero -> disconnected)
func init(handle: NBN_ConnectionHandle) nbnet_server_message_sender {
return (:nbnet_server_message_sender){
.handle = handle,
};
}
func send(self: *nbnet_server_message_sender, message: *server_message, reliability: reliability) void {
if self.*.handle == 0 {
return;
}
var value = message.*.to_bubby();
defer value.fini();
var string = std::string::init();
defer string.fini();
var writer = std::writer::init[[std::string]](&string);
std::print_format(writer, "{}", (:[]std::formatter)[std::formatter::init[[bubby::value]](&value)]);
var data = string.data();
var count = string.count();
#std::print_format_line(std::err(), "SERVER MESSAGE STRING: {}", (:[]std::formatter)[std::formatter::init[[[]byte]](&data)]);
#std::print_format_line(std::err(), "SERVER MESSAGE LENGTH: {}", (:[]std::formatter)[std::formatter::init[[usize]](&count)]);
var outgoing = ::message::create();
outgoing.*.len = (:uint)count;
std::slice[[byte]]::copy(outgoing.*.buf[0:count], data);
var err: sint = uninit;
switch reliability {
::reliability::RELIABILE {
err = NBN_GameServer_SendReliableMessageTo(self.*.handle, ::message::TYPE, outgoing);
}
::reliability::UNRELIABILE {
err = NBN_GameServer_SendUnreliableMessageTo(self.*.handle, ::message::TYPE, outgoing);
}
}
if err < 0 {
std::print_line(std::err(), "error: failed to send server message");
}
}
}
enum network {
LOCAL;
CLIENT;
SERVER;
}
func raylib_init() void {
SetTraceLogLevel(LOG_WARNING);
SetConfigFlags(FLAG_MSAA_4X_HINT);
InitWindow(960, 720, startof("NATAC"));
InitAudioDevice();
SetTargetFPS(60);
}
func raylib_fini() void {
CloseAudioDevice();
CloseWindow();
}
func run_local(debug: bool) void {
raylib_init();
defer raylib_fini();
var sstate = server_state::init();
defer sstate.fini();
var cstate = client_state::init();
defer cstate.fini();
cstate.debug = debug;
cstate.connected = true;
var smessage_sender = (:local_server_message_sender){
.client = &cstate,
};
sstate.connections.push((:connection){
.player = std::optional[[player]]::EMPTY,
.sender = message_sender[[server_message]]::init[[local_server_message_sender]](&smessage_sender)
});
var connection = &sstate.connections.data()[0]; # The one and only connection.
var cmessage_sender = (:local_client_message_sender){
.server = &sstate,
.connection = connection,
};
var cmessage_sender = message_sender[[client_message]]::init[[local_client_message_sender]](&cmessage_sender);
for not WindowShouldClose() {
server_update(&sstate);
client_update(&cstate, &cmessage_sender);
client_render(&cstate);
}
}
func run_client(debug: bool, address: std::optional[[*byte]]) void {
raylib_init();
defer raylib_fini();
var cstate = client_state::init();
defer cstate.fini();
cstate.debug = debug;
for not WindowShouldClose() and address.is_empty() {
client_pre_connect_update(&cstate, &address);
client_pre_connect_render(&cstate);
}
if WindowShouldClose() {
return;
}
NBN_Log_SetIsEnabled(NBN_LogType::NBN_LOG_TRACE, false);
NBN_Log_SetIsEnabled(NBN_LogType::NBN_LOG_DEBUG, false);
NBN_Driver_Init();
var address = address.value();
var port = 31415u16;
if NBN_GameClient_StartEx(startof("natac"), address, port, std::ptr[[uint8_t]]::NULL, 0) < 0 {
std::print_line(std::err(), "error: failed to start the nbnet client");
std::exit(std::EXIT_FAILURE);
}
defer NBN_GameClient_Stop();
NBN_GameClient_RegisterMessage(
message::TYPE,
(:NBN_MessageBuilder)message::create,
(:NBN_MessageDestructor)message::destroy,
(:NBN_MessageSerializer)message::serialize);
var client_message_sender = nbnet_client_message_sender::init();
var message_sender = message_sender[[client_message]]::init[[nbnet_client_message_sender]](&client_message_sender);
for not WindowShouldClose() {
for true {
var ev = NBN_GameClient_Poll();
if ev < 0 {
std::print_line(std::err(), "error: failed to poll nbnet event");
break;
}
if ev == NBN_NO_EVENT {
break;
}
if ev == NBN_CONNECTED {
std::print_line(std::err(), "info: connected to server");
cstate.connected = true;
client_message_sender.connected = true;
}
if ev == NBN_DISCONNECTED {
std::print_line(std::err(), "info: disconnected from server");
cstate.connected = false;
client_message_sender.connected = false;
if NBN_GameClient_GetServerCloseCode() == BUSY_CODE {
std::print_line(std::err(), "error: server sent busy code");
}
break;
}
if ev == NBN_MESSAGE_RECEIVED {
var info = NBN_GameClient_GetMessageInfo();
assert info.type_ == message::TYPE;
var incoming = (:*message)info.data;
var count = (:usize)incoming.*.len;
var data = (:[]byte){(:*byte)&incoming.*.buf[0], count};
#std::print_format_line(std::err(), "INCOMING SERVER MESSAGE STRING: {}", (:[]std::formatter)[std::formatter::init[[[]byte]](&data)]);
#std::print_format_line(std::err(), "INCOMING SERVER MESSAGE LENGTH: {}", (:[]std::formatter)[std::formatter::init[[usize]](&count)]);
var result = bubby::value::init_from_str(data);
assert result.is_value(); # XXX: Need to handle decoding error.
var value = result.value();
defer value.fini();
var server_message = server_message::init_from_bubby(&value);
defer server_message.fini();
cstate.update_from_server_message(&server_message);
message::destroy(incoming);
}
}
client_update(&cstate, &message_sender);
if NBN_GameClient_SendPackets() < 0 {
std::print_line(std::err(), "error: failed to send nbnet packets");
}
client_render(&cstate);
}
# Poll remaining nbnet events and clean up outstanding messages.
for true {
var ev = NBN_GameClient_Poll();
if ev < 0 or ev == NBN_NO_EVENT {
break;
}
if ev == NBN_MESSAGE_RECEIVED {
var info = NBN_GameClient_GetMessageInfo();
assert info.type_ == message::TYPE;
var incoming = (:*message)info.data;
message::destroy(incoming);
}
}
}
func run_server() void {
NBN_Driver_Init();
var port = 31415u16;
NBN_Log_SetIsEnabled(NBN_LogType::NBN_LOG_TRACE, false);
NBN_Log_SetIsEnabled(NBN_LogType::NBN_LOG_DEBUG, false);
if NBN_GameServer_StartEx(startof("natac"), port) < 0 {
std::print_line(std::err(), "error: failed to start the nbnet server");
std::exit(std::EXIT_FAILURE);
}
defer NBN_GameServer_Stop();
NBN_GameServer_RegisterMessage(
message::TYPE,
(:NBN_MessageBuilder)message::create,
(:NBN_MessageDestructor)message::destroy,
(:NBN_MessageSerializer)message::serialize);
var sstate = server_state::init();
defer sstate.fini();
for true {
for true {
var ev = NBN_GameServer_Poll();
if ev < 0 {
std::print_line(std::err(), "error: failed to poll nbnet event");
break;
}
if ev == NBN_NO_EVENT {
break;
}
if ev == NBN_NEW_CONNECTION {
std::print_line(std::err(), "info: new connection");
let MAX_CONNECTIONS = 32u; # arbitary
if sstate.connections.count() == MAX_CONNECTIONS {
NBN_GameServer_RejectIncomingConnectionWithCode(BUSY_CODE);
break;
}
var server_message_sender = std::new[[nbnet_server_message_sender]]();
*server_message_sender = nbnet_server_message_sender::init(NBN_GameServer_GetIncomingConnection());
NBN_GameServer_AcceptIncomingConnection();
sstate.connections.push((:connection){
.player = std::optional[[player]]::EMPTY,
.sender = message_sender[[server_message]]::init[[nbnet_server_message_sender]](server_message_sender)
});
}
if ev == NBN_CLIENT_DISCONNECTED {
std::print_line(std::err(), "info: disconnected");
var handle = NBN_GameServer_GetDisconnectedClient();
for i in sstate.connections.count() {
if ((:*nbnet_server_message_sender)sstate.connections.data()[i].sender.object).*.handle != handle {
continue;
}
var server_message_sender = (:*nbnet_server_message_sender)sstate.connections.data()[i].sender.object;
std::delete[[nbnet_server_message_sender]](server_message_sender);
sstate.connections.remove(i);
break;
}
}
if ev == NBN_CLIENT_MESSAGE_RECEIVED {
var info = NBN_GameServer_GetMessageInfo();
assert info.type_ == message::TYPE;
var incoming = (:*message)info.data;
var count = (:usize)incoming.*.len;
var data = (:[]byte){(:*byte)&incoming.*.buf[0], count};
#std::print_format_line(std::err(), "INCOMING CLIENT MESSAGE STRING: {}", (:[]std::formatter)[std::formatter::init[[[]byte]](&data)]);
#std::print_format_line(std::err(), "INCOMING CLIENT MESSAGE LENGTH: {}", (:[]std::formatter)[std::formatter::init[[usize]](&count)]);
var result = bubby::value::init_from_str(data);
assert result.is_value(); # XXX: Need to handle decoding error.
var value = result.value();
defer value.fini();
var client_message = client_message::init_from_bubby(&value);
defer client_message.fini();
var handle = info.sender;
for i in sstate.connections.count() {
if ((:*nbnet_server_message_sender)sstate.connections.data()[i].sender.object).*.handle != handle {
continue;
}
sstate.update_from_client_message(&client_message, &sstate.connections.data()[i]);
break;
}
message::destroy(incoming);
}
}
server_update(&sstate);
if NBN_GameServer_SendPackets() < 0 {
std::print_line(std::err(), "error: failed to send nbnet packets");
break;
}
}
# Poll remaining nbnet events and clean up outstanding messages.
for true {
var ev = NBN_GameClient_Poll();
if ev < 0 or ev == NBN_NO_EVENT {
break;
}
if ev == NBN_CLIENT_MESSAGE_RECEIVED {
var info = NBN_GameServer_GetMessageInfo();
assert info.type_ == message::TYPE;
var incoming = (:*message)info.data;
message::destroy(incoming);
}
}
}
func usage() void {
# Specifically do not mention the -debug and -local options.
# Those options are primarily intended for Natac development.
std::print_line(std::err(), "Usage: natac [options]");
std::print_line(std::err(), "Options:");
std::print_line(std::err(), " -client IPADDR Join a game hosted on a server with IP address IPADDR.");
std::print_line(std::err(), " -server Start the game server.");
std::print_line(std::err(), " -seed SEED Initialize the random number generator with a the specified seed.");
std::print_line(std::err(), " -h, -help Display usage information and exit.");
}
func main() void {
# Application Global Allocator.
var allocator = std::general_allocator::init();
defer allocator.fini();
defer {
var iter = std::general_allocator_iterator::init(&allocator);
for iter.advance() {
var size = iter.current().*.size();
std::print_format_line(
std::err(),
"leaked allocation of size {}",
(:[]std::formatter)[
std::formatter::init[[usize]](&size)]);
}
}
var allocator = std::allocator::init[[typeof(allocator)]](&allocator);
std::set_global_allocator(allocator);
var now = unix_time_now();
var s = std::string::init_from_format("{}", (:[]std::formatter)[std::formatter::init[[typeof(now)]](&now)]);
defer s.fini();
random_init(s.data());
# Argument Parsing.
var argparser = std::argument_parser::init((:[][]byte)[
"seed:",
"debug",
"client:",
"server",
"local",
"h",
"help",
]);
var opt_debug = false;
var opt_network = std::optional[[network]]::EMPTY;
var opt_address = std::optional[[*byte]]::EMPTY;
for argparser.advance() {
if argparser.check_option("seed") {
random_init(argparser.argument_value());
continue;
}
if argparser.check_option("debug") {
opt_debug = true;
continue;
}
if argparser.check_option("client") {
opt_network = std::optional[[network]]::init_value(network::CLIENT);
opt_address = std::optional[[*byte]]::init_value(startof(argparser.argument_value()));
continue;
}
if argparser.check_option("server") {
opt_network = std::optional[[network]]::init_value(network::SERVER);
continue;
}
if argparser.check_option("local") {
opt_network = std::optional[[network]]::init_value(network::LOCAL);
continue;
}
if argparser.check_option("h") or argparser.check_option("help") {
usage();
std::exit(std::EXIT_SUCCESS);
}
var arg = argparser.argument_value();
std::print_format_line(
std::err(),
"error: unexpected argument `{}`",
(:[]std::formatter)[
std::formatter::init[[typeof(arg)]](&arg)]);
std::exit(std::EXIT_FAILURE);
}
# Start the Application Main Loop.
if opt_network.is_empty() or opt_network.value() == ::network::CLIENT {
return run_client(opt_debug, opt_address);
}
if opt_network.value() == ::network::SERVER {
return run_server();
}
if opt_network.value() == ::network::LOCAL {
return run_local(opt_debug);
}
std::unreachable(fileof(), lineof());
}