-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathcl_cgame.cpp
More file actions
1687 lines (1404 loc) · 45.1 KB
/
cl_cgame.cpp
File metadata and controls
1687 lines (1404 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
// cl_cgame.c -- client system interaction with client game
#include "client.h"
#include "cg_msgdef.h"
#include "key_identification.h"
#if defined(USE_MUMBLE)
#include "mumblelink/libmumblelink.h"
#endif
#include "qcommon/crypto.h"
#include "qcommon/sys.h"
#include "framework/CommonVMServices.h"
#include "framework/CommandSystem.h"
#include "framework/CvarSystem.h"
#include "framework/Network.h"
// Suppress warnings for unused [this] lambda captures.
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-lambda-capture"
#endif
/**
* Independently of the gamelogic, we can assume the game to have "teams" with an id,
* as long as we don't assume any semantics on that
* we can assume however that "0" is some form of "neutral" or "non" team,
* most likely a non-playing client that e.g. observes the game or hasn't joined yet.
* even in a deathmatch or singleplayer game, joining would start with team 1, even though there might not be another one
* this allows several client logic (like team specific binds or configurations) to work no matter how the team is called or what its attributes are
*/
static Cvar::Cvar<int> p_team("p_team", "team number of your team", Cvar::ROM, 0);
/*
====================
CL_GetUserCmd
====================
*/
bool CL_GetUserCmd( int cmdNumber, usercmd_t *ucmd )
{
// cmds[cmdNumber] is the last properly generated command
// can't return anything that we haven't created yet
if ( cmdNumber > cl.cmdNumber )
{
Sys::Drop( "CL_GetUserCmd: %i >= %i", cmdNumber, cl.cmdNumber );
}
// the usercmd has been overwritten in the wrapping
// buffer because it is too far out of date
if ( cmdNumber <= cl.cmdNumber - CMD_BACKUP )
{
return false;
}
*ucmd = cl.cmds[ cmdNumber & CMD_MASK ];
return true;
}
int CL_GetCurrentCmdNumber()
{
return cl.cmdNumber;
}
/*
=====================
CL_ConfigstringModified
=====================
*/
void CL_ConfigstringModified( Cmd::Args& csCmd )
{
if (csCmd.Argc() < 3) {
Sys::Drop( "CL_ConfigstringModified: wrong command received" );
}
int index = atoi( csCmd.Argv(1).c_str() );
if ( index < 0 || index >= MAX_CONFIGSTRINGS )
{
Sys::Drop( "CL_ConfigstringModified: bad index %i", index );
}
if ( cl.gameState[index] == csCmd.Argv(2) )
{
return;
}
cl.gameState[index] = csCmd.Argv(2);
if ( index == CS_SYSTEMINFO )
{
// parse serverId and other cvars
CL_SystemInfoChanged();
}
}
/*
===================
CL_HandleServerCommand
CL_GetServerCommand
===================
*/
bool CL_HandleServerCommand(Str::StringRef text, std::string& newText) {
static char bigConfigString[ BIG_INFO_STRING ];
Cmd::Args args(text);
if (args.Argc() == 0) {
return false;
}
auto cmd = args.Argv(0);
int argc = args.Argc();
if (cmd == "disconnect") {
// NERVE - SMF - allow server to indicate why they were disconnected
if (argc >= 2) {
Sys::Drop("^3Server disconnected:\n^7%s", args.Argv(1).c_str());
} else {
Sys::Drop("^3Server disconnected:\n^7(reason unknown)");
}
}
// bcs0 to bcs2 are used by the server to send info strings that are bigger than the size of a packet.
// See also SV_UpdateConfigStrings
// bcs0 starts a new big config string
// bcs1 continues it
// bcs2 finishes it and feeds it back as a new command sent by the server (bcs0 makes it a cs command)
if (cmd == "bcs0") {
if (argc >= 3) {
Com_sprintf(bigConfigString, BIG_INFO_STRING, "cs %s %s", args.Argv(1).c_str(), args.EscapedArgs(2).c_str());
}
return false;
}
if (cmd == "bcs1") {
if (argc >= 3) {
const char* s = Cmd_QuoteString( args[2].c_str() );
if (strlen(bigConfigString) + strlen(s) >= BIG_INFO_STRING) {
Sys::Drop("bcs exceeded BIG_INFO_STRING");
}
Q_strcat(bigConfigString, sizeof(bigConfigString), s);
}
return false;
}
if (cmd == "bcs2") {
if (argc >= 3) {
const char* s = Cmd_QuoteString( args[2].c_str() );
if (strlen(bigConfigString) + strlen(s) + 1 >= BIG_INFO_STRING) {
Sys::Drop("bcs exceeded BIG_INFO_STRING");
}
Q_strcat(bigConfigString, sizeof(bigConfigString), s);
Q_strcat(bigConfigString, sizeof(bigConfigString), "\"");
newText = bigConfigString;
return CL_HandleServerCommand(bigConfigString, newText);
}
return false;
}
if (cmd == "cs") {
CL_ConfigstringModified(args);
return true;
}
if (cmd == "map_restart") {
// clear outgoing commands before passing
// the restart to the cgame
memset(cl.cmds, 0, sizeof(cl.cmds));
return true;
}
if (cmd == "popup") {
// direct server to client popup request, bypassing cgame
if (cls.state == connstate_t::CA_ACTIVE && !clc.demoplaying && argc >=1) {
// TODO: Pass to the cgame
}
return false;
}
if (cmd == "pubkey_decrypt") {
char buffer[ MAX_STRING_CHARS ] = "pubkey_identify ";
NettleLength msg_len = MAX_STRING_CHARS - 16;
mpz_t message;
if (argc == 1) {
Log::Notice("^3Server sent a pubkey_decrypt command, but sent nothing to decrypt!");
return false;
}
mpz_init_set_str(message, args.Argv(1).c_str(), 16);
if (rsa_decrypt(&private_key, &msg_len, (unsigned char *) buffer + 16, message)) {
nettle_mpz_set_str_256_u(message, msg_len, (unsigned char *) buffer + 16);
mpz_get_str(buffer + 16, 16, message);
CL_AddReliableCommand(buffer);
}
mpz_clear(message);
return false;
}
return true;
}
// Get the server commands, does client-specific handling
// that may block the propagation of a command to cgame.
// If the propagation is not blocked then it puts the command
// in commands.
void CL_FillServerCommands(std::vector<std::string>& commands, int start, int end)
{
// if we have irretrievably lost a reliable command, drop the connection
if ( start <= clc.serverCommandSequence - MAX_RELIABLE_COMMANDS )
{
// when a demo record was started after the client got a whole bunch of
// reliable commands then the client never got those first reliable commands
if ( clc.demoplaying )
{
return;
}
Sys::Drop( "CL_FillServerCommand: a reliable command was cycled out" );
}
if ( end > clc.serverCommandSequence )
{
Sys::Drop( "CL_FillServerCommand: requested command not received" );
}
for (int i = start; i < end; i++) {
const char* s = clc.serverCommands[i].c_str();
std::string cmdText = s;
if (CL_HandleServerCommand(s, cmdText)) {
commands.push_back(std::move(cmdText));
}
}
}
/*
====================
CL_GetSnapshot
====================
*/
bool CL_GetSnapshot( int snapshotNumber, ipcSnapshot_t *snapshot )
{
clSnapshot_t *clSnap;
if ( snapshotNumber > cl.snap.messageNum )
{
Sys::Drop( "CL_GetSnapshot: snapshotNumber > cl.snapshot.messageNum" );
}
// if the frame has fallen out of the circular buffer, we can't return it
if ( cl.snap.messageNum - snapshotNumber >= PACKET_BACKUP )
{
return false;
}
// if the frame is not valid, we can't return it
clSnap = &cl.snapshots[ snapshotNumber & PACKET_MASK ];
if ( !clSnap->valid )
{
return false;
}
// write the snapshot
snapshot->b.snapFlags = clSnap->snapFlags;
snapshot->b.ping = clSnap->ping;
snapshot->b.serverTime = clSnap->serverTime;
memcpy( snapshot->b.areamask, clSnap->areamask, sizeof( snapshot->b.areamask ) );
snapshot->ps = clSnap->ps;
snapshot->b.entities = clSnap->entities;
CL_FillServerCommands(snapshot->b.serverCommands, clc.lastExecutedServerCommand, clSnap->serverCommandNum);
clc.lastExecutedServerCommand = clSnap->serverCommandNum;
return true;
}
/*
====================
CL_ShutdownCGame
====================
*/
void CL_ShutdownCGame()
{
cls.cgameStarted = false;
if ( !cgvm.IsActive() )
{
return;
}
cgvm.CGameShutdown();
}
/*
* ====================
* LAN_ResetPings
* ====================
*/
static void LAN_ResetPings( int source )
{
int count, i;
serverInfo_t *servers = nullptr;
count = 0;
switch ( source )
{
case AS_LOCAL:
servers = &cls.localServers[ 0 ];
count = MAX_OTHER_SERVERS;
break;
case AS_GLOBAL:
servers = &cls.globalServers[ 0 ];
count = MAX_GLOBAL_SERVERS;
break;
}
if ( servers )
{
for ( i = 0; i < count; i++ )
{
servers[ i ].pingStatus = pingStatus_t::WAITING;
servers[ i ].pingAttempts = 0;
servers[ i ].ping = -1;
}
}
}
/*
* ====================
* LAN_GetServerCount
* ====================
*/
static int LAN_GetServerCount( int source )
{
switch ( source )
{
case AS_LOCAL:
return cls.numlocalservers;
case AS_GLOBAL:
return cls.numglobalservers;
}
return 0;
}
/*
* ====================
* LAN_GetServerInfo
* ====================
*/
static void LAN_GetServerInfo( int source, int n, trustedServerInfo_t &trustedInfo, std::string &info )
{
serverInfo_t *server = nullptr;
switch ( source )
{
case AS_LOCAL:
if ( n >= 0 && n < MAX_OTHER_SERVERS )
{
server = &cls.localServers[ n ];
}
break;
case AS_GLOBAL:
if ( n >= 0 && n < MAX_GLOBAL_SERVERS )
{
server = &cls.globalServers[ n ];
}
break;
}
if ( server )
{
trustedInfo.responseProto = server->responseProto;
Q_strncpyz( trustedInfo.addr, Net::AddressToString( server->adr, true ).c_str(), sizeof( trustedInfo.addr ) );
Q_strncpyz( trustedInfo.featuredLabel, server->label, sizeof( trustedInfo.featuredLabel ) );
info = server->infoString;
}
else
{
trustedInfo = {};
info.clear();
}
}
/*
* ====================
* LAN_GetServerPing
* ====================
*/
static int LAN_GetServerPing( int source, int n )
{
serverInfo_t *server = nullptr;
switch ( source )
{
case AS_LOCAL:
if ( n >= 0 && n < MAX_OTHER_SERVERS )
{
server = &cls.localServers[ n ];
}
break;
case AS_GLOBAL:
if ( n >= 0 && n < MAX_GLOBAL_SERVERS )
{
server = &cls.globalServers[ n ];
}
break;
}
if ( server )
{
return server->ping;
}
return -1;
}
/*
* ====================
* LAN_MarkServerVisible
* ====================
*/
static void LAN_MarkServerVisible( int source, int n, bool visible )
{
if ( n == -1 )
{
int count = MAX_OTHER_SERVERS;
serverInfo_t *server = nullptr;
switch ( source )
{
case AS_LOCAL:
server = &cls.localServers[ 0 ];
break;
case AS_GLOBAL:
server = &cls.globalServers[ 0 ];
count = MAX_GLOBAL_SERVERS;
break;
}
if ( server )
{
for ( n = 0; n < count; n++ )
{
server[ n ].visible = visible;
}
}
}
else
{
switch ( source )
{
case AS_LOCAL:
if ( n >= 0 && n < MAX_OTHER_SERVERS )
{
cls.localServers[ n ].visible = visible;
}
break;
case AS_GLOBAL:
if ( n >= 0 && n < MAX_GLOBAL_SERVERS )
{
cls.globalServers[ n ].visible = visible;
}
break;
}
}
}
/*
* =======================
* LAN_ServerIsVisible
* =======================
*/
static int LAN_ServerIsVisible( int source, int n )
{
switch ( source )
{
case AS_LOCAL:
if ( n >= 0 && n < MAX_OTHER_SERVERS )
{
return cls.localServers[ n ].visible;
}
break;
case AS_GLOBAL:
if ( n >= 0 && n < MAX_GLOBAL_SERVERS )
{
return cls.globalServers[ n ].visible;
}
break;
}
return false;
}
/*
* ====================
* Key_GetCatcher
* ====================
*/
int Key_GetCatcher()
{
return cls.keyCatchers;
}
/*
* ====================
* Key_SetCatcher
* ====================
*/
void Key_SetCatcher( int catcher )
{
// NERVE - SMF - console overrides everything
if ( cls.keyCatchers & KEYCATCH_CONSOLE )
{
cls.keyCatchers = catcher | KEYCATCH_CONSOLE;
}
else
{
cls.keyCatchers = catcher;
}
}
/*
====================
CL_InitCGame
Should only by called by CL_StartHunkUsers
====================
*/
void CL_InitCGame()
{
const char *info;
const char *mapname;
int t1, t2;
t1 = Sys::Milliseconds();
// put away the console
Con_Close();
// find the current mapname
info = cl.gameState[ CS_SERVERINFO ].c_str();
mapname = Info_ValueForKey( info, "mapname" );
Com_sprintf( cl.mapname, sizeof( cl.mapname ), "maps/%s.bsp", mapname );
cls.state = connstate_t::CA_LOADING;
// init for this gamestate
cgvm.CGameInit(clc.serverMessageSequence, clc.clientNum);
// we will send a usercmd this frame, which
// will cause the server to send us the first snapshot
cls.state = connstate_t::CA_PRIMED;
t2 = Sys::Milliseconds();
Log::Debug( "CL_InitCGame: %5.2fs", ( t2 - t1 ) / 1000.0 );
// have the renderer touch all its images, so they are present
// on the card even if the driver does deferred loading
re.EndRegistration();
// Cause any input while loading to be dropped and forget what's pressed
IN_DropInputsForFrame();
CL_ClearKeys();
Key_ClearStates();
}
/*
=====================
CL_CGameRendering
=====================
*/
void CL_CGameRendering()
{
cgvm.CGameDrawActiveFrame(cl.serverTime, clc.demoplaying);
}
/*
=================
CL_AdjustTimeDelta
Adjust the clients view of server time.
We attempt to have cl.serverTime exactly equal the server's view
of time plus the timeNudge, but with variable latencies over
the Internet, it will often need to drift a bit to match conditions.
Our ideal time would be to have the adjusted time approach, but not pass,
the very latest snapshot.
Adjustments are only made when a new snapshot arrives with a rational
latency, which keeps the adjustment process framerate independent and
prevents massive overadjustment during times of significant packet loss
or bursted delayed packets.
=================
*/
static const int RESET_TIME = 500;
void CL_AdjustTimeDelta()
{
// int resetTime;
int newDelta;
int deltaDelta;
cl.newSnapshots = false;
// the delta never drifts when replaying a demo
if ( clc.demoplaying )
{
return;
}
// if the current time is WAY off, just correct to the current value
/*
if(com_sv_running.Get())
{
resetTime = 100;
}
else
{
resetTime = RESET_TIME;
}
*/
newDelta = cl.snap.serverTime - cls.realtime;
deltaDelta = abs( newDelta - cl.serverTimeDelta );
if ( deltaDelta > RESET_TIME )
{
cl.serverTimeDelta = newDelta;
cl.oldServerTime = cl.snap.serverTime; // FIXME: is this a problem for cgame?
cl.serverTime = cl.snap.serverTime;
if ( cl_showTimeDelta->integer )
{
Log::Notice( "<RESET> " );
}
}
else if ( deltaDelta > 100 )
{
// fast adjust, cut the difference in half
if ( cl_showTimeDelta->integer )
{
Log::Notice( "<FAST> " );
}
cl.serverTimeDelta = ( cl.serverTimeDelta + newDelta ) >> 1;
}
else
{
// slow drift adjust, only move 1 or 2 msec
// if any of the frames between this and the previous snapshot
// had to be extrapolated, nudge our sense of time back a little
// the granularity of +1 / -2 is too high for timescale modified frametimes
if ( com_timescale->value == 0 || com_timescale->value == 1 )
{
if ( cl.extrapolatedSnapshot )
{
cl.extrapolatedSnapshot = false;
cl.serverTimeDelta -= 2;
}
else
{
// otherwise, move our sense of time forward to minimize total latency
cl.serverTimeDelta++;
}
}
}
if ( cl_showTimeDelta->integer )
{
Log::Notice("%i ", cl.serverTimeDelta );
}
}
/*
==================
CL_FirstSnapshot
==================
*/
void CL_FirstSnapshot()
{
// ignore snapshots that don't have entities
if ( cl.snap.snapFlags & SNAPFLAG_NOT_ACTIVE )
{
return;
}
cls.state = connstate_t::CA_ACTIVE;
// set the timedelta so we are exactly on this first frame
cl.serverTimeDelta = cl.snap.serverTime - cls.realtime;
cl.oldServerTime = cl.snap.serverTime;
clc.timeDemoBaseTime = cl.snap.serverTime;
// if this is the first frame of active play,
// execute the contents of activeAction now
// this is to allow scripting a timedemo to start right
// after loading
if ( cl_activeAction->string[ 0 ] )
{
Cmd::BufferCommandText(cl_activeAction->string);
Cvar_Set( "activeAction", "" );
}
#if defined(USE_MUMBLE)
if ( ( cl_useMumble->integer ) && !mumble_islinked() )
{
int ret = mumble_link( CLIENT_WINDOW_TITLE );
Log::Notice(ret == 0 ? "Mumble: Linking to Mumble application okay" : "Mumble: Linking to Mumble application failed" );
}
#endif
// resend userinfo upon entering the game, as some cvars may
// not have had the CVAR_USERINFO flag set until loading cgame
cvar_modifiedFlags |= CVAR_USERINFO;
}
/*
==================
CL_SetCGameTime
==================
*/
void CL_SetCGameTime()
{
// getting a valid frame message ends the connection process
if ( cls.state != connstate_t::CA_ACTIVE )
{
if ( cls.state != connstate_t::CA_PRIMED )
{
return;
}
if ( clc.demoplaying )
{
// we shouldn't get the first snapshot on the same frame
// as the gamestate, because it causes a bad time skip
if ( !clc.firstDemoFrameSkipped )
{
clc.firstDemoFrameSkipped = true;
return;
}
CL_ReadDemoMessage();
}
if ( cl.newSnapshots )
{
cl.newSnapshots = false;
CL_FirstSnapshot();
}
if ( cls.state != connstate_t::CA_ACTIVE )
{
return;
}
}
// if we have gotten to this point, cl.snap is guaranteed to be valid
if ( !cl.snap.valid )
{
Sys::Drop( "CL_SetCGameTime: !cl.snap.valid" );
}
if ( cl.snap.serverTime < cl.oldFrameServerTime )
{
// Ridah, if this is a localhost, then we are probably loading a savegame
if ( cls.servername == "loopback" )
{
// do nothing?
CL_FirstSnapshot();
}
else
{
Sys::Drop( "cl.snap.serverTime < cl.oldFrameServerTime" );
}
}
cl.oldFrameServerTime = cl.snap.serverTime;
// cl_timeNudge is a user adjustable cvar that allows more
// or less latency to be added in the interest of better
// smoothness or better responsiveness.
int tn = Math::Clamp( cl_timeNudge->integer, -30, 30 );
cl.serverTime = cls.realtime + cl.serverTimeDelta - tn;
// guarantee that time will never flow backwards, even if
// serverTimeDelta made an adjustment or cl_timeNudge was changed
if ( cl.serverTime < cl.oldServerTime )
{
cl.serverTime = cl.oldServerTime;
}
cl.oldServerTime = cl.serverTime;
// note if we are almost past the latest frame (without timeNudge),
// so we will try and adjust back a bit when the next snapshot arrives
if ( cls.realtime + cl.serverTimeDelta >= cl.snap.serverTime - 5 )
{
cl.extrapolatedSnapshot = true;
}
// if we have gotten new snapshots, drift serverTimeDelta
// don't do this every frame, or a period of packet loss would
// make a huge adjustment
if ( cl.newSnapshots )
{
CL_AdjustTimeDelta();
}
if ( !clc.demoplaying )
{
return;
}
// if we are playing a demo back, we can just keep reading
// messages from the demo file until the cgame definitely
// has valid snapshots to interpolate between
// a timedemo will always use a deterministic set of time samples
// no matter what speed machine it is run on
if ( cvar_demo_timedemo.Get() )
{
if ( !clc.timeDemoStart )
{
clc.timeDemoStart = Sys::Milliseconds();
}
clc.timeDemoFrames++;
cl.serverTime = clc.timeDemoBaseTime + clc.timeDemoFrames * 50;
}
while ( cl.serverTime >= cl.snap.serverTime )
{
// feed another message, which should change
// the contents of cl.snap
CL_ReadDemoMessage();
if ( cls.state != connstate_t::CA_ACTIVE )
{
Cvar_Set( "timescale", "1" );
return; // end of demo
}
}
}
/**
* is notified by teamchanges.
* while most notifications will come from the cgame, due to game semantics,
* other code may assume a change to a non-team "0", like e.g. /disconnect
*/
void CL_OnTeamChanged( int newTeam )
{
static bool first = true;
if ( p_team.Get() == newTeam && !first )
{
return;
}
first = false;
Cvar::SetValueForce( "p_team", std::to_string( newTeam ) );
/* set all team specific teambindings */
Keyboard::SetTeam( newTeam );
/*
* execute a possibly team aware config each time the team was changed.
* the user can use the cvars p_team or p_teamname (if the cgame sets it) within that config
* to e.g. execute team specific configs, like cg_<team>Config did previously, but with less dependency on the cgame
*/
Cmd::BufferCommandText( "exec -f " TEAMCONFIG_NAME );
}
CGameVM::CGameVM(): VM::VMBase("cgame", Cvar::CHEAT), services(nullptr), cmdBuffer("client")
{
}
void CGameVM::Start()
{
services = std::unique_ptr<VM::CommonVMServices>(new VM::CommonVMServices(*this, "CGame", FS::Owner::CGAME, Cmd::CGAME_VM));
this->Create();
this->CGameStaticInit();
}
void CGameVM::CGameStaticInit()
{
this->SendMsg<CGameStaticInitMsg>(Sys::Milliseconds());
}
void CGameVM::CGameInit(int serverMessageNum, int clientNum)
{
this->SendMsg<CGameInitMsg>(serverMessageNum, clientNum, cls.windowConfig, cl.gameState);
NetcodeTable psTable;
size_t psSize;
this->SendMsg<VM::GetNetcodeTablesMsg>(psTable, psSize);
MSG_InitNetcodeTables(std::move(psTable), psSize);
}
void CGameVM::CGameShutdown()
{
try {
this->SendMsg<CGameShutdownMsg>();
} catch (Sys::DropErr& err) {
Log::Notice("Error during cgame shutdown: %s", err.what());
}
this->Free();
services = nullptr;
}
void CGameVM::CGameDrawActiveFrame(int serverTime, bool demoPlayback)
{
this->SendMsg<CGameDrawActiveFrameMsg>(serverTime, demoPlayback);
}
bool CGameVM::CGameKeyDownEvent(Keyboard::Key key, bool repeat)
{
if (!key.IsValid())
return false;
bool consumed;
this->SendMsg<CGameKeyDownEventMsg>(key, repeat, consumed);
return consumed;
}
void CGameVM::CGameKeyUpEvent(Keyboard::Key key)
{
if (!key.IsValid())
return;
this->SendMsg<CGameKeyUpEventMsg>(key);
}
void CGameVM::CGameMouseEvent(int dx, int dy)