+/*
+ * Copyright (C) 2021-2022 Mt.ZERO Software, Harry Godden - All Rights Reserved
+ * All trademarks are property of their respective owners
+ */
+
#ifndef NETWORK_H
#define NETWORK_H
#include "vg/vg_stdint.h"
+#include "steam.h"
+#include "network_msg.h"
+#include "highscores.h"
+
+VG_STATIC int network_scores_updated = 0;
+
+/*
+ * Interface
+ */
+//#define SR_USE_LOCALHOST
+
+/* Call it at start; Connects us to the gameserver */
+VG_STATIC void network_init(void);
+
+/* Run this from main loop */
+VG_STATIC void network_update(void);
+
+/* Call it at shutdown */
+VG_STATIC void network_end(void);
+
+/*
+ * Can buffer up a bunch of these by calling many times, they will be
+ * sent at the next connection
+ */
+VG_STATIC void network_submit_highscore( u32 trackid, u16 points, u16 time );
+
+/*
+ * Game endpoints are provided with the same names to allow running without a
+ * network connection.
+ */
+#ifdef SR_NETWORKED
+
+/*
+ * Runtime connection stuff
+ */
+VG_STATIC u8 steam_app_ticket[ 1024 ];
+VG_STATIC u32 steam_app_ticket_length;
+VG_STATIC int network_name_update = 1;
+
+VG_STATIC HSteamNetConnection cremote;
+VG_STATIC ESteamNetworkingConnectionState cremote_state =
+ k_ESteamNetworkingConnectionState_None;
+
+/*
+ * Implementation
+ */
+
+VG_STATIC void scores_update(void);
+
+VG_STATIC void on_auth_ticket_recieved( void *result, void *context )
+{
+ EncryptedAppTicketResponse_t *response = result;
+
+ if( response->m_eResult == k_EResultOK )
+ {
+ vg_info( " New app ticket ready\n" );
+ }
+ else
+ {
+ vg_warn( " Could not request new encrypted app ticket (%u)\n",
+ response->m_eResult );
+ }
+
+ if( SteamAPI_ISteamUser_GetEncryptedAppTicket( hSteamUser,
+ steam_app_ticket,
+ vg_list_size(steam_app_ticket),
+ &steam_app_ticket_length ))
+ {
+ vg_success( " Loaded app ticket (%u bytes)\n", steam_app_ticket_length );
+ }
+ else
+ {
+ vg_error( " No ticket availible\n" );
+ steam_app_ticket_length = 0;
+ }
+}
+
+VG_STATIC void request_auth_ticket(void)
+{
+ /*
+ * TODO Check for one thats cached on the disk and load it.
+ * This might be OK though because steam seems to cache the result
+ */
+
+ vg_info( "Requesting new authorization ticket\n" );
+
+ vg_steam_async_call *call = vg_alloc_async_steam_api_call();
+ call->userdata = NULL;
+ call->p_handler = on_auth_ticket_recieved;
+ call->id =
+ SteamAPI_ISteamUser_RequestEncryptedAppTicket( hSteamUser, NULL, 0 );
+}
+
+VG_STATIC void send_auth_ticket(void)
+{
+ u32 size = sizeof(netmsg_auth) + steam_app_ticket_length;
+ netmsg_auth *auth = alloca(size);
+
+ auth->inetmsg_id = k_inetmsg_auth;
+ auth->ticket_length = steam_app_ticket_length;
+ for( int i=0; i<steam_app_ticket_length; i++ )
+ auth->ticket[i] = steam_app_ticket[i];
+
+ SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
+ hSteamNetworkingSockets, cremote, auth, size,
+ k_nSteamNetworkingSend_Reliable, NULL );
+}
+
+VG_STATIC void send_score_request(void)
+{
+ vg_info( "Requesting scores\n" );
+ netmsg_scores_request req;
+ req.inetmsg_id = k_inetmsg_scores_request;
+
+ SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
+ hSteamNetworkingSockets, cremote, &req, sizeof(netmsg_scores_request),
+ k_nSteamNetworkingSend_Reliable, NULL );
+}
+
+VG_STATIC void send_score_update(void)
+{
+ vg_info( "Sending scores\n" );
+ u32 size = sizeof(netmsg_set_score) +
+ vg_list_size(track_infos)*sizeof(struct netmsg_score_record);
+ netmsg_set_score *setscore = alloca( size );
+ setscore->inetmsg_id = k_inetmsg_set_score;
+
+ int count = 0;
+ for( u32 i=0; i<vg_list_size(track_infos); i++ ){
+ if( track_infos[i].push ){
+ track_infos[i].push = 0;
+
+#if 0
+ highscore_record *user_record = highscore_find_user_record( 0, i );
+
+ if( !user_record ){
+ vg_error( "No score set but tried to upload for track %u\n", i );
+ continue;
+ }
+#endif
+ highscore_record *user_record = &track_infos[i].record;
+
+ setscore->records[count].trackid = i;
+ setscore->records[count].playerid = 0;
+ setscore->records[count].points = user_record->points;
+ setscore->records[count].time = user_record->time;
+
+ count ++;
+ }
+ }
+
+ if( count == 0 ) return;
+ u32 send_size = sizeof(netmsg_set_score) +
+ count*sizeof(struct netmsg_score_record);
+ setscore->record_count = count;
+
+ SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
+ hSteamNetworkingSockets, cremote, setscore, send_size,
+ k_nSteamNetworkingSend_Reliable, NULL );
+}
+
+VG_STATIC void send_nickname(void)
+{
+ netmsg_set_nickname nick;
+ nick.inetmsg_id = k_inetmsg_set_nickname;
+
+ memset( nick.nickname, 0, 16 );
+ vg_strncpy( steam_username_at_startup, nick.nickname, 16,
+ k_strncpy_allow_cutoff );
+
+ SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
+ hSteamNetworkingSockets, cremote, &nick, sizeof(netmsg_set_nickname),
+ k_nSteamNetworkingSend_Reliable, NULL );
+
+ network_name_update = 0;
+}
+
+VG_STATIC void server_routine_update(void)
+{
+ send_auth_ticket();
+
+ if( network_name_update )
+ send_nickname();
+
+ send_score_update();
+ send_score_request();
+}
+
+VG_STATIC void on_server_connect_status( CallbackMsg_t *msg )
+{
+ SteamNetConnectionStatusChangedCallback_t *info = (void *)msg->m_pubParam;
+ vg_info( " Connection status changed for %lu\n", info->m_hConn );
+ vg_info( " %s -> %s\n",
+ string_ESteamNetworkingConnectionState(info->m_eOldState),
+ string_ESteamNetworkingConnectionState(info->m_info.m_eState) );
+
+ if( info->m_hConn == cremote )
+ {
+ cremote_state = info->m_info.m_eState;
+ if( info->m_info.m_eState ==
+ k_ESteamNetworkingConnectionState_Connected )
+ {
+ vg_success(" Connected to remote server.. running updates\n");
+ server_routine_update();
+ }
+ }
+ else
+ {
+ vg_warn( " Recieved signal from unknown connection\n" );
+ }
+}
+
+VG_STATIC void network_connect_gc(void)
+{
+ /* Connect to server if not connected */
+ SteamNetworkingIPAddr remoteAddr;
+
+#ifdef SR_USE_LOCALHOST
+ SteamAPI_SteamNetworkingIPAddr_SetIPv6LocalHost( &remoteAddr, 27402 );
+#else
+ const char *server_lon1 = "46.101.34.155:27402";
+ SteamAPI_SteamNetworkingIPAddr_ParseString( &remoteAddr, server_lon1 );
+#endif
+
+ char buf[256];
+ SteamAPI_SteamNetworkingIPAddr_ToString( &remoteAddr, buf, 256, 1 );
+ vg_info( "connect to: %s\n", buf );
+
+ cremote = SteamAPI_ISteamNetworkingSockets_ConnectByIPAddress(
+ hSteamNetworkingSockets, &remoteAddr, 0, NULL );
+}
+
+VG_STATIC void on_inet_scoreboard( SteamNetworkingMessage_t *msg )
+{
+ netmsg_scoreboard *sb = msg->m_pData;
+
+ u32 base_size = sizeof(netmsg_scoreboard)-
+ sizeof(struct netmsg_board)*vg_list_size(track_infos),
+ expected = base_size+sizeof(struct netmsg_board)*sb->board_count;
+
+ if( msg->m_cbSize != expected ){
+ vg_error( "Server scoreboard was corrupted. Size: %u != %u\n",
+ msg->m_cbSize, expected );
+ }
+ else{
+ if( vg_list_size(track_infos) > sb->board_count )
+ vg_warn( "Server is out of date, not enough boards recieved\n");
+ else if( vg_list_size(track_infos) < sb->board_count )
+ vg_warn( "Client out of date, server sent more boards than we have\n");
+ else
+ vg_success( "Recieved new scoreboards from server\n" );
+
+ for( int i=0; i < vg_min(sb->board_count,vg_list_size(track_infos)); i++){
+ scoreboard_client_data.boards[i] = sb->boards[i];
+ highscores_board_printf( stdout, sb->boards[i].data, 10 );
+ }
+ }
+
+ /* We dont need to stay on the server currently */
+ SteamAPI_ISteamNetworkingSockets_CloseConnection(
+ hSteamNetworkingSockets, cremote, 0, NULL, 1 );
+
+ network_scores_updated = 1;
+}
+
+VG_STATIC void poll_connection(void)
+{
+ SteamNetworkingMessage_t *messages[32];
+ int len;
+
+ while(1){
+ len = SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnConnection(
+ hSteamNetworkingSockets, cremote, messages, vg_list_size(messages));
+
+ if( len <= 0 )
+ return;
+
+ for( int i=0; i<len; i++ ){
+ SteamNetworkingMessage_t *msg = messages[i];
+
+ if( msg->m_cbSize < sizeof(netmsg_blank) ){
+ vg_warn( "Discarding message (too small: %d)\n", msg->m_cbSize );
+ continue;
+ }
+
+ netmsg_blank *tmp = msg->m_pData;
+
+ if( tmp->inetmsg_id == k_inetmsg_scoreboard )
+ on_inet_scoreboard( msg );
+
+ SteamAPI_SteamNetworkingMessage_t_Release( msg );
+ }
+ }
+}
+
+/*
+ * Subroutine to be connected to main game loop, runs all routines on timers
+ */
+VG_STATIC void network_update(void)
+{
+ if( steam_ready ){
+ static double last_update = 0.0;
+ poll_connection();
+
+ if( vg.time > (last_update + 60.0) ){
+ last_update = vg.time;
+
+ if( steam_app_ticket_length ){
+ network_connect_gc();
+ }
+ else{
+ vg_low( "Not making remote connection; app ticket not gotten\n" );
+ }
+ }
+
+ if( vg.time > (last_update + 10.0) &&
+ (cremote_state == k_ESteamNetworkingConnectionState_Connected ))
+ {
+ vg_warn( "Connected to server but no return... disconnecting\n" );
+ SteamAPI_ISteamNetworkingSockets_CloseConnection(
+ hSteamNetworkingSockets, cremote, 0, NULL, 1 );
+ }
+ }
+}
+
+VG_STATIC void network_init(void)
+{
+ if( steam_ready ){
+ steam_register_callback( k_iSteamNetConnectionStatusChangedCallBack,
+ on_server_connect_status );
+ request_auth_ticket();
+ }
+}
+
+VG_STATIC void network_end(void)
+{
+ /* TODO: Fire off any buffered highscores that need to be setn */
+ if( cremote_state == k_ESteamNetworkingConnectionState_Connected ||
+ cremote_state == k_ESteamNetworkingConnectionState_Connecting )
+ {
+ SteamAPI_ISteamNetworkingSockets_CloseConnection(
+ hSteamNetworkingSockets, cremote, 0, NULL, 1 );
+ }
+}
+#else /* SR_NETWORKED */
+VG_STATIC void network_init(void){}
+VG_STATIC void network_update(void){}
+VG_STATIC void network_end(void){}
+#endif /* SR_NETWORKED */
#endif /* NETWORK_H */