Windows libraries for getaddrinfo
[carveJwlIkooP6JGAAIwe30JlM.git] / network.c
1 #include "skaterift.h"
2 #include "vg/vg_steam.h"
3 #include "vg/vg_steam_networking.h"
4 #include "vg/vg_steam_auth.h"
5 #include "vg/vg_steam_friends.h"
6 #include "player.h"
7 #include "network.h"
8 #include "network_msg.h"
9 #include "network_common.h"
10 #include "player_remote.h"
11 #include "world.h"
12 #include "world_sfd.h"
13 #include "world_routes.h"
14 #include "vg/vg_imgui.h"
15 #include "gui.h"
16 #include "ent_region.h"
17 #include "vg/vg_loader.h"
18
19 #ifdef _WIN32
20 #include <winsock2.h>
21 #include <ws2tcpip.h>
22 #else
23 #include <sys/socket.h>
24 #include <sys/types.h>
25 #include <netdb.h>
26 #endif
27
28 struct network_client network_client =
29 {
30 .auth_mode = eServerModeAuthentication,
31 .state = k_ESteamNetworkingConnectionState_None,
32 .last_intent_change = -99999.9
33 };
34
35 static void scores_update(void);
36
37 int packet_minsize( SteamNetworkingMessage_t *msg, u32 size ){
38 if( msg->m_cbSize < size ) {
39 vg_error( "Invalid packet size (must be at least %u)\n", size );
40 return 0;
41 }
42 else{
43 return 1;
44 }
45 }
46
47 static void on_auth_ticket_recieved( void *result, void *context ){
48 EncryptedAppTicketResponse_t *response = result;
49
50 if( response->m_eResult == k_EResultOK ){
51 vg_info( " New app ticket ready\n" );
52 }
53 else{
54 vg_warn( " Could not request new encrypted app ticket (%u)\n",
55 response->m_eResult );
56 }
57
58 if( SteamAPI_ISteamUser_GetEncryptedAppTicket( hSteamUser,
59 network_client.app_symmetric_key,
60 vg_list_size(network_client.app_symmetric_key),
61 &network_client.app_key_length )){
62 vg_success( " Loaded app ticket\n" );
63 }
64 else{
65 vg_error( " No ticket availible\n" );
66 network_client.app_key_length = 0;
67 }
68 }
69
70 static void request_auth_ticket(void){
71 /*
72 * TODO Check for one thats cached on the disk and load it.
73 * This might be OK though because steam seems to cache the result
74 */
75
76 vg_info( "Requesting new authorization ticket\n" );
77
78 vg_steam_async_call *call = vg_alloc_async_steam_api_call();
79 call->userdata = NULL;
80 call->p_handler = on_auth_ticket_recieved;
81 call->id =
82 SteamAPI_ISteamUser_RequestEncryptedAppTicket( hSteamUser, NULL, 0 );
83 }
84
85 static void network_send_username(void){
86 if( !network_connected() )
87 return;
88
89 netmsg_playerusername *update = alloca( sizeof(netmsg_playerusername)+
90 NETWORK_USERNAME_MAX );
91 update->inetmsg_id = k_inetmsg_playerusername;
92 update->index = 0xff;
93
94 ISteamFriends *hSteamFriends = SteamAPI_SteamFriends();
95 const char *username = SteamAPI_ISteamFriends_GetPersonaName(hSteamFriends);
96 u32 chs = str_utf8_collapse( username, update->name, NETWORK_USERNAME_MAX );
97
98 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
99 hSteamNetworkingSockets, network_client.remote,
100 update, sizeof(netmsg_playerusername)+chs+1,
101 k_nSteamNetworkingSend_Reliable, NULL );
102 }
103
104 void network_send_region(void)
105 {
106 if( !network_connected() )
107 return;
108
109 netmsg_region *region = alloca( sizeof(netmsg_region) + NETWORK_REGION_MAX );
110
111 region->inetmsg_id = k_inetmsg_region;
112 region->client = 0;
113 region->flags = global_ent_region.flags;
114
115 u32 l = vg_strncpy( global_ent_region.location, region->loc,
116 NETWORK_REGION_MAX, k_strncpy_always_add_null );
117
118 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
119 hSteamNetworkingSockets, network_client.remote,
120 region, sizeof(netmsg_region)+l+1,
121 k_nSteamNetworkingSend_Reliable, NULL );
122 }
123
124 static void network_send_request( netmsg_request *req, vg_msg *body,
125 void (*callback)(
126 netmsg_request *res, vg_msg *body,
127 u64 userdata),
128 u64 userdata ){
129 u32 len = 0;
130 if( body ){
131 len = body->cur.co;
132 vg_info( "Request scoreboard. Info (%u):\n", body->cur.co );
133 vg_msg_print( body, len );
134
135 if( body->error != k_vg_msg_error_OK ){
136 vg_error( "Body not OK\n" );
137 return;
138 }
139 }
140
141 if( callback ){
142 req->id = vg_pool_lru( &network_client.request_pool );
143 if( req->id ){
144 vg_pool_watch( &network_client.request_pool, req->id );
145 struct network_request *pn =
146 vg_pool_item( &network_client.request_pool, req->id );
147 pn->callback = callback;
148 pn->sendtime = vg.time_real;
149 pn->userdata = userdata;
150 }
151 else{
152 vg_error( "Unable to send request. Pool is full.\n" );
153 return;
154 }
155 }
156 else
157 req->id = 0;
158
159 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
160 hSteamNetworkingSockets, network_client.remote,
161 req, sizeof(netmsg_request)+len,
162 k_nSteamNetworkingSend_Reliable, NULL );
163 }
164
165 static void network_scoreboard_callback( netmsg_request *res, vg_msg *body,
166 u64 userdata ){
167 world_instance *world = world_current_instance();
168
169 world_routes_recv_scoreboard( world, body, userdata, res->status );
170 if( userdata == world_sfd.active_route_board )
171 world_sfd_compile_active_scores();
172 }
173
174
175
176 /* mod_uid: world mod uid,
177 * route_uid: run name (just a string)
178 * week:
179 * 0 ALL TIME
180 * 1 CURRENT WEEK
181 * 2 ALL TIME + CURRENT WEEK
182 * .
183 * 10+ specific week index
184 */
185 void network_request_scoreboard( const char *mod_uid,
186 const char *route_uid,
187 u32 week, u64 userdata ){
188 if( !network_connected() )
189 return;
190
191 netmsg_request *req = alloca( sizeof(netmsg_request) + 512 );
192 req->inetmsg_id = k_inetmsg_request;
193
194 vg_msg data;
195 vg_msg_init( &data, req->q, 512 );
196 vg_msg_wkvstr( &data, "endpoint", "scoreboard" );
197 vg_msg_wkvstr( &data, "mod", mod_uid );
198 vg_msg_wkvstr( &data, "route", route_uid );
199 vg_msg_wkvnum( &data, "week", k_vg_msg_u32, 1, &week );
200 network_send_request( req, &data, network_scoreboard_callback, userdata );
201 }
202
203 static void network_publish_callback( netmsg_request *res, vg_msg *body,
204 u64 userdata ){
205 if( res->status != k_request_status_ok ){
206 vg_error( "Publish laptime, server error #%d\n", (i32)res->status );
207 }
208 }
209
210 void network_publish_laptime( const char *mod_uid,
211 const char *route_uid, f64 lap_time ){
212 if( !network_connected() )
213 return;
214
215 i32 time_centiseconds = lap_time * 100.0;
216
217 netmsg_request *req = alloca( sizeof(netmsg_request) + 512 );
218 req->inetmsg_id = k_inetmsg_request;
219
220 vg_msg data;
221 vg_msg_init( &data, req->q, 512 );
222 vg_msg_wkvstr( &data, "endpoint", "setlap" );
223 vg_msg_wkvstr( &data, "mod", mod_uid );
224 vg_msg_wkvstr( &data, "route", route_uid );
225 vg_msg_wkvnum( &data, "time", k_vg_msg_i32, 1, &time_centiseconds );
226 network_send_request( req, &data, network_publish_callback, 0 );
227 }
228
229 static void network_request_rx_300_400( SteamNetworkingMessage_t *msg ){
230 netmsg_blank *tmp = msg->m_pData;
231
232 if( tmp->inetmsg_id == k_inetmsg_request ){
233
234 }
235 else if( tmp->inetmsg_id == k_inetmsg_response ){
236 netmsg_request *res = (netmsg_request *)msg->m_pData;
237
238 vg_msg *body = NULL;
239
240 vg_msg data;
241 if( res->status == k_request_status_ok ){
242 vg_msg_init( &data, res->q, msg->m_cbSize - sizeof(netmsg_request) );
243 vg_success( "Response to #%d:\n", (i32)res->id );
244 vg_msg_print( &data, data.max );
245 body = &data;
246 }
247 else {
248 vg_warn( "Server response to #%d: %d\n", (i32)res->id, res->status );
249 }
250
251 if( res->id ){
252 struct network_request *pn =
253 vg_pool_item( &network_client.request_pool, res->id );
254 pn->callback( res, body, pn->userdata );
255 vg_pool_unwatch( &network_client.request_pool, res->id );
256 }
257 }
258 }
259
260 void network_send_item( enum netmsg_playeritem_type type )
261 {
262 if( !network_connected() )
263 return;
264
265 netmsg_playeritem *item =
266 alloca( sizeof(netmsg_playeritem) + ADDON_UID_MAX );
267 item->inetmsg_id = k_inetmsg_playeritem;
268 item->type_index = type;
269 item->client = 0;
270
271 if( (type == k_netmsg_playeritem_world0) ||
272 (type == k_netmsg_playeritem_world1) ){
273
274 enum world_purpose purpose = type - k_netmsg_playeritem_world0;
275 addon_reg *reg = world_static.instance_addons[ purpose ];
276
277 if( reg )
278 addon_alias_uid( &reg->alias, item->uid );
279 else
280 item->uid[0] = '\0';
281 }
282 else{
283 u16 view_id = 0;
284 enum addon_type addon_type = k_addon_type_none;
285 if( type == k_netmsg_playeritem_board ){
286 view_id = localplayer.board_view_slot;
287 addon_type = k_addon_type_board;
288 }
289 else if( type == k_netmsg_playeritem_player ){
290 view_id = localplayer.playermodel_view_slot;
291 addon_type = k_addon_type_player;
292 }
293
294 struct addon_cache *cache = &addon_system.cache[addon_type];
295 vg_pool *pool = &cache->pool;
296
297 SDL_AtomicLock( &addon_system.sl_cache_using_resources );
298 addon_cache_entry *entry = vg_pool_item( pool, view_id );
299 addon_alias_uid( &entry->reg_ptr->alias, item->uid );
300 SDL_AtomicUnlock( &addon_system.sl_cache_using_resources );
301 }
302
303 vg_info( "send equip: [%u] %s\n",
304 item->type_index, item->uid );
305 u32 chs = strlen(item->uid);
306
307 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
308 hSteamNetworkingSockets, network_client.remote,
309 item, sizeof(netmsg_playeritem)+chs+1,
310 k_nSteamNetworkingSend_Reliable, NULL );
311 }
312
313 static void network_disconnect(void){
314 SteamAPI_ISteamNetworkingSockets_CloseConnection(
315 hSteamNetworkingSockets, network_client.remote, 0, NULL, 0 );
316 network_client.remote = 0;
317 network_client.state = k_ESteamNetworkingConnectionState_None;
318
319 for( int i=0; i<vg_list_size(netplayers.list); i++ ){
320 netplayers.list[i].active = 0;
321 }
322 }
323
324 void network_status_string( vg_str *str, u32 *colour )
325 {
326 if( skaterift.demo_mode ){
327 vg_strcat( str, "Offline" );
328 return;
329 }
330
331 if( steam_ready ){
332 if( network_client.user_intent == k_server_intent_offline ){
333 vg_strcat( str, "Offline" );
334 }
335 else {
336 ESteamNetworkingConnectionState state = network_client.state;
337
338 if( state == k_ESteamNetworkingConnectionState_None )
339 vg_strcat( str, "No Connection" );
340 else if( state == k_ESteamNetworkingConnectionState_Connecting )
341 {
342 vg_strcatf( str, "Connecting...\n%s", network_client.host_adress );
343
344 if( network_client.retries ){
345 vg_strcat( str, "\n(" );
346 vg_strcati32( str, network_client.retries );
347 vg_strcat( str, " retries)" );
348 }
349 }
350 else if( state == k_ESteamNetworkingConnectionState_Connected ){
351 vg_strcatf( str, "Connected to:\n%s", network_client.host_adress );
352 *colour = 0xff00a020;
353 }
354 else if( state == k_ESteamNetworkingConnectionState_ClosedByPeer )
355 vg_strcat( str, "Connection Closed" );
356 else if( state == k_ESteamNetworkingConnectionState_FindingRoute )
357 vg_strcat( str, "Finding Route" );
358 else if( state ==
359 k_ESteamNetworkingConnectionState_ProblemDetectedLocally){
360 vg_strcat( str, "Problem Detected\nLocally" );
361 *colour = 0xff0000a0;
362 }
363 else
364 vg_strcat( str, "???" );
365 }
366 }
367 else {
368 vg_strcat( str, "Steam Offline" );
369 *colour = 0xff0000a0;
370 }
371 }
372
373 void render_server_status_gui(void)
374 {
375 render_fb_bind( gpipeline.fb_workshop_preview, 0 );
376
377 /* HACK */
378 vg_ui.cur_vert = 0;
379 vg_ui.cur_indice = 0;
380 vg_ui.vert_start = 0;
381 vg_ui.indice_start = 0;
382
383 ui_rect r = { 0, 0, 128, 48 };
384
385 char buf[128];
386 vg_str str;
387 vg_strnull( &str, buf, sizeof(buf) );
388
389 u32 bg = 0xff000000;
390 network_status_string( &str, &bg );
391
392 ui_fill( r, bg );
393 ui_text( r, buf, 1, k_ui_align_center, 0 );
394 ui_flush( k_ui_shader_colour, 128, 48 );
395
396 skaterift.rt_textures[ k_skaterift_rt_server_status ] =
397 gpipeline.fb_workshop_preview->attachments[0].id;
398 }
399
400 static void on_server_connect_status( CallbackMsg_t *msg ){
401 SteamNetConnectionStatusChangedCallback_t *info = (void *)msg->m_pubParam;
402 vg_info( " Connection status changed for %lu\n", info->m_hConn );
403 vg_info( " %s -> %s\n",
404 string_ESteamNetworkingConnectionState(info->m_eOldState),
405 string_ESteamNetworkingConnectionState(info->m_info.m_eState) );
406
407 if( info->m_hConn == network_client.remote ){
408 network_client.state = info->m_info.m_eState;
409
410 if( info->m_info.m_eState ==
411 k_ESteamNetworkingConnectionState_Connected ){
412 vg_success(" Connected to remote server.. authenticating\n");
413
414 /* send version info to server */
415 netmsg_version version;
416 version.inetmsg_id = k_inetmsg_version;
417 version.version = NETWORK_SKATERIFT_VERSION;
418 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
419 hSteamNetworkingSockets, network_client.remote, &version,
420 sizeof(netmsg_version), k_nSteamNetworkingSend_Reliable, NULL );
421
422 /* TODO: We should really wait to see if the server is in auth mode
423 * first... */
424 u32 size = sizeof(netmsg_auth) + network_client.app_key_length;
425 netmsg_auth *auth = alloca(size);
426 auth->inetmsg_id = k_inetmsg_auth;
427 auth->ticket_length = network_client.app_key_length;
428 for( int i=0; i<network_client.app_key_length; i++ )
429 auth->ticket[i] = network_client.app_symmetric_key[i];
430
431 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
432 hSteamNetworkingSockets, network_client.remote, auth, size,
433 k_nSteamNetworkingSend_Reliable, NULL );
434 }
435 else if( info->m_info.m_eState ==
436 k_ESteamNetworkingConnectionState_ClosedByPeer ){
437
438 if( info->m_info.m_eEndReason ==
439 k_ESteamNetConnectionEnd_Misc_InternalError ){
440 network_client.retries = 40;
441 }
442 network_disconnect();
443 }
444 else if( info->m_info.m_eState ==
445 k_ESteamNetworkingConnectionState_ProblemDetectedLocally ){
446 network_disconnect();
447 }
448 }
449 else{
450 //vg_warn( " Recieved signal from unknown connection\n" );
451 }
452
453 render_server_status_gui();
454 }
455
456 static void on_persona_state_change( CallbackMsg_t *msg ){
457 if( !network_connected() )
458 return;
459
460 PersonaStateChange_t *info = (void *)msg->m_pubParam;
461 ISteamUser *hSteamUser = SteamAPI_SteamUser();
462
463 vg_info( "User: %llu, change: %u\n", info->m_ulSteamID,
464 info->m_nChangeFlags );
465
466 if( info->m_ulSteamID == SteamAPI_ISteamUser_GetSteamID(hSteamUser) ){
467 if( info->m_nChangeFlags & k_EPersonaChangeName ){
468 network_send_username();
469 }
470 }
471
472 if( info->m_nChangeFlags & k_EPersonaChangeRelationshipChanged ){
473 for( u32 i=0; i<NETWORK_MAX_PLAYERS; i ++ ){
474 struct network_player *rp = &netplayers.list[i];
475 if( rp->steamid == info->m_ulSteamID ){
476 player_remote_update_friendflags( rp );
477 }
478 }
479 }
480 }
481
482 void network_set_host( const char *host_str, const char *port_str )
483 {
484 vg_strncpy( host_str, network_client.host_adress,
485 sizeof(network_client.host_adress), k_strncpy_overflow_fatal );
486
487 memset( &network_client.ip, 0, sizeof(network_client.ip) );
488 network_client.ip_resolved = 0;
489
490 if( port_str )
491 {
492 vg_strncpy( port_str, network_client.host_port,
493 sizeof(network_client.host_port), k_strncpy_overflow_fatal );
494 }
495 else
496 {
497 vg_str str;
498 vg_strnull( &str, network_client.host_port,
499 sizeof(network_client.host_port) );
500 vg_strcati32( &str, NETWORK_PORT );
501 }
502
503 network_client.ip.m_port = atoi( network_client.host_port );
504 }
505
506 static void network_connect(void)
507 {
508 VG_ASSERT( network_client.ip_resolved );
509
510 vg_info( "connecting...\n" );
511 network_client.remote = SteamAPI_ISteamNetworkingSockets_ConnectByIPAddress(
512 hSteamNetworkingSockets, &network_client.ip, 0, NULL );
513 }
514
515 static void network_sign_on_complete(void){
516 vg_success( "Sign on completed\n" );
517
518 /* send our init info */
519 network_send_username();
520 for( u32 i=0; i<k_netmsg_playeritem_max; i ++ ){
521 network_send_item(i);
522 }
523 network_send_region();
524 }
525
526 static void poll_remote_connection(void){
527 SteamNetworkingMessage_t *messages[32];
528 int len;
529
530 for( int i=0; i<10; i++ ){
531 len = SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnConnection(
532 hSteamNetworkingSockets, network_client.remote,
533 messages, vg_list_size(messages));
534
535 if( len <= 0 )
536 return;
537
538 for( int i=0; i<len; i++ ){
539 SteamNetworkingMessage_t *msg = messages[i];
540
541 if( msg->m_cbSize < sizeof(netmsg_blank) ){
542 vg_warn( "Discarding message (too small: %d)\n", msg->m_cbSize );
543 continue;
544 }
545
546 netmsg_blank *tmp = msg->m_pData;
547
548 if( (tmp->inetmsg_id >= 200) && (tmp->inetmsg_id < 300) ){
549 player_remote_rx_200_300( msg );
550 }
551 else if( (tmp->inetmsg_id >= 300) && (tmp->inetmsg_id < 400) ){
552 network_request_rx_300_400( msg );
553 }
554 else {
555 if( tmp->inetmsg_id == k_inetmsg_version ){
556 netmsg_version *version = msg->m_pData;
557 if( version->version != NETWORK_SKATERIFT_VERSION ){
558 network_disconnect();
559 /* we dont want to connect to this server ever */
560 network_client.retries = 999;
561 network_client.last_attempt = 999999999.9;
562 vg_error( "version mismatch with server\n" );
563 }
564 else {
565 network_client.remote_version = version->version;
566 network_sign_on_complete();
567 }
568 }
569 }
570
571 SteamAPI_SteamNetworkingMessage_t_Release( msg );
572 }
573 }
574 }
575
576 static void network_resolve_host_async( void *payload, u32 size )
577 {
578 u32 *status = payload;
579 network_client.ip_resolved = *status;
580
581 char buf[256];
582 SteamAPI_SteamNetworkingIPAddr_ToString( &network_client.ip, buf, 256, 1 );
583 vg_info( "Resolved host address to: %s\n", buf );
584 }
585
586 static void network_resolve_host_thread( void *_ )
587 {
588 vg_async_item *call = vg_async_alloc(8);
589 u32 *status = call->payload;
590 *status = 0;
591
592 if( (network_client.host_adress[0] >= '0') &&
593 (network_client.host_adress[0] <= '9') )
594 {
595 SteamAPI_SteamNetworkingIPAddr_ParseString(
596 &network_client.ip,
597 network_client.host_adress );
598 network_client.ip.m_port = atoi( network_client.host_port );
599 *status = 1;
600 goto end;
601 }
602
603 vg_info( "Resolving host.. %s (:%s)\n",
604 network_client.host_adress, network_client.host_port );
605
606 struct addrinfo hints;
607 struct addrinfo *result;
608
609 /* Obtain address(es) matching host/port. */
610
611 memset( &hints, 0, sizeof(hints) );
612 hints.ai_family = AF_INET6;
613 hints.ai_socktype = SOCK_DGRAM;
614 hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
615 hints.ai_protocol = 0;
616
617 int s = getaddrinfo( network_client.host_adress, network_client.host_port,
618 &hints, &result);
619 if( s != 0 )
620 {
621 #ifndef _WIN32
622 vg_error( "getaddrinfo: %s\n", gai_strerror(s) );
623 #endif
624
625 if( !strcmp( network_client.host_adress, "skaterift.com" ) )
626 {
627 vg_warn( "getaddrinfo failed for skaterift.com;\n "
628 "falling back to a hardcoded IPv4\n" );
629 strcpy( network_client.host_adress, "46.101.34.155" );
630 SteamAPI_SteamNetworkingIPAddr_ParseString(
631 &network_client.ip,
632 network_client.host_adress );
633 network_client.ip.m_port = NETWORK_PORT;
634 *status = 1;
635 }
636
637 goto end;
638 }
639
640 struct sockaddr_in6 *inaddr = (struct sockaddr_in6 *)result->ai_addr;
641 memcpy( network_client.ip.m_ipv6, &inaddr->sin6_addr, 16 );
642 freeaddrinfo( result );
643
644 *status = 1;
645
646 end: vg_async_dispatch( call, network_resolve_host_async );
647 }
648
649 void network_update(void)
650 {
651 if( !steam_ready )
652 return;
653
654 ESteamNetworkingConnectionState state = network_client.state;
655
656 if( network_client.user_intent == k_server_intent_offline )
657 {
658 if( state != k_ESteamNetworkingConnectionState_None )
659 network_disconnect();
660
661 return;
662 }
663
664 if( state == k_ESteamNetworkingConnectionState_Connected )
665 {
666 poll_remote_connection();
667 f64 frame_delta = vg.time_real - network_client.last_frame;
668
669 if( frame_delta > NETWORK_FRAMERATE )
670 {
671 network_client.last_frame = vg.time_real;
672 remote_player_send_playerframe();
673 localplayer.sfx_buffer_count = 0;
674 }
675
676 remote_player_debug_update();
677 }
678 else
679 {
680 if( (state == k_ESteamNetworkingConnectionState_Connecting) ||
681 (state == k_ESteamNetworkingConnectionState_FindingRoute) )
682 {
683 return;
684 }
685 else
686 {
687 f64 waited = vg.time_real - network_client.last_attempt,
688 min_wait = 1.0;
689
690 if( network_client.retries > 5 )
691 min_wait = 60.0;
692
693 if( waited < min_wait )
694 return;
695
696 if( !network_client.ip_resolved )
697 {
698 if( vg_loader_availible() )
699 {
700 vg_loader_start( network_resolve_host_thread, NULL );
701 }
702 else return;
703 }
704 else
705 network_connect();
706
707 network_client.retries ++;
708 network_client.last_attempt = vg.time_real;
709 }
710 }
711 }
712
713 void chat_send_message( const char *message )
714 {
715 if( !network_connected() ){
716 return;
717 }
718
719 netmsg_chat *chat = alloca( sizeof(netmsg_chat) + NETWORK_MAX_CHAT );
720 chat->inetmsg_id = k_inetmsg_chat;
721 chat->client = 0;
722
723 u32 l = vg_strncpy( message, chat->msg, NETWORK_MAX_CHAT,
724 k_strncpy_always_add_null );
725
726 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
727 hSteamNetworkingSockets, network_client.remote,
728 chat, sizeof(netmsg_chat)+l+1,
729 k_nSteamNetworkingSend_Reliable, NULL );
730 }
731
732 static int cmd_network_send_message( int argc, const char *argv[] ){
733 char buf[ NETWORK_MAX_CHAT ];
734 vg_str str;
735 vg_strnull( &str, buf, NETWORK_MAX_CHAT );
736
737 for( int i=0; i<argc; i ++ ){
738 vg_strcat( &str, argv[i] );
739
740 if( i < argc-1 )
741 vg_strcatch( &str, ' ' );
742 }
743
744 chat_send_message( buf );
745 return 0;
746 }
747
748 void network_init(void)
749 {
750 vg_console_reg_var( "network_info", &network_client.network_info,
751 k_var_dtype_i32, VG_VAR_PERSISTENT );
752 vg_console_reg_var( "auto_connect", &network_client.auto_connect,
753 k_var_dtype_i32, VG_VAR_PERSISTENT );
754 if( steam_ready ){
755 u32 alloc_size = sizeof(struct network_request)*NETWORK_MAX_REQUESTS;
756 network_client.request_buffer =
757 vg_linear_alloc( vg_mem.rtmemory, alloc_size );
758 memset( network_client.request_buffer, 0, alloc_size );
759
760 vg_pool *pool = &network_client.request_pool;
761 pool->buffer = network_client.request_buffer;
762 pool->count = NETWORK_MAX_REQUESTS;
763 pool->stride = sizeof( struct network_request );
764 pool->offset = offsetof( struct network_request, poolnode );
765 vg_pool_init( pool );
766
767 steam_register_callback( k_iSteamNetConnectionStatusChangedCallBack,
768 on_server_connect_status );
769 steam_register_callback( k_iPersonaStateChange,
770 on_persona_state_change );
771 request_auth_ticket();
772
773 vg_console_reg_cmd( "say", cmd_network_send_message, NULL );
774 }
775 }
776
777 void network_end(void)
778 {
779 /* TODO: Send buffered highscores that were not already */
780 if( (network_client.state == k_ESteamNetworkingConnectionState_Connected) ||
781 (network_client.state == k_ESteamNetworkingConnectionState_Connecting) )
782 {
783 SteamAPI_ISteamNetworkingSockets_CloseConnection(
784 hSteamNetworkingSockets, network_client.remote, 0, NULL, 1 );
785 }
786 }