fc454c75afbf7cf643aefe861def63250a2ed0a7
[carveJwlIkooP6JGAAIwe30JlM.git] / network.h
1 /*
2 * Copyright (C) 2021-2022 Mt.ZERO Software, Harry Godden - All Rights Reserved
3 * All trademarks are property of their respective owners
4 */
5
6 #ifndef NETWORK_H
7 #define NETWORK_H
8
9 #include "vg/vg_stdint.h"
10 #include "steam.h"
11 #include "network_msg.h"
12 #include "highscores.h"
13
14 VG_STATIC int network_scores_updated = 0;
15
16 /*
17 * Interface
18 */
19 //#define SR_USE_LOCALHOST
20
21 /* Call it at start; Connects us to the gameserver */
22 VG_STATIC void network_init(void);
23
24 /* Run this from main loop */
25 VG_STATIC void network_update(void);
26
27 /* Call it at shutdown */
28 VG_STATIC void network_end(void);
29
30 /*
31 * Can buffer up a bunch of these by calling many times, they will be
32 * sent at the next connection
33 */
34 VG_STATIC void network_submit_highscore( u32 trackid, u16 points, u16 time );
35
36 /*
37 * Game endpoints are provided with the same names to allow running without a
38 * network connection.
39 */
40 #ifdef SR_NETWORKED
41
42 /*
43 * Runtime connection stuff
44 */
45 VG_STATIC u8 steam_app_ticket[ 1024 ];
46 VG_STATIC u32 steam_app_ticket_length;
47 VG_STATIC int network_name_update = 1;
48
49 VG_STATIC HSteamNetConnection cremote;
50 VG_STATIC ESteamNetworkingConnectionState cremote_state =
51 k_ESteamNetworkingConnectionState_None;
52
53 /*
54 * Implementation
55 */
56
57 VG_STATIC void scores_update(void);
58
59 VG_STATIC void on_auth_ticket_recieved( void *result, void *context )
60 {
61 EncryptedAppTicketResponse_t *response = result;
62
63 if( response->m_eResult == k_EResultOK )
64 {
65 vg_info( " New app ticket ready\n" );
66 }
67 else
68 {
69 vg_warn( " Could not request new encrypted app ticket (%u)\n",
70 response->m_eResult );
71 }
72
73 if( SteamAPI_ISteamUser_GetEncryptedAppTicket( hSteamUser,
74 steam_app_ticket,
75 vg_list_size(steam_app_ticket),
76 &steam_app_ticket_length ))
77 {
78 vg_success( " Loaded app ticket (%u bytes)\n", steam_app_ticket_length );
79 }
80 else
81 {
82 vg_error( " No ticket availible\n" );
83 steam_app_ticket_length = 0;
84 }
85 }
86
87 VG_STATIC void request_auth_ticket(void)
88 {
89 /*
90 * TODO Check for one thats cached on the disk and load it.
91 * This might be OK though because steam seems to cache the result
92 */
93
94 vg_info( "Requesting new authorization ticket\n" );
95 steam_async *call = steam_new_async();
96 call->data = NULL;
97 call->p_handler = on_auth_ticket_recieved;
98 call->id = SteamAPI_ISteamUser_RequestEncryptedAppTicket( hSteamUser,
99 NULL, 0 );
100 }
101
102 VG_STATIC void send_auth_ticket(void)
103 {
104 u32 size = sizeof(netmsg_auth) + steam_app_ticket_length;
105 netmsg_auth *auth = alloca(size);
106
107 auth->inetmsg_id = k_inetmsg_auth;
108 auth->ticket_length = steam_app_ticket_length;
109 for( int i=0; i<steam_app_ticket_length; i++ )
110 auth->ticket[i] = steam_app_ticket[i];
111
112 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
113 hSteamNetworkingSockets, cremote, auth, size,
114 k_nSteamNetworkingSend_Reliable, NULL );
115 }
116
117 VG_STATIC void send_score_request(void)
118 {
119 vg_info( "Requesting scores\n" );
120 netmsg_scores_request req;
121 req.inetmsg_id = k_inetmsg_scores_request;
122
123 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
124 hSteamNetworkingSockets, cremote, &req, sizeof(netmsg_scores_request),
125 k_nSteamNetworkingSend_Reliable, NULL );
126 }
127
128 VG_STATIC void send_score_update(void)
129 {
130 vg_info( "Sending scores\n" );
131 u32 size = sizeof(netmsg_set_score) +
132 vg_list_size(track_infos)*sizeof(struct netmsg_score_record);
133 netmsg_set_score *setscore = alloca( size );
134 setscore->inetmsg_id = k_inetmsg_set_score;
135
136 int count = 0;
137 for( u32 i=0; i<vg_list_size(track_infos); i++ )
138 {
139 if( track_infos[i].push )
140 {
141 track_infos[i].push = 0;
142 highscore_record *user_record = highscore_find_user_record( 0, i );
143
144 if( !user_record )
145 {
146 vg_error( "No score set but tried to upload for track %u\n", i );
147 continue;
148 }
149
150 setscore->records[count].trackid = i;
151 setscore->records[count].playerid = 0;
152 setscore->records[count].points = user_record->points;
153 setscore->records[count].time = user_record->time;
154
155 count ++;
156 }
157 }
158
159 if( count == 0 )
160 return;
161
162 u32 send_size = sizeof(netmsg_set_score) +
163 count*sizeof(struct netmsg_score_record);
164 setscore->record_count = count;
165
166 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
167 hSteamNetworkingSockets, cremote, setscore, send_size,
168 k_nSteamNetworkingSend_Reliable, NULL );
169 }
170
171 VG_STATIC void send_nickname(void)
172 {
173 netmsg_set_nickname nick;
174 nick.inetmsg_id = k_inetmsg_set_nickname;
175
176 memset( nick.nickname, 0, 16 );
177 vg_strncpy( steam_username_at_startup, nick.nickname, 16 );
178
179 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
180 hSteamNetworkingSockets, cremote, &nick, sizeof(netmsg_set_nickname),
181 k_nSteamNetworkingSend_Reliable, NULL );
182
183 network_name_update = 0;
184 }
185
186 VG_STATIC void server_routine_update(void)
187 {
188 send_auth_ticket();
189
190 if( network_name_update )
191 send_nickname();
192
193 send_score_update();
194 send_score_request();
195 }
196
197 VG_STATIC void on_server_connect_status( CallbackMsg_t *msg )
198 {
199 SteamNetConnectionStatusChangedCallback_t *info = (void *)msg->m_pubParam;
200 vg_info( " Connection status changed for %lu\n", info->m_hConn );
201 vg_info( " %s -> %s\n",
202 string_ESteamNetworkingConnectionState(info->m_eOldState),
203 string_ESteamNetworkingConnectionState(info->m_info.m_eState) );
204
205 if( info->m_hConn == cremote )
206 {
207 cremote_state = info->m_info.m_eState;
208 if( info->m_info.m_eState ==
209 k_ESteamNetworkingConnectionState_Connected )
210 {
211 vg_success(" Connected to remote server.. running updates\n");
212 server_routine_update();
213 }
214 }
215 else
216 {
217 vg_warn( " Recieved signal from unknown connection\n" );
218 }
219 }
220
221 VG_STATIC void network_connect_gc(void)
222 {
223 /* Connect to server if not connected */
224 SteamNetworkingIPAddr remoteAddr;
225
226 #ifdef SR_USE_LOCALHOST
227 SteamAPI_SteamNetworkingIPAddr_SetIPv6LocalHost( &remoteAddr, 27402 );
228 #else
229 const char *server_lon1 = "46.101.34.155:27402";
230 SteamAPI_SteamNetworkingIPAddr_ParseString( &remoteAddr, server_lon1 );
231 #endif
232
233 char buf[256];
234 SteamAPI_SteamNetworkingIPAddr_ToString( &remoteAddr, buf, 256, 1 );
235 vg_info( "connect to: %s\n", buf );
236
237 cremote = SteamAPI_ISteamNetworkingSockets_ConnectByIPAddress(
238 hSteamNetworkingSockets, &remoteAddr, 0, NULL );
239 }
240
241 VG_STATIC void on_inet_scoreboard( SteamNetworkingMessage_t *msg )
242 {
243 netmsg_scoreboard *sb = msg->m_pData;
244
245 u32 base_size = sizeof(netmsg_scoreboard)-
246 sizeof(struct netmsg_board)*vg_list_size(track_infos),
247 expected = base_size+sizeof(struct netmsg_board)*sb->board_count;
248
249 if( msg->m_cbSize != expected )
250 {
251 vg_error( "Server scoreboard was corrupted. Size: %u != %u\n",
252 msg->m_cbSize, expected );
253 }
254 else
255 {
256 if( vg_list_size(track_infos) > sb->board_count )
257 vg_warn( "Server is out of date, not enough boards recieved\n");
258 else if( vg_list_size(track_infos) < sb->board_count )
259 vg_warn( "Client out of date, server sent more boards than we have\n");
260 else
261 vg_success( "Recieved new scoreboards from server\n" );
262
263 for( int i=0; i < vg_min(sb->board_count,vg_list_size(track_infos)); i++)
264 {
265 scoreboard_client_data.boards[i] = sb->boards[i];
266 highscores_board_printf( stdout, sb->boards[i].data, 10 );
267 }
268 }
269
270 /* We dont need to stay on the server currently */
271 SteamAPI_ISteamNetworkingSockets_CloseConnection(
272 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
273
274 network_scores_updated = 1;
275 }
276
277 VG_STATIC void poll_connection(void)
278 {
279 SteamNetworkingMessage_t *messages[32];
280 int len;
281
282 while(1)
283 {
284 len = SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnConnection(
285 hSteamNetworkingSockets, cremote, messages, vg_list_size(messages));
286
287 if( len <= 0 )
288 return;
289
290 for( int i=0; i<len; i++ )
291 {
292 SteamNetworkingMessage_t *msg = messages[i];
293
294 if( msg->m_cbSize < sizeof(netmsg_blank) )
295 {
296 vg_warn( "Discarding message (too small: %d)\n", msg->m_cbSize );
297 continue;
298 }
299
300 netmsg_blank *tmp = msg->m_pData;
301
302 if( tmp->inetmsg_id == k_inetmsg_scoreboard )
303 on_inet_scoreboard( msg );
304
305 SteamAPI_SteamNetworkingMessage_t_Release( msg );
306 }
307 }
308 }
309
310 /*
311 * Subroutine to be connected to main game loop, runs all routines on timers
312 */
313 VG_STATIC void network_update(void)
314 {
315 if( steam_ready )
316 {
317 static double last_update = 0.0;
318 poll_connection();
319
320 if( vg.time > (last_update + 60.0) )
321 {
322 last_update = vg.time;
323
324 if( steam_app_ticket_length )
325 {
326 network_connect_gc();
327 }
328 else
329 {
330 vg_low( "Not making remote connection; app ticket not gotten\n" );
331 }
332 }
333
334 if( vg.time > (last_update + 10.0) &&
335 (cremote_state == k_ESteamNetworkingConnectionState_Connected ))
336 {
337 vg_warn( "Connected to server but no return... disconnecting\n" );
338 SteamAPI_ISteamNetworkingSockets_CloseConnection(
339 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
340 }
341 }
342 }
343
344 VG_STATIC void network_init(void)
345 {
346 if( steam_ready )
347 {
348 steam_register_callback( k_iSteamNetConnectionStatusChangedCallBack,
349 on_server_connect_status );
350 request_auth_ticket();
351 }
352 }
353
354 VG_STATIC void network_end(void)
355 {
356 /* TODO: Fire off any buffered highscores that need to be setn */
357 if( cremote_state == k_ESteamNetworkingConnectionState_Connected ||
358 cremote_state == k_ESteamNetworkingConnectionState_Connecting )
359 {
360 SteamAPI_ISteamNetworkingSockets_CloseConnection(
361 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
362 }
363 }
364
365 #else /* SR_NETWORKED */
366
367 VG_STATIC void network_init(void){}
368 VG_STATIC void network_update(void){}
369 VG_STATIC void network_end(void){}
370
371 #endif /* SR_NETWORKED */
372 #endif /* NETWORK_H */