1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4 
5 This file is part of Quake III Arena source code.
6 
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11 
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20 ===========================================================================
21 */
22 // client.h -- primary header for client
23 
24 #include "../qcommon/q_shared.h"
25 #include "../qcommon/qcommon.h"
26 #include "../renderer/tr_public.h"
27 #include "../ui/ui_public.h"
28 #include "keys.h"
29 #include "snd_public.h"
30 #include "../cgame/cg_public.h"
31 #include "../game/bg_public.h"
32 
33 #ifdef USE_CURL
34 #include "cl_curl.h"
35 #endif /* USE_CURL */
36 
37 #ifdef USE_VOIP
38 #include "speex/speex.h"
39 #include "speex/speex_preprocess.h"
40 #endif
41 
42 // file full of random crap that gets used to create cl_guid
43 #define QKEY_FILE "qkey"
44 #define QKEY_SIZE 2048
45 
46 #define	RETRANSMIT_TIMEOUT	3000	// time between connection packet retransmits
47 
48 // snapshots are a view of the server at a given time
49 typedef struct {
50 	qboolean		valid;			// cleared if delta parsing was invalid
51 	int				snapFlags;		// rate delayed and dropped commands
52 
53 	int				serverTime;		// server time the message is valid for (in msec)
54 
55 	int				messageNum;		// copied from netchan->incoming_sequence
56 	int				deltaNum;		// messageNum the delta is from
57 	int				ping;			// time from when cmdNum-1 was sent to time packet was reeceived
58 	byte			areamask[MAX_MAP_AREA_BYTES];		// portalarea visibility bits
59 
60 	int				cmdNum;			// the next cmdNum the server is expecting
61 	playerState_t	ps;						// complete information about the current player at this time
62 
63 	int				numEntities;			// all of the entities that need to be presented
64 	int				parseEntitiesNum;		// at the time of this snapshot
65 
66 	int				serverCommandNum;		// execute all commands up to this before
67 											// making the snapshot current
68 } clSnapshot_t;
69 
70 
71 
72 /*
73 =============================================================================
74 
75 the clientActive_t structure is wiped completely at every
76 new gamestate_t, potentially several times during an established connection
77 
78 =============================================================================
79 */
80 
81 typedef struct {
82 	int		p_cmdNumber;		// cl.cmdNumber when packet was sent
83 	int		p_serverTime;		// usercmd->serverTime when packet was sent
84 	int		p_realtime;			// cls.realtime when packet was sent
85 } outPacket_t;
86 
87 // the parseEntities array must be large enough to hold PACKET_BACKUP frames of
88 // entities, so that when a delta compressed message arives from the server
89 // it can be un-deltad from the original
90 #define	MAX_PARSE_ENTITIES	2048
91 
92 extern int g_console_field_width;
93 
94 typedef struct {
95 	int			timeoutcount;		// it requres several frames in a timeout condition
96 									// to disconnect, preventing debugging breaks from
97 									// causing immediate disconnects on continue
98 	clSnapshot_t	snap;			// latest received from server
99 
100 	int			serverTime;			// may be paused during play
101 	int			oldServerTime;		// to prevent time from flowing bakcwards
102 	int			oldFrameServerTime;	// to check tournament restarts
103 	int			serverTimeDelta;	// cl.serverTime = cls.realtime + cl.serverTimeDelta
104 									// this value changes as net lag varies
105 	qboolean	extrapolatedSnapshot;	// set if any cgame frame has been forced to extrapolate
106 									// cleared when CL_AdjustTimeDelta looks at it
107 	qboolean	newSnapshots;		// set on parse of any valid packet
108 
109 	gameState_t	gameState;			// configstrings
110 	char		mapname[MAX_QPATH];	// extracted from CS_SERVERINFO
111 
112 	int			parseEntitiesNum;	// index (not anded off) into cl_parse_entities[]
113 
114 	int			mouseDx[2], mouseDy[2];	// added to by mouse events
115 	int			mouseIndex;
116 	int			joystickAxis[MAX_JOYSTICK_AXIS];	// set by joystick events
117 
118 	// cgame communicates a few values to the client system
119 	int			cgameUserCmdValue;	// current weapon to add to usercmd_t
120 	float		cgameSensitivity;
121 
122 	// cmds[cmdNumber] is the predicted command, [cmdNumber-1] is the last
123 	// properly generated command
124 	usercmd_t	cmds[CMD_BACKUP];	// each mesage will send several old cmds
125 	int			cmdNumber;			// incremented each frame, because multiple
126 									// frames may need to be packed into a single packet
127 
128 	outPacket_t	outPackets[PACKET_BACKUP];	// information about each packet we have sent out
129 
130 	// the client maintains its own idea of view angles, which are
131 	// sent to the server each frame.  It is cleared to 0 upon entering each level.
132 	// the server sends a delta each frame which is added to the locally
133 	// tracked view angles to account for standing on rotating objects,
134 	// and teleport direction changes
135 	vec3_t		viewangles;
136 
137 	int			serverId;			// included in each client message so the server
138 												// can tell if it is for a prior map_restart
139 	// big stuff at end of structure so most offsets are 15 bits or less
140 	clSnapshot_t	snapshots[PACKET_BACKUP];
141 
142 	entityState_t	entityBaselines[MAX_GENTITIES];	// for delta compression when not in previous frame
143 
144 	entityState_t	parseEntities[MAX_PARSE_ENTITIES];
145 } clientActive_t;
146 
147 extern	clientActive_t		cl;
148 
149 /*
150 =============================================================================
151 
152 the clientConnection_t structure is wiped when disconnecting from a server,
153 either to go to a full screen console, play a demo, or connect to a different server
154 
155 A connection can be to either a server through the network layer or a
156 demo through a file.
157 
158 =============================================================================
159 */
160 
161 #define MAX_TIMEDEMO_DURATIONS	4096
162 
163 typedef struct {
164 
165 	int			clientNum;
166 	int			lastPacketSentTime;			// for retransmits during connection
167 	int			lastPacketTime;				// for timeouts
168 
169 	netadr_t	serverAddress;
170 	int			connectTime;				// for connection retransmits
171 	int			connectPacketCount;			// for display on connection dialog
172 	char		serverMessage[MAX_STRING_TOKENS];	// for display on connection dialog
173 
174 	int			challenge;					// from the server to use for connecting
175 	int			checksumFeed;				// from the server for checksum calculations
176 
177 	// these are our reliable messages that go to the server
178 	int			reliableSequence;
179 	int			reliableAcknowledge;		// the last one the server has executed
180 	char		reliableCommands[MAX_RELIABLE_COMMANDS][MAX_STRING_CHARS];
181 
182 	// server message (unreliable) and command (reliable) sequence
183 	// numbers are NOT cleared at level changes, but continue to
184 	// increase as long as the connection is valid
185 
186 	// message sequence is used by both the network layer and the
187 	// delta compression layer
188 	int			serverMessageSequence;
189 
190 	// reliable messages received from server
191 	int			serverCommandSequence;
192 	int			lastExecutedServerCommand;		// last server command grabbed or executed with CL_GetServerCommand
193 	char		serverCommands[MAX_RELIABLE_COMMANDS][MAX_STRING_CHARS];
194 
195 	// file transfer from server
196 	fileHandle_t download;
197 	char		downloadTempName[MAX_OSPATH];
198 	char		downloadName[MAX_OSPATH];
199 #ifdef USE_CURL
200 	qboolean	cURLEnabled;
201 	qboolean	cURLUsed;
202 	qboolean	cURLDisconnected;
203 	char		downloadURL[MAX_OSPATH];
204 	CURL		*downloadCURL;
205 	CURLM		*downloadCURLM;
206 #endif /* USE_CURL */
207 	int		sv_allowDownload;
208 	char		sv_dlURL[MAX_CVAR_VALUE_STRING];
209 	int			downloadNumber;
210 	int			downloadBlock;	// block we are waiting for
211 	int			downloadCount;	// how many bytes we got
212 	int			downloadSize;	// how many bytes we got
213 	char		downloadList[MAX_INFO_STRING]; // list of paks we need to download
214 	qboolean	downloadRestart;	// if true, we need to do another FS_Restart because we downloaded a pak
215 
216 	// demo information
217 	char		demoName[MAX_QPATH];
218 	qboolean	spDemoRecording;
219 	qboolean	demorecording;
220 	qboolean	demoplaying;
221 	qboolean	demowaiting;	// don't record until a non-delta message is received
222 	qboolean	firstDemoFrameSkipped;
223 	fileHandle_t	demofile;
224 
225 	int			timeDemoFrames;		// counter of rendered frames
226 	int			timeDemoStart;		// cls.realtime before first frame
227 	int			timeDemoBaseTime;	// each frame will be at this time + frameNum * 50
228 	int			timeDemoLastFrame;// time the last frame was rendered
229 	int			timeDemoMinDuration;	// minimum frame duration
230 	int			timeDemoMaxDuration;	// maximum frame duration
231 	unsigned char	timeDemoDurations[ MAX_TIMEDEMO_DURATIONS ];	// log of frame durations
232 
233 #ifdef USE_VOIP
234 	qboolean speexInitialized;
235 	int speexFrameSize;
236 	int speexSampleRate;
237 
238 	// incoming data...
239 	// !!! FIXME: convert from parallel arrays to array of a struct.
240 	SpeexBits speexDecoderBits[MAX_CLIENTS];
241 	void *speexDecoder[MAX_CLIENTS];
242 	byte voipIncomingGeneration[MAX_CLIENTS];
243 	int voipIncomingSequence[MAX_CLIENTS];
244 	float voipGain[MAX_CLIENTS];
245 	qboolean voipIgnore[MAX_CLIENTS];
246 	qboolean voipMuteAll;
247 
248 	// outgoing data...
249 	int voipTarget1;  // these three ints make up a bit mask of 92 bits.
250 	int voipTarget2;  //  the bits say who a VoIP pack is addressed to:
251 	int voipTarget3;  //  (1 << clientnum). See cl_voipSendTarget cvar.
252 	SpeexPreprocessState *speexPreprocessor;
253 	SpeexBits speexEncoderBits;
254 	void *speexEncoder;
255 	int voipOutgoingDataSize;
256 	int voipOutgoingDataFrames;
257 	int voipOutgoingSequence;
258 	byte voipOutgoingGeneration;
259 	byte voipOutgoingData[1024];
260 	float voipPower;
261 #endif
262 
263 	// big stuff at end of structure so most offsets are 15 bits or less
264 	netchan_t	netchan;
265 } clientConnection_t;
266 
267 extern	clientConnection_t clc;
268 
269 /*
270 ==================================================================
271 
272 the clientStatic_t structure is never wiped, and is used even when
273 no client connection is active at all
274 
275 ==================================================================
276 */
277 
278 typedef struct {
279 	netadr_t	adr;
280 	int			start;
281 	int			time;
282 	char		info[MAX_INFO_STRING];
283 } ping_t;
284 
285 typedef struct {
286 	netadr_t	adr;
287 	char	  	hostName[MAX_NAME_LENGTH];
288 	char	  	mapName[MAX_NAME_LENGTH];
289 	char	  	game[MAX_NAME_LENGTH];
290 	int			netType;
291 	int			gameType;
292 	int		  	clients;
293 	int		  	maxClients;
294 	int			minPing;
295 	int			maxPing;
296 	int			ping;
297 	qboolean	visible;
298 	int			punkbuster;
299 } serverInfo_t;
300 
301 typedef struct {
302 	connstate_t	state;				// connection status
303 
304 	qboolean	cddialog;			// bring up the cd needed dialog next frame
305 
306 	char		servername[MAX_OSPATH];		// name of server from original connect (used by reconnect)
307 
308 	// when the server clears the hunk, all of these must be restarted
309 	qboolean	rendererStarted;
310 	qboolean	soundStarted;
311 	qboolean	soundRegistered;
312 	qboolean	uiStarted;
313 	qboolean	cgameStarted;
314 
315 	int			framecount;
316 	int			frametime;			// msec since last frame
317 
318 	int			realtime;			// ignores pause
319 	int			realFrametime;		// ignoring pause, so console always works
320 
321 	int			numlocalservers;
322 	serverInfo_t	localServers[MAX_OTHER_SERVERS];
323 
324 	int			numglobalservers;
325 	serverInfo_t  globalServers[MAX_GLOBAL_SERVERS];
326 	// additional global servers
327 	int			numGlobalServerAddresses;
328 	netadr_t		globalServerAddresses[MAX_GLOBAL_SERVERS];
329 
330 	int			numfavoriteservers;
331 	serverInfo_t	favoriteServers[MAX_OTHER_SERVERS];
332 
333 	int pingUpdateSource;		// source currently pinging or updating
334 
335 	// update server info
336 	netadr_t	updateServer;
337 	char		updateChallenge[MAX_TOKEN_CHARS];
338 	char		updateInfoString[MAX_INFO_STRING];
339 
340 	netadr_t	authorizeServer;
341 
342 	// rendering info
343 	glconfig_t	glconfig;
344 	qhandle_t	charSetShader;
345 	qhandle_t	whiteShader;
346 	qhandle_t	consoleShader;
347 } clientStatic_t;
348 
349 extern	clientStatic_t		cls;
350 
351 //=============================================================================
352 
353 extern	vm_t			*cgvm;	// interface to cgame dll or vm
354 extern	vm_t			*uivm;	// interface to ui dll or vm
355 extern	refexport_t		re;		// interface to refresh .dll
356 
357 
358 //
359 // cvars
360 //
361 extern	cvar_t	*cl_nodelta;
362 extern	cvar_t	*cl_debugMove;
363 extern	cvar_t	*cl_noprint;
364 extern	cvar_t	*cl_timegraph;
365 extern	cvar_t	*cl_maxpackets;
366 extern	cvar_t	*cl_packetdup;
367 extern	cvar_t	*cl_shownet;
368 extern	cvar_t	*cl_showSend;
369 extern	cvar_t	*cl_timeNudge;
370 extern	cvar_t	*cl_showTimeDelta;
371 extern	cvar_t	*cl_freezeDemo;
372 
373 extern	cvar_t	*cl_yawspeed;
374 extern	cvar_t	*cl_pitchspeed;
375 extern	cvar_t	*cl_run;
376 extern	cvar_t	*cl_anglespeedkey;
377 
378 extern	cvar_t	*cl_sensitivity;
379 extern	cvar_t	*cl_freelook;
380 
381 extern	cvar_t	*cl_mouseAccel;
382 extern	cvar_t	*cl_showMouseRate;
383 
384 extern	cvar_t	*m_pitch;
385 extern	cvar_t	*m_yaw;
386 extern	cvar_t	*m_forward;
387 extern	cvar_t	*m_side;
388 extern	cvar_t	*m_filter;
389 
390 extern	cvar_t	*cl_timedemo;
391 extern	cvar_t	*cl_aviFrameRate;
392 extern	cvar_t	*cl_aviMotionJpeg;
393 
394 extern	cvar_t	*cl_activeAction;
395 
396 extern	cvar_t	*cl_allowDownload;
397 extern  cvar_t  *cl_downloadMethod;
398 extern	cvar_t	*cl_conXOffset;
399 extern	cvar_t	*cl_inGameVideo;
400 
401 extern	cvar_t	*cl_lanForcePackets;
402 extern	cvar_t	*cl_autoRecordDemo;
403 
404 extern	cvar_t	*cl_consoleKeys;
405 
406 #ifdef USE_MUMBLE
407 extern	cvar_t	*cl_useMumble;
408 extern	cvar_t	*cl_mumbleScale;
409 #endif
410 
411 #ifdef USE_VOIP
412 // cl_voipSendTarget is a string: "all" to broadcast to everyone, "none" to
413 //  send to no one, or a comma-separated list of client numbers:
414 //  "0,7,2,23" ... an empty string is treated like "all".
415 extern	cvar_t	*cl_voipUseVAD;
416 extern	cvar_t	*cl_voipVADThreshold;
417 extern	cvar_t	*cl_voipSend;
418 extern	cvar_t	*cl_voipSendTarget;
419 extern	cvar_t	*cl_voipGainDuringCapture;
420 extern	cvar_t	*cl_voipCaptureMult;
421 extern	cvar_t	*cl_voipShowMeter;
422 extern	cvar_t	*cl_voip;
423 #endif
424 
425 //=================================================
426 
427 //
428 // cl_main
429 //
430 
431 void CL_Init (void);
432 void CL_FlushMemory(void);
433 void CL_ShutdownAll(void);
434 void CL_AddReliableCommand( const char *cmd );
435 
436 void CL_StartHunkUsers( qboolean rendererOnly );
437 
438 void CL_Disconnect_f (void);
439 void CL_GetChallengePacket (void);
440 void CL_Vid_Restart_f( void );
441 void CL_Snd_Restart_f (void);
442 void CL_StartDemoLoop( void );
443 void CL_NextDemo( void );
444 void CL_ReadDemoMessage( void );
445 void CL_StopRecord_f(void);
446 
447 void CL_InitDownloads(void);
448 void CL_NextDownload(void);
449 
450 void CL_GetPing( int n, char *buf, int buflen, int *pingtime );
451 void CL_GetPingInfo( int n, char *buf, int buflen );
452 void CL_ClearPing( int n );
453 int CL_GetPingQueueCount( void );
454 
455 void CL_ShutdownRef( void );
456 void CL_InitRef( void );
457 #ifndef STANDALONE
458 qboolean CL_CDKeyValidate( const char *key, const char *checksum );
459 #endif
460 int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen );
461 
462 qboolean CL_CheckPaused(void);
463 
464 //
465 // cl_input
466 //
467 typedef struct {
468 	int			down[2];		// key nums holding it down
469 	unsigned	downtime;		// msec timestamp
470 	unsigned	msec;			// msec down this frame if both a down and up happened
471 	qboolean	active;			// current state
472 	qboolean	wasPressed;		// set when down, not cleared when up
473 } kbutton_t;
474 
475 extern	kbutton_t	in_mlook, in_klook;
476 extern 	kbutton_t 	in_strafe;
477 extern 	kbutton_t 	in_speed;
478 
479 #ifdef USE_VOIP
480 extern 	kbutton_t 	in_voiprecord;
481 #endif
482 
483 void CL_InitInput (void);
484 void CL_SendCmd (void);
485 void CL_ClearState (void);
486 void CL_ReadPackets (void);
487 
488 void CL_WritePacket( void );
489 void IN_CenterView (void);
490 
491 void CL_VerifyCode( void );
492 
493 float CL_KeyState (kbutton_t *key);
494 int Key_StringToKeynum( char *str );
495 char *Key_KeynumToString (int keynum);
496 
497 //
498 // cl_parse.c
499 //
500 extern int cl_connectedToPureServer;
501 extern int cl_connectedToCheatServer;
502 
503 #ifdef USE_VOIP
504 extern int cl_connectedToVoipServer;
505 void CL_Voip_f( void );
506 #endif
507 
508 void CL_SystemInfoChanged( void );
509 void CL_ParseServerMessage( msg_t *msg );
510 
511 //====================================================================
512 
513 void	CL_ServerInfoPacket( netadr_t from, msg_t *msg );
514 void	CL_LocalServers_f( void );
515 void	CL_GlobalServers_f( void );
516 void	CL_FavoriteServers_f( void );
517 void	CL_Ping_f( void );
518 qboolean CL_UpdateVisiblePings_f( int source );
519 
520 
521 //
522 // console
523 //
524 void Con_DrawCharacter (int cx, int line, int num);
525 
526 void Con_CheckResize (void);
527 void Con_Init (void);
528 void Con_Clear_f (void);
529 void Con_ToggleConsole_f (void);
530 void Con_DrawNotify (void);
531 void Con_ClearNotify (void);
532 void Con_RunConsole (void);
533 void Con_DrawConsole (void);
534 void Con_PageUp( void );
535 void Con_PageDown( void );
536 void Con_Top( void );
537 void Con_Bottom( void );
538 void Con_Close( void );
539 
540 void CL_LoadConsoleHistory( void );
541 void CL_SaveConsoleHistory( void );
542 
543 //
544 // cl_scrn.c
545 //
546 void	SCR_Init (void);
547 void	SCR_UpdateScreen (void);
548 
549 void	SCR_DebugGraph (float value, int color);
550 
551 int		SCR_GetBigStringWidth( const char *str );	// returns in virtual 640x480 coordinates
552 
553 void	SCR_AdjustFrom640( float *x, float *y, float *w, float *h );
554 void	SCR_FillRect( float x, float y, float width, float height,
555 					 const float *color );
556 void	SCR_DrawPic( float x, float y, float width, float height, qhandle_t hShader );
557 void	SCR_DrawNamedPic( float x, float y, float width, float height, const char *picname );
558 
559 void	SCR_DrawBigString( int x, int y, const char *s, float alpha, qboolean noColorEscape );			// draws a string with embedded color control characters with fade
560 void	SCR_DrawBigStringColor( int x, int y, const char *s, vec4_t color, qboolean noColorEscape );	// ignores embedded color control characters
561 void	SCR_DrawSmallStringExt( int x, int y, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape );
562 void	SCR_DrawSmallChar( int x, int y, int ch );
563 
564 
565 //
566 // cl_cin.c
567 //
568 
569 void CL_PlayCinematic_f( void );
570 void SCR_DrawCinematic (void);
571 void SCR_RunCinematic (void);
572 void SCR_StopCinematic (void);
573 int CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits);
574 e_status CIN_StopCinematic(int handle);
575 e_status CIN_RunCinematic (int handle);
576 void CIN_DrawCinematic (int handle);
577 void CIN_SetExtents (int handle, int x, int y, int w, int h);
578 void CIN_SetLooping (int handle, qboolean loop);
579 void CIN_UploadCinematic(int handle);
580 void CIN_CloseAllVideos(void);
581 
582 //
583 // cl_cgame.c
584 //
585 void CL_InitCGame( void );
586 void CL_ShutdownCGame( void );
587 qboolean CL_GameCommand( void );
588 void CL_CGameRendering( stereoFrame_t stereo );
589 void CL_SetCGameTime( void );
590 void CL_FirstSnapshot( void );
591 void CL_ShaderStateChanged(void);
592 
593 //
594 // cl_ui.c
595 //
596 void CL_InitUI( void );
597 void CL_ShutdownUI( void );
598 int Key_GetCatcher( void );
599 void Key_SetCatcher( int catcher );
600 void LAN_LoadCachedServers( void );
601 void LAN_SaveServersToCache( void );
602 
603 
604 //
605 // cl_net_chan.c
606 //
607 void CL_Netchan_Transmit( netchan_t *chan, msg_t* msg);	//int length, const byte *data );
608 void CL_Netchan_TransmitNextFragment( netchan_t *chan );
609 qboolean CL_Netchan_Process( netchan_t *chan, msg_t *msg );
610 
611 //
612 // cl_avi.c
613 //
614 qboolean CL_OpenAVIForWriting( const char *filename );
615 void CL_TakeVideoFrame( void );
616 void CL_WriteAVIVideoFrame( const byte *imageBuffer, int size );
617 void CL_WriteAVIAudioFrame( const byte *pcmBuffer, int size );
618 qboolean CL_CloseAVI( void );
619 qboolean CL_VideoRecording( void );
620 
621 //
622 // cl_main.c
623 //
624 void CL_WriteDemoMessage ( msg_t *msg, int headerBytes );
625 
626