my fucking fingers
[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
96 vg_steam_async_call *call = vg_alloc_async_steam_api_call();
97 call->userdata = NULL;
98 call->p_handler = on_auth_ticket_recieved;
99 call->id =
100 SteamAPI_ISteamUser_RequestEncryptedAppTicket( hSteamUser, NULL, 0 );
101 }
102
103 VG_STATIC void send_auth_ticket(void)
104 {
105 u32 size = sizeof(netmsg_auth) + steam_app_ticket_length;
106 netmsg_auth *auth = alloca(size);
107
108 auth->inetmsg_id = k_inetmsg_auth;
109 auth->ticket_length = steam_app_ticket_length;
110 for( int i=0; i<steam_app_ticket_length; i++ )
111 auth->ticket[i] = steam_app_ticket[i];
112
113 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
114 hSteamNetworkingSockets, cremote, auth, size,
115 k_nSteamNetworkingSend_Reliable, NULL );
116 }
117
118 VG_STATIC void send_score_request(void)
119 {
120 vg_info( "Requesting scores\n" );
121 netmsg_scores_request req;
122 req.inetmsg_id = k_inetmsg_scores_request;
123
124 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
125 hSteamNetworkingSockets, cremote, &req, sizeof(netmsg_scores_request),
126 k_nSteamNetworkingSend_Reliable, NULL );
127 }
128
129 VG_STATIC void send_score_update(void)
130 {
131 vg_info( "Sending scores\n" );
132 u32 size = sizeof(netmsg_set_score) +
133 vg_list_size(track_infos)*sizeof(struct netmsg_score_record);
134 netmsg_set_score *setscore = alloca( size );
135 setscore->inetmsg_id = k_inetmsg_set_score;
136
137 int count = 0;
138 for( u32 i=0; i<vg_list_size(track_infos); i++ )
139 {
140 if( track_infos[i].push )
141 {
142 track_infos[i].push = 0;
143 highscore_record *user_record = highscore_find_user_record( 0, i );
144
145 if( !user_record )
146 {
147 vg_error( "No score set but tried to upload for track %u\n", i );
148 continue;
149 }
150
151 setscore->records[count].trackid = i;
152 setscore->records[count].playerid = 0;
153 setscore->records[count].points = user_record->points;
154 setscore->records[count].time = user_record->time;
155
156 count ++;
157 }
158 }
159
160 if( count == 0 )
161 return;
162
163 u32 send_size = sizeof(netmsg_set_score) +
164 count*sizeof(struct netmsg_score_record);
165 setscore->record_count = count;
166
167 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
168 hSteamNetworkingSockets, cremote, setscore, send_size,
169 k_nSteamNetworkingSend_Reliable, NULL );
170 }
171
172 VG_STATIC void send_nickname(void)
173 {
174 netmsg_set_nickname nick;
175 nick.inetmsg_id = k_inetmsg_set_nickname;
176
177 memset( nick.nickname, 0, 16 );
178 vg_strncpy( steam_username_at_startup, nick.nickname, 16,
179 k_strncpy_allow_cutoff );
180
181 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
182 hSteamNetworkingSockets, cremote, &nick, sizeof(netmsg_set_nickname),
183 k_nSteamNetworkingSend_Reliable, NULL );
184
185 network_name_update = 0;
186 }
187
188 VG_STATIC void server_routine_update(void)
189 {
190 send_auth_ticket();
191
192 if( network_name_update )
193 send_nickname();
194
195 send_score_update();
196 send_score_request();
197 }
198
199 VG_STATIC void on_server_connect_status( CallbackMsg_t *msg )
200 {
201 SteamNetConnectionStatusChangedCallback_t *info = (void *)msg->m_pubParam;
202 vg_info( " Connection status changed for %lu\n", info->m_hConn );
203 vg_info( " %s -> %s\n",
204 string_ESteamNetworkingConnectionState(info->m_eOldState),
205 string_ESteamNetworkingConnectionState(info->m_info.m_eState) );
206
207 if( info->m_hConn == cremote )
208 {
209 cremote_state = info->m_info.m_eState;
210 if( info->m_info.m_eState ==
211 k_ESteamNetworkingConnectionState_Connected )
212 {
213 vg_success(" Connected to remote server.. running updates\n");
214 server_routine_update();
215 }
216 }
217 else
218 {
219 vg_warn( " Recieved signal from unknown connection\n" );
220 }
221 }
222
223 VG_STATIC void network_connect_gc(void)
224 {
225 /* Connect to server if not connected */
226 SteamNetworkingIPAddr remoteAddr;
227
228 #ifdef SR_USE_LOCALHOST
229 SteamAPI_SteamNetworkingIPAddr_SetIPv6LocalHost( &remoteAddr, 27402 );
230 #else
231 const char *server_lon1 = "46.101.34.155:27402";
232 SteamAPI_SteamNetworkingIPAddr_ParseString( &remoteAddr, server_lon1 );
233 #endif
234
235 char buf[256];
236 SteamAPI_SteamNetworkingIPAddr_ToString( &remoteAddr, buf, 256, 1 );
237 vg_info( "connect to: %s\n", buf );
238
239 cremote = SteamAPI_ISteamNetworkingSockets_ConnectByIPAddress(
240 hSteamNetworkingSockets, &remoteAddr, 0, NULL );
241 }
242
243 VG_STATIC void on_inet_scoreboard( SteamNetworkingMessage_t *msg )
244 {
245 netmsg_scoreboard *sb = msg->m_pData;
246
247 u32 base_size = sizeof(netmsg_scoreboard)-
248 sizeof(struct netmsg_board)*vg_list_size(track_infos),
249 expected = base_size+sizeof(struct netmsg_board)*sb->board_count;
250
251 if( msg->m_cbSize != expected )
252 {
253 vg_error( "Server scoreboard was corrupted. Size: %u != %u\n",
254 msg->m_cbSize, expected );
255 }
256 else
257 {
258 if( vg_list_size(track_infos) > sb->board_count )
259 vg_warn( "Server is out of date, not enough boards recieved\n");
260 else if( vg_list_size(track_infos) < sb->board_count )
261 vg_warn( "Client out of date, server sent more boards than we have\n");
262 else
263 vg_success( "Recieved new scoreboards from server\n" );
264
265 for( int i=0; i < vg_min(sb->board_count,vg_list_size(track_infos)); i++)
266 {
267 scoreboard_client_data.boards[i] = sb->boards[i];
268 highscores_board_printf( stdout, sb->boards[i].data, 10 );
269 }
270 }
271
272 /* We dont need to stay on the server currently */
273 SteamAPI_ISteamNetworkingSockets_CloseConnection(
274 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
275
276 network_scores_updated = 1;
277 }
278
279 VG_STATIC void poll_connection(void)
280 {
281 SteamNetworkingMessage_t *messages[32];
282 int len;
283
284 while(1)
285 {
286 len = SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnConnection(
287 hSteamNetworkingSockets, cremote, messages, vg_list_size(messages));
288
289 if( len <= 0 )
290 return;
291
292 for( int i=0; i<len; i++ )
293 {
294 SteamNetworkingMessage_t *msg = messages[i];
295
296 if( msg->m_cbSize < sizeof(netmsg_blank) )
297 {
298 vg_warn( "Discarding message (too small: %d)\n", msg->m_cbSize );
299 continue;
300 }
301
302 netmsg_blank *tmp = msg->m_pData;
303
304 if( tmp->inetmsg_id == k_inetmsg_scoreboard )
305 on_inet_scoreboard( msg );
306
307 SteamAPI_SteamNetworkingMessage_t_Release( msg );
308 }
309 }
310 }
311
312 /*
313 * Subroutine to be connected to main game loop, runs all routines on timers
314 */
315 VG_STATIC void network_update(void)
316 {
317 if( steam_ready )
318 {
319 static double last_update = 0.0;
320 poll_connection();
321
322 if( vg.time > (last_update + 60.0) )
323 {
324 last_update = vg.time;
325
326 if( steam_app_ticket_length )
327 {
328 network_connect_gc();
329 }
330 else
331 {
332 vg_low( "Not making remote connection; app ticket not gotten\n" );
333 }
334 }
335
336 if( vg.time > (last_update + 10.0) &&
337 (cremote_state == k_ESteamNetworkingConnectionState_Connected ))
338 {
339 vg_warn( "Connected to server but no return... disconnecting\n" );
340 SteamAPI_ISteamNetworkingSockets_CloseConnection(
341 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
342 }
343 }
344 }
345
346 VG_STATIC void network_init(void)
347 {
348 if( steam_ready )
349 {
350 steam_register_callback( k_iSteamNetConnectionStatusChangedCallBack,
351 on_server_connect_status );
352 request_auth_ticket();
353 }
354 }
355
356 VG_STATIC void network_end(void)
357 {
358 /* TODO: Fire off any buffered highscores that need to be setn */
359 if( cremote_state == k_ESteamNetworkingConnectionState_Connected ||
360 cremote_state == k_ESteamNetworkingConnectionState_Connecting )
361 {
362 SteamAPI_ISteamNetworkingSockets_CloseConnection(
363 hSteamNetworkingSockets, cremote, 0, NULL, 1 );
364 }
365 }
366
367 #else /* SR_NETWORKED */
368
369 VG_STATIC void network_init(void){}
370 VG_STATIC void network_update(void){}
371 VG_STATIC void network_end(void){}
372
373 #endif /* SR_NETWORKED */
374 #endif /* NETWORK_H */