Debian Codegraph @

code/client/cl_cgame.c

raw symbols SCIP
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 // cl_cgame.c -- client system interaction with client game
23
24 #include "client.h"
25
26 #include "../botlib/botlib.h"
27
28 #ifdef USE_MUMBLE
29 #include "libmumblelink.h"
30 #endif
31
32 extern botlib_export_t *botlib_export;
33
34 extern qboolean loadCamera(const char *name);
35 extern void startCamera(int time);
36 extern qboolean getCameraInfo(int time, vec3_t *origin, vec3_t *angles);
37
38 /*
39 ====================
40 CL_GetGameState
41 ====================
42 */
43 void CL_GetGameState( gameState_t *gs ) {
44 *gs = cl.gameState;
45 }
46
47 /*
48 ====================
49 CL_GetGlconfig
50 ====================
51 */
52 void CL_GetGlconfig( glconfig_t *glconfig ) {
53 *glconfig = cls.glconfig;
54 }
55
56
57 /*
58 ====================
59 CL_GetUserCmd
60 ====================
61 */
62 qboolean CL_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) {
63 // cmds[cmdNumber] is the last properly generated command
64
65 // can't return anything that we haven't created yet
66 if ( cmdNumber > cl.cmdNumber ) {
67 Com_Error( ERR_DROP, "CL_GetUserCmd: %i >= %i", cmdNumber, cl.cmdNumber );
68 }
69
70 // the usercmd has been overwritten in the wrapping
71 // buffer because it is too far out of date
72 if ( cmdNumber <= cl.cmdNumber - CMD_BACKUP ) {
73 return qfalse;
74 }
75
76 *ucmd = cl.cmds[ cmdNumber & CMD_MASK ];
77
78 return qtrue;
79 }
80
81 int CL_GetCurrentCmdNumber( void ) {
82 return cl.cmdNumber;
83 }
84
85
86 /*
87 ====================
88 CL_GetParseEntityState
89 ====================
90 */
91 qboolean CL_GetParseEntityState( int parseEntityNumber, entityState_t *state ) {
92 // can't return anything that hasn't been parsed yet
93 if ( parseEntityNumber >= cl.parseEntitiesNum ) {
94 Com_Error( ERR_DROP, "CL_GetParseEntityState: %i >= %i",
95 parseEntityNumber, cl.parseEntitiesNum );
96 }
97
98 // can't return anything that has been overwritten in the circular buffer
99 if ( parseEntityNumber <= cl.parseEntitiesNum - MAX_PARSE_ENTITIES ) {
100 return qfalse;
101 }
102
103 *state = cl.parseEntities[ parseEntityNumber & ( MAX_PARSE_ENTITIES - 1 ) ];
104 return qtrue;
105 }
106
107 /*
108 ====================
109 CL_GetCurrentSnapshotNumber
110 ====================
111 */
112 void CL_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) {
113 *snapshotNumber = cl.snap.messageNum;
114 *serverTime = cl.snap.serverTime;
115 }
116
117 /*
118 ====================
119 CL_GetSnapshot
120 ====================
121 */
122 qboolean CL_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) {
123 clSnapshot_t *clSnap;
124 int i, count;
125
126 if ( snapshotNumber > cl.snap.messageNum ) {
127 Com_Error( ERR_DROP, "CL_GetSnapshot: snapshotNumber > cl.snapshot.messageNum" );
128 }
129
130 // if the frame has fallen out of the circular buffer, we can't return it
131 if ( cl.snap.messageNum - snapshotNumber >= PACKET_BACKUP ) {
132 return qfalse;
133 }
134
135 // if the frame is not valid, we can't return it
136 clSnap = &cl.snapshots[snapshotNumber & PACKET_MASK];
137 if ( !clSnap->valid ) {
138 return qfalse;
139 }
140
141 // if the entities in the frame have fallen out of their
142 // circular buffer, we can't return it
143 if ( cl.parseEntitiesNum - clSnap->parseEntitiesNum >= MAX_PARSE_ENTITIES ) {
144 return qfalse;
145 }
146
147 // write the snapshot
148 snapshot->snapFlags = clSnap->snapFlags;
149 snapshot->serverCommandSequence = clSnap->serverCommandNum;
150 snapshot->ping = clSnap->ping;
151 snapshot->serverTime = clSnap->serverTime;
152 Com_Memcpy( snapshot->areamask, clSnap->areamask, sizeof( snapshot->areamask ) );
153 snapshot->ps = clSnap->ps;
154 count = clSnap->numEntities;
155 if ( count > MAX_ENTITIES_IN_SNAPSHOT ) {
156 Com_DPrintf( "CL_GetSnapshot: truncated %i entities to %i\n", count, MAX_ENTITIES_IN_SNAPSHOT );
157 count = MAX_ENTITIES_IN_SNAPSHOT;
158 }
159 snapshot->numEntities = count;
160 for ( i = 0 ; i < count ; i++ ) {
161 snapshot->entities[i] =
162 cl.parseEntities[ ( clSnap->parseEntitiesNum + i ) & (MAX_PARSE_ENTITIES-1) ];
163 }
164
165 // FIXME: configstring changes and server commands!!!
166
167 return qtrue;
168 }
169
170 /*
171 =====================
172 CL_SetUserCmdValue
173 =====================
174 */
175 void CL_SetUserCmdValue( int userCmdValue, float sensitivityScale ) {
176 cl.cgameUserCmdValue = userCmdValue;
177 cl.cgameSensitivity = sensitivityScale;
178 }
179
180 /*
181 =====================
182 CL_AddCgameCommand
183 =====================
184 */
185 void CL_AddCgameCommand( const char *cmdName ) {
186 Cmd_AddCommand( cmdName, NULL );
187 }
188
189
190 /*
191 =====================
192 CL_ConfigstringModified
193 =====================
194 */
195 void CL_ConfigstringModified( void ) {
196 char *old, *s;
197 int i, index;
198 char *dup;
199 gameState_t oldGs;
200 int len;
201
202 index = atoi( Cmd_Argv(1) );
203 if ( index < 0 || index >= MAX_CONFIGSTRINGS ) {
204 Com_Error( ERR_DROP, "CL_ConfigstringModified: bad index %i", index );
205 }
206 // get everything after "cs <num>"
207 s = Cmd_ArgsFrom(2);
208
209 old = cl.gameState.stringData + cl.gameState.stringOffsets[ index ];
210 if ( !strcmp( old, s ) ) {
211 return; // unchanged
212 }
213
214 // build the new gameState_t
215 oldGs = cl.gameState;
216
217 Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
218
219 // leave the first 0 for uninitialized strings
220 cl.gameState.dataCount = 1;
221
222 for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
223 if ( i == index ) {
224 dup = s;
225 } else {
226 dup = oldGs.stringData + oldGs.stringOffsets[ i ];
227 }
228 if ( !dup[0] ) {
229 continue; // leave with the default empty string
230 }
231
232 len = strlen( dup );
233
234 if ( len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS ) {
235 Com_Error( ERR_DROP, "MAX_GAMESTATE_CHARS exceeded" );
236 }
237
238 // append it to the gameState string buffer
239 cl.gameState.stringOffsets[ i ] = cl.gameState.dataCount;
240 Com_Memcpy( cl.gameState.stringData + cl.gameState.dataCount, dup, len + 1 );
241 cl.gameState.dataCount += len + 1;
242 }
243
244 if ( index == CS_SYSTEMINFO ) {
245 // parse serverId and other cvars
246 CL_SystemInfoChanged();
247 }
248
249 }
250
251
252 /*
253 ===================
254 CL_GetServerCommand
255
256 Set up argc/argv for the given command
257 ===================
258 */
259 qboolean CL_GetServerCommand( int serverCommandNumber ) {
260 char *s;
261 char *cmd;
262 static char bigConfigString[BIG_INFO_STRING];
263 int argc;
264
265 // if we have irretrievably lost a reliable command, drop the connection
266 if ( serverCommandNumber <= clc.serverCommandSequence - MAX_RELIABLE_COMMANDS ) {
267 // when a demo record was started after the client got a whole bunch of
268 // reliable commands then the client never got those first reliable commands
269 if ( clc.demoplaying )
270 return qfalse;
271 Com_Error( ERR_DROP, "CL_GetServerCommand: a reliable command was cycled out" );
272 return qfalse;
273 }
274
275 if ( serverCommandNumber > clc.serverCommandSequence ) {
276 Com_Error( ERR_DROP, "CL_GetServerCommand: requested a command not received" );
277 return qfalse;
278 }
279
280 s = clc.serverCommands[ serverCommandNumber & ( MAX_RELIABLE_COMMANDS - 1 ) ];
281 clc.lastExecutedServerCommand = serverCommandNumber;
282
283 Com_DPrintf( "serverCommand: %i : %s\n", serverCommandNumber, s );
284
285 rescan:
286 Cmd_TokenizeString( s );
287 cmd = Cmd_Argv(0);
288 argc = Cmd_Argc();
289
290 if ( !strcmp( cmd, "disconnect" ) ) {
291 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=552
292 // allow server to indicate why they were disconnected
293 if ( argc >= 2 )
294 Com_Error( ERR_SERVERDISCONNECT, "Server disconnected - %s", Cmd_Argv( 1 ) );
295 else
296 Com_Error( ERR_SERVERDISCONNECT, "Server disconnected" );
297 }
298
299 if ( !strcmp( cmd, "bcs0" ) ) {
300 Com_sprintf( bigConfigString, BIG_INFO_STRING, "cs %s \"%s", Cmd_Argv(1), Cmd_Argv(2) );
301 return qfalse;
302 }
303
304 if ( !strcmp( cmd, "bcs1" ) ) {
305 s = Cmd_Argv(2);
306 if( strlen(bigConfigString) + strlen(s) >= BIG_INFO_STRING ) {
307 Com_Error( ERR_DROP, "bcs exceeded BIG_INFO_STRING" );
308 }
309 strcat( bigConfigString, s );
310 return qfalse;
311 }
312
313 if ( !strcmp( cmd, "bcs2" ) ) {
314 s = Cmd_Argv(2);
315 if( strlen(bigConfigString) + strlen(s) + 1 >= BIG_INFO_STRING ) {
316 Com_Error( ERR_DROP, "bcs exceeded BIG_INFO_STRING" );
317 }
318 strcat( bigConfigString, s );
319 strcat( bigConfigString, "\"" );
320 s = bigConfigString;
321 goto rescan;
322 }
323
324 if ( !strcmp( cmd, "cs" ) ) {
325 CL_ConfigstringModified();
326 // reparse the string, because CL_ConfigstringModified may have done another Cmd_TokenizeString()
327 Cmd_TokenizeString( s );
328 return qtrue;
329 }
330
331 if ( !strcmp( cmd, "map_restart" ) ) {
332 // clear notify lines and outgoing commands before passing
333 // the restart to the cgame
334 Con_ClearNotify();
335 // reparse the string, because Con_ClearNotify() may have done another Cmd_TokenizeString()
336 Cmd_TokenizeString( s );
337 Com_Memset( cl.cmds, 0, sizeof( cl.cmds ) );
338 return qtrue;
339 }
340
341 // the clientLevelShot command is used during development
342 // to generate 128*128 screenshots from the intermission
343 // point of levels for the menu system to use
344 // we pass it along to the cgame to make appropriate adjustments,
345 // but we also clear the console and notify lines here
346 if ( !strcmp( cmd, "clientLevelShot" ) ) {
347 // don't do it if we aren't running the server locally,
348 // otherwise malicious remote servers could overwrite
349 // the existing thumbnails
350 if ( !com_sv_running->integer ) {
351 return qfalse;
352 }
353 // close the console
354 Con_Close();
355 // take a special screenshot next frame
356 Cbuf_AddText( "wait ; wait ; wait ; wait ; screenshot levelshot\n" );
357 return qtrue;
358 }
359
360 // we may want to put a "connect to other server" command here
361
362 // cgame can now act on the command
363 return qtrue;
364 }
365
366
367 /*
368 ====================
369 CL_CM_LoadMap
370
371 Just adds default parameters that cgame doesn't need to know about
372 ====================
373 */
374 void CL_CM_LoadMap( const char *mapname ) {
375 int checksum;
376
377 CM_LoadMap( mapname, qtrue, &checksum );
378 }
379
380 /*
381 ====================
382 CL_ShutdownCGame
383
384 ====================
385 */
386 void CL_ShutdownCGame( void ) {
387 Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CGAME );
388 cls.cgameStarted = qfalse;
389 if ( !cgvm ) {
390 return;
391 }
392 VM_Call( cgvm, CG_SHUTDOWN );
393 VM_Free( cgvm );
394 cgvm = NULL;
395 }
396
397 static int FloatAsInt( float f ) {
398 floatint_t fi;
399 fi.f = f;
400 return fi.i;
401 }
402
403 /*
404 ====================
405 CL_CgameSystemCalls
406
407 The cgame module is making a system call
408 ====================
409 */
410 intptr_t CL_CgameSystemCalls( intptr_t *args ) {
411 switch( args[0] ) {
412 case CG_PRINT:
413 Com_Printf( "%s", (const char*)VMA(1) );
414 return 0;
415 case CG_ERROR:
416 Com_Error( ERR_DROP, "%s", (const char*)VMA(1) );
417 return 0;
418 case CG_MILLISECONDS:
419 return Sys_Milliseconds();
420 case CG_CVAR_REGISTER:
421 Cvar_Register( VMA(1), VMA(2), VMA(3), args[4] );
422 return 0;
423 case CG_CVAR_UPDATE:
424 Cvar_Update( VMA(1) );
425 return 0;
426 case CG_CVAR_SET:
427 Cvar_SetSafe( VMA(1), VMA(2) );
428 return 0;
429 case CG_CVAR_VARIABLESTRINGBUFFER:
430 Cvar_VariableStringBuffer( VMA(1), VMA(2), args[3] );
431 return 0;
432 case CG_ARGC:
433 return Cmd_Argc();
434 case CG_ARGV:
435 Cmd_ArgvBuffer( args[1], VMA(2), args[3] );
436 return 0;
437 case CG_ARGS:
438 Cmd_ArgsBuffer( VMA(1), args[2] );
439 return 0;
440 case CG_FS_FOPENFILE:
441 return FS_FOpenFileByMode( VMA(1), VMA(2), args[3] );
442 case CG_FS_READ:
443 FS_Read( VMA(1), args[2], args[3] );
444 return 0;
445 case CG_FS_WRITE:
446 FS_Write( VMA(1), args[2], args[3] );
447 return 0;
448 case CG_FS_FCLOSEFILE:
449 FS_FCloseFile( args[1] );
450 return 0;
451 case CG_FS_SEEK:
452 return FS_Seek( args[1], args[2], args[3] );
453 case CG_SENDCONSOLECOMMAND:
454 Cbuf_AddText( VMA(1) );
455 return 0;
456 case CG_ADDCOMMAND:
457 CL_AddCgameCommand( VMA(1) );
458 return 0;
459 case CG_REMOVECOMMAND:
460 Cmd_RemoveCommandSafe( VMA(1) );
461 return 0;
462 case CG_SENDCLIENTCOMMAND:
463 CL_AddReliableCommand(VMA(1), qfalse);
464 return 0;
465 case CG_UPDATESCREEN:
466 // this is used during lengthy level loading, so pump message loop
467 // Com_EventLoop(); // FIXME: if a server restarts here, BAD THINGS HAPPEN!
468 // We can't call Com_EventLoop here, a restart will crash and this _does_ happen
469 // if there is a map change while we are downloading at pk3.
470 // ZOID
471 SCR_UpdateScreen();
472 return 0;
473 case CG_CM_LOADMAP:
474 CL_CM_LoadMap( VMA(1) );
475 return 0;
476 case CG_CM_NUMINLINEMODELS:
477 return CM_NumInlineModels();
478 case CG_CM_INLINEMODEL:
479 return CM_InlineModel( args[1] );
480 case CG_CM_TEMPBOXMODEL:
481 return CM_TempBoxModel( VMA(1), VMA(2), /*int capsule*/ qfalse );
482 case CG_CM_TEMPCAPSULEMODEL:
483 return CM_TempBoxModel( VMA(1), VMA(2), /*int capsule*/ qtrue );
484 case CG_CM_POINTCONTENTS:
485 return CM_PointContents( VMA(1), args[2] );
486 case CG_CM_TRANSFORMEDPOINTCONTENTS:
487 return CM_TransformedPointContents( VMA(1), args[2], VMA(3), VMA(4) );
488 case CG_CM_BOXTRACE:
489 CM_BoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], /*int capsule*/ qfalse );
490 return 0;
491 case CG_CM_CAPSULETRACE:
492 CM_BoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], /*int capsule*/ qtrue );
493 return 0;
494 case CG_CM_TRANSFORMEDBOXTRACE:
495 CM_TransformedBoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], VMA(8), VMA(9), /*int capsule*/ qfalse );
496 return 0;
497 case CG_CM_TRANSFORMEDCAPSULETRACE:
498 CM_TransformedBoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], VMA(8), VMA(9), /*int capsule*/ qtrue );
499 return 0;
500 case CG_CM_MARKFRAGMENTS:
501 return re.MarkFragments( args[1], VMA(2), VMA(3), args[4], VMA(5), args[6], VMA(7) );
502 case CG_S_STARTSOUND:
503 S_StartSound( VMA(1), args[2], args[3], args[4] );
504 return 0;
505 case CG_S_STARTLOCALSOUND:
506 S_StartLocalSound( args[1], args[2] );
507 return 0;
508 case CG_S_CLEARLOOPINGSOUNDS:
509 S_ClearLoopingSounds(args[1]);
510 return 0;
511 case CG_S_ADDLOOPINGSOUND:
512 S_AddLoopingSound( args[1], VMA(2), VMA(3), args[4] );
513 return 0;
514 case CG_S_ADDREALLOOPINGSOUND:
515 S_AddRealLoopingSound( args[1], VMA(2), VMA(3), args[4] );
516 return 0;
517 case CG_S_STOPLOOPINGSOUND:
518 S_StopLoopingSound( args[1] );
519 return 0;
520 case CG_S_UPDATEENTITYPOSITION:
521 S_UpdateEntityPosition( args[1], VMA(2) );
522 return 0;
523 case CG_S_RESPATIALIZE:
524 S_Respatialize( args[1], VMA(2), VMA(3), args[4] );
525 return 0;
526 case CG_S_REGISTERSOUND:
527 return S_RegisterSound( VMA(1), args[2] );
528 case CG_S_STARTBACKGROUNDTRACK:
529 S_StartBackgroundTrack( VMA(1), VMA(2) );
530 return 0;
531 case CG_R_LOADWORLDMAP:
532 re.LoadWorld( VMA(1) );
533 return 0;
534 case CG_R_REGISTERMODEL:
535 return re.RegisterModel( VMA(1) );
536 case CG_R_REGISTERSKIN:
537 return re.RegisterSkin( VMA(1) );
538 case CG_R_REGISTERSHADER:
539 return re.RegisterShader( VMA(1) );
540 case CG_R_REGISTERSHADERNOMIP:
541 return re.RegisterShaderNoMip( VMA(1) );
542 case CG_R_REGISTERFONT:
543 re.RegisterFont( VMA(1), args[2], VMA(3));
544 return 0;
545 case CG_R_CLEARSCENE:
546 re.ClearScene();
547 return 0;
548 case CG_R_ADDREFENTITYTOSCENE:
549 re.AddRefEntityToScene( VMA(1) );
550 return 0;
551 case CG_R_ADDPOLYTOSCENE:
552 re.AddPolyToScene( args[1], args[2], VMA(3), 1 );
553 return 0;
554 case CG_R_ADDPOLYSTOSCENE:
555 re.AddPolyToScene( args[1], args[2], VMA(3), args[4] );
556 return 0;
557 case CG_R_LIGHTFORPOINT:
558 return re.LightForPoint( VMA(1), VMA(2), VMA(3), VMA(4) );
559 case CG_R_ADDLIGHTTOSCENE:
560 re.AddLightToScene( VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) );
561 return 0;
562 case CG_R_ADDADDITIVELIGHTTOSCENE:
563 re.AddAdditiveLightToScene( VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) );
564 return 0;
565 case CG_R_RENDERSCENE:
566 re.RenderScene( VMA(1) );
567 return 0;
568 case CG_R_SETCOLOR:
569 re.SetColor( VMA(1) );
570 return 0;
571 case CG_R_DRAWSTRETCHPIC:
572 re.DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] );
573 return 0;
574 case CG_R_MODELBOUNDS:
575 re.ModelBounds( args[1], VMA(2), VMA(3) );
576 return 0;
577 case CG_R_LERPTAG:
578 return re.LerpTag( VMA(1), args[2], args[3], args[4], VMF(5), VMA(6) );
579 case CG_GETGLCONFIG:
580 CL_GetGlconfig( VMA(1) );
581 return 0;
582 case CG_GETGAMESTATE:
583 CL_GetGameState( VMA(1) );
584 return 0;
585 case CG_GETCURRENTSNAPSHOTNUMBER:
586 CL_GetCurrentSnapshotNumber( VMA(1), VMA(2) );
587 return 0;
588 case CG_GETSNAPSHOT:
589 return CL_GetSnapshot( args[1], VMA(2) );
590 case CG_GETSERVERCOMMAND:
591 return CL_GetServerCommand( args[1] );
592 case CG_GETCURRENTCMDNUMBER:
593 return CL_GetCurrentCmdNumber();
594 case CG_GETUSERCMD:
595 return CL_GetUserCmd( args[1], VMA(2) );
596 case CG_SETUSERCMDVALUE:
597 CL_SetUserCmdValue( args[1], VMF(2) );
598 return 0;
599 case CG_MEMORY_REMAINING:
600 return Hunk_MemoryRemaining();
601 case CG_KEY_ISDOWN:
602 return Key_IsDown( args[1] );
603 case CG_KEY_GETCATCHER:
604 return Key_GetCatcher();
605 case CG_KEY_SETCATCHER:
606 // Don't allow the cgame module to close the console
607 Key_SetCatcher( args[1] | ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) );
608 return 0;
609 case CG_KEY_GETKEY:
610 return Key_GetKey( VMA(1) );
611
612
613
614 case CG_MEMSET:
615 Com_Memset( VMA(1), args[2], args[3] );
616 return 0;
617 case CG_MEMCPY:
618 Com_Memcpy( VMA(1), VMA(2), args[3] );
619 return 0;
620 case CG_STRNCPY:
621 strncpy( VMA(1), VMA(2), args[3] );
622 return args[1];
623 case CG_SIN:
624 return FloatAsInt( sin( VMF(1) ) );
625 case CG_COS:
626 return FloatAsInt( cos( VMF(1) ) );
627 case CG_ATAN2:
628 return FloatAsInt( atan2( VMF(1), VMF(2) ) );
629 case CG_SQRT:
630 return FloatAsInt( sqrt( VMF(1) ) );
631 case CG_FLOOR:
632 return FloatAsInt( floor( VMF(1) ) );
633 case CG_CEIL:
634 return FloatAsInt( ceil( VMF(1) ) );
635 case CG_ACOS:
636 return FloatAsInt( Q_acos( VMF(1) ) );
637
638 case CG_PC_ADD_GLOBAL_DEFINE:
639 return botlib_export->PC_AddGlobalDefine( VMA(1) );
640 case CG_PC_LOAD_SOURCE:
641 return botlib_export->PC_LoadSourceHandle( VMA(1) );
642 case CG_PC_FREE_SOURCE:
643 return botlib_export->PC_FreeSourceHandle( args[1] );
644 case CG_PC_READ_TOKEN:
645 return botlib_export->PC_ReadTokenHandle( args[1], VMA(2) );
646 case CG_PC_SOURCE_FILE_AND_LINE:
647 return botlib_export->PC_SourceFileAndLine( args[1], VMA(2), VMA(3) );
648
649 case CG_S_STOPBACKGROUNDTRACK:
650 S_StopBackgroundTrack();
651 return 0;
652
653 case CG_REAL_TIME:
654 return Com_RealTime( VMA(1) );
655 case CG_SNAPVECTOR:
656 Q_SnapVector(VMA(1));
657 return 0;
658
659 case CG_CIN_PLAYCINEMATIC:
660 return CIN_PlayCinematic(VMA(1), args[2], args[3], args[4], args[5], args[6]);
661
662 case CG_CIN_STOPCINEMATIC:
663 return CIN_StopCinematic(args[1]);
664
665 case CG_CIN_RUNCINEMATIC:
666 return CIN_RunCinematic(args[1]);
667
668 case CG_CIN_DRAWCINEMATIC:
669 CIN_DrawCinematic(args[1]);
670 return 0;
671
672 case CG_CIN_SETEXTENTS:
673 CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]);
674 return 0;
675
676 case CG_R_REMAP_SHADER:
677 re.RemapShader( VMA(1), VMA(2), VMA(3) );
678 return 0;
679
680 /*
681 case CG_LOADCAMERA:
682 return loadCamera(VMA(1));
683
684 case CG_STARTCAMERA:
685 startCamera(args[1]);
686 return 0;
687
688 case CG_GETCAMERAINFO:
689 return getCameraInfo(args[1], VMA(2), VMA(3));
690 */
691 case CG_GET_ENTITY_TOKEN:
692 return re.GetEntityToken( VMA(1), args[2] );
693 case CG_R_INPVS:
694 return re.inPVS( VMA(1), VMA(2) );
695
696 default:
697 assert(0);
698 Com_Error( ERR_DROP, "Bad cgame system trap: %ld", (long int) args[0] );
699 }
700 return 0;
701 }
702
703
704 /*
705 ====================
706 CL_InitCGame
707
708 Should only be called by CL_StartHunkUsers
709 ====================
710 */
711 void CL_InitCGame( void ) {
712 const char *info;
713 const char *mapname;
714 int t1, t2;
715 vmInterpret_t interpret;
716
717 t1 = Sys_Milliseconds();
718
719 // put away the console
720 Con_Close();
721
722 // find the current mapname
723 info = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SERVERINFO ];
724 mapname = Info_ValueForKey( info, "mapname" );
725 Com_sprintf( cl.mapname, sizeof( cl.mapname ), "maps/%s.bsp", mapname );
726
727 // load the dll or bytecode
728 interpret = Cvar_VariableValue("vm_cgame");
729 if(cl_connectedToPureServer)
730 {
731 // if sv_pure is set we only allow qvms to be loaded
732 if(interpret != VMI_COMPILED && interpret != VMI_BYTECODE)
733 interpret = VMI_COMPILED;
734 }
735
736 cgvm = VM_Create( "cgame", CL_CgameSystemCalls, interpret );
737 if ( !cgvm ) {
738 Com_Error( ERR_DROP, "VM_Create on cgame failed" );
739 }
740 clc.state = CA_LOADING;
741
742 // init for this gamestate
743 // use the lastExecutedServerCommand instead of the serverCommandSequence
744 // otherwise server commands sent just before a gamestate are dropped
745 VM_Call( cgvm, CG_INIT, clc.serverMessageSequence, clc.lastExecutedServerCommand, clc.clientNum );
746
747 // reset any CVAR_CHEAT cvars registered by cgame
748 if ( !clc.demoplaying && !cl_connectedToCheatServer )
749 Cvar_SetCheatState();
750
751 // we will send a usercmd this frame, which
752 // will cause the server to send us the first snapshot
753 clc.state = CA_PRIMED;
754
755 t2 = Sys_Milliseconds();
756
757 Com_Printf( "CL_InitCGame: %5.2f seconds\n", (t2-t1)/1000.0 );
758
759 // have the renderer touch all its images, so they are present
760 // on the card even if the driver does deferred loading
761 re.EndRegistration();
762
763 // make sure everything is paged in
764 if (!Sys_LowPhysicalMemory()) {
765 Com_TouchMemory();
766 }
767
768 // clear anything that got printed
769 Con_ClearNotify ();
770 }
771
772
773 /*
774 ====================
775 CL_GameCommand
776
777 See if the current console command is claimed by the cgame
778 ====================
779 */
780 qboolean CL_GameCommand( void ) {
781 if ( !cgvm ) {
782 return qfalse;
783 }
784
785 return VM_Call( cgvm, CG_CONSOLE_COMMAND );
786 }
787
788
789
790 /*
791 =====================
792 CL_CGameRendering
793 =====================
794 */
795 void CL_CGameRendering( stereoFrame_t stereo ) {
796 VM_Call( cgvm, CG_DRAW_ACTIVE_FRAME, cl.serverTime, stereo, clc.demoplaying );
797 VM_Debug( 0 );
798 }
799
800
801 /*
802 =================
803 CL_AdjustTimeDelta
804
805 Adjust the clients view of server time.
806
807 We attempt to have cl.serverTime exactly equal the server's view
808 of time plus the timeNudge, but with variable latencies over
809 the internet it will often need to drift a bit to match conditions.
810
811 Our ideal time would be to have the adjusted time approach, but not pass,
812 the very latest snapshot.
813
814 Adjustments are only made when a new snapshot arrives with a rational
815 latency, which keeps the adjustment process framerate independent and
816 prevents massive overadjustment during times of significant packet loss
817 or bursted delayed packets.
818 =================
819 */
820
821 #define RESET_TIME 500
822
823 void CL_AdjustTimeDelta( void ) {
824 int newDelta;
825 int deltaDelta;
826
827 cl.newSnapshots = qfalse;
828
829 // the delta never drifts when replaying a demo
830 if ( clc.demoplaying ) {
831 return;
832 }
833
834 newDelta = cl.snap.serverTime - cls.realtime;
835 deltaDelta = abs( newDelta - cl.serverTimeDelta );
836
837 if ( deltaDelta > RESET_TIME ) {
838 cl.serverTimeDelta = newDelta;
839 cl.oldServerTime = cl.snap.serverTime; // FIXME: is this a problem for cgame?
840 cl.serverTime = cl.snap.serverTime;
841 if ( cl_showTimeDelta->integer ) {
842 Com_Printf( "<RESET> " );
843 }
844 } else if ( deltaDelta > 100 ) {
845 // fast adjust, cut the difference in half
846 if ( cl_showTimeDelta->integer ) {
847 Com_Printf( "<FAST> " );
848 }
849 cl.serverTimeDelta = ( cl.serverTimeDelta + newDelta ) >> 1;
850 } else {
851 // slow drift adjust, only move 1 or 2 msec
852
853 // if any of the frames between this and the previous snapshot
854 // had to be extrapolated, nudge our sense of time back a little
855 // the granularity of +1 / -2 is too high for timescale modified frametimes
856 if ( com_timescale->value == 0 || com_timescale->value == 1 ) {
857 if ( cl.extrapolatedSnapshot ) {
858 cl.extrapolatedSnapshot = qfalse;
859 cl.serverTimeDelta -= 2;
860 } else {
861 // otherwise, move our sense of time forward to minimize total latency
862 cl.serverTimeDelta++;
863 }
864 }
865 }
866
867 if ( cl_showTimeDelta->integer ) {
868 Com_Printf( "%i ", cl.serverTimeDelta );
869 }
870 }
871
872
873 /*
874 ==================
875 CL_FirstSnapshot
876 ==================
877 */
878 void CL_FirstSnapshot( void ) {
879 // ignore snapshots that don't have entities
880 if ( cl.snap.snapFlags & SNAPFLAG_NOT_ACTIVE ) {
881 return;
882 }
883 clc.state = CA_ACTIVE;
884
885 // set the timedelta so we are exactly on this first frame
886 cl.serverTimeDelta = cl.snap.serverTime - cls.realtime;
887 cl.oldServerTime = cl.snap.serverTime;
888
889 clc.timeDemoBaseTime = cl.snap.serverTime;
890
891 // if this is the first frame of active play,
892 // execute the contents of activeAction now
893 // this is to allow scripting a timedemo to start right
894 // after loading
895 if ( cl_activeAction->string[0] ) {
896 Cbuf_AddText( cl_activeAction->string );
897 Cvar_Set( "activeAction", "" );
898 }
899
900 #ifdef USE_MUMBLE
901 if ((cl_useMumble->integer) && !mumble_islinked()) {
902 int ret = mumble_link(CLIENT_WINDOW_TITLE);
903 Com_Printf("Mumble: Linking to Mumble application %s\n", ret==0?"ok":"failed");
904 }
905 #endif
906
907 #ifdef USE_VOIP
908 if (!clc.voipCodecInitialized) {
909 int i;
910 int error;
911
912 clc.opusEncoder = opus_encoder_create(48000, 1, OPUS_APPLICATION_VOIP, &error);
913
914 if ( error ) {
915 Com_DPrintf("VoIP: Error opus_encoder_create %d\n", error);
916 return;
917 }
918
919 for (i = 0; i < MAX_CLIENTS; i++) {
920 clc.opusDecoder[i] = opus_decoder_create(48000, 1, &error);
921 if ( error ) {
922 Com_DPrintf("VoIP: Error opus_decoder_create(%d) %d\n", i, error);
923 return;
924 }
925 clc.voipIgnore[i] = qfalse;
926 clc.voipGain[i] = 1.0f;
927 }
928 clc.voipCodecInitialized = qtrue;
929 clc.voipMuteAll = qfalse;
930 Cmd_AddCommand ("voip", CL_Voip_f);
931 Cvar_Set("cl_voipSendTarget", "spatial");
932 Com_Memset(clc.voipTargets, ~0, sizeof(clc.voipTargets));
933 }
934 #endif
935 }
936
937 /*
938 ==================
939 CL_SetCGameTime
940 ==================
941 */
942 void CL_SetCGameTime( void ) {
943 // getting a valid frame message ends the connection process
944 if ( clc.state != CA_ACTIVE ) {
945 if ( clc.state != CA_PRIMED ) {
946 return;
947 }
948 if ( clc.demoplaying ) {
949 // we shouldn't get the first snapshot on the same frame
950 // as the gamestate, because it causes a bad time skip
951 if ( !clc.firstDemoFrameSkipped ) {
952 clc.firstDemoFrameSkipped = qtrue;
953 return;
954 }
955 CL_ReadDemoMessage();
956 }
957 if ( cl.newSnapshots ) {
958 cl.newSnapshots = qfalse;
959 CL_FirstSnapshot();
960 }
961 if ( clc.state != CA_ACTIVE ) {
962 return;
963 }
964 }
965
966 // if we have gotten to this point, cl.snap is guaranteed to be valid
967 if ( !cl.snap.valid ) {
968 Com_Error( ERR_DROP, "CL_SetCGameTime: !cl.snap.valid" );
969 }
970
971 // allow pause in single player
972 if ( sv_paused->integer && CL_CheckPaused() && com_sv_running->integer ) {
973 // paused
974 return;
975 }
976
977 if ( cl.snap.serverTime < cl.oldFrameServerTime ) {
978 Com_Error( ERR_DROP, "cl.snap.serverTime < cl.oldFrameServerTime" );
979 }
980 cl.oldFrameServerTime = cl.snap.serverTime;
981
982
983 // get our current view of time
984
985 if ( clc.demoplaying && cl_freezeDemo->integer ) {
986 // cl_freezeDemo is used to lock a demo in place for single frame advances
987
988 } else {
989 // cl_timeNudge is a user adjustable cvar that allows more
990 // or less latency to be added in the interest of better
991 // smoothness or better responsiveness.
992 int tn;
993
994 tn = cl_timeNudge->integer;
995 if (tn<-30) {
996 tn = -30;
997 } else if (tn>30) {
998 tn = 30;
999 }
1000
1001 cl.serverTime = cls.realtime + cl.serverTimeDelta - tn;
1002
1003 // guarantee that time will never flow backwards, even if
1004 // serverTimeDelta made an adjustment or cl_timeNudge was changed
1005 if ( cl.serverTime < cl.oldServerTime ) {
1006 cl.serverTime = cl.oldServerTime;
1007 }
1008 cl.oldServerTime = cl.serverTime;
1009
1010 // note if we are almost past the latest frame (without timeNudge),
1011 // so we will try and adjust back a bit when the next snapshot arrives
1012 if ( cls.realtime + cl.serverTimeDelta >= cl.snap.serverTime - 5 ) {
1013 cl.extrapolatedSnapshot = qtrue;
1014 }
1015 }
1016
1017 // if we have gotten new snapshots, drift serverTimeDelta
1018 // don't do this every frame, or a period of packet loss would
1019 // make a huge adjustment
1020 if ( cl.newSnapshots ) {
1021 CL_AdjustTimeDelta();
1022 }
1023
1024 if ( !clc.demoplaying ) {
1025 return;
1026 }
1027
1028 // if we are playing a demo back, we can just keep reading
1029 // messages from the demo file until the cgame definitely
1030 // has valid snapshots to interpolate between
1031
1032 // a timedemo will always use a deterministic set of time samples
1033 // no matter what speed machine it is run on,
1034 // while a normal demo may have different time samples
1035 // each time it is played back
1036 if ( cl_timedemo->integer ) {
1037 int now = Sys_Milliseconds( );
1038 int frameDuration;
1039
1040 if (!clc.timeDemoStart) {
1041 clc.timeDemoStart = clc.timeDemoLastFrame = now;
1042 clc.timeDemoMinDuration = INT_MAX;
1043 clc.timeDemoMaxDuration = 0;
1044 }
1045
1046 frameDuration = now - clc.timeDemoLastFrame;
1047 clc.timeDemoLastFrame = now;
1048
1049 // Ignore the first measurement as it'll always be 0
1050 if( clc.timeDemoFrames > 0 )
1051 {
1052 if( frameDuration > clc.timeDemoMaxDuration )
1053 clc.timeDemoMaxDuration = frameDuration;
1054
1055 if( frameDuration < clc.timeDemoMinDuration )
1056 clc.timeDemoMinDuration = frameDuration;
1057
1058 // 255 ms = about 4fps
1059 if( frameDuration > UCHAR_MAX )
1060 frameDuration = UCHAR_MAX;
1061
1062 clc.timeDemoDurations[ ( clc.timeDemoFrames - 1 ) %
1063 MAX_TIMEDEMO_DURATIONS ] = frameDuration;
1064 }
1065
1066 clc.timeDemoFrames++;
1067 cl.serverTime = clc.timeDemoBaseTime + clc.timeDemoFrames * 50;
1068 }
1069
1070 while ( cl.serverTime >= cl.snap.serverTime ) {
1071 // feed another messag, which should change
1072 // the contents of cl.snap
1073 CL_ReadDemoMessage();
1074 if ( clc.state != CA_ACTIVE ) {
1075 return; // end of demo
1076 }
1077 }
1078
1079 }
1080
1081
1082