-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame_network.cpp
3978 lines (3418 loc) · 110 KB
/
Game_network.cpp
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
#include "../idlib/precompiled.h"
#pragma hdrstop
#include "Game_local.h"
// RAVEN BEGIN
// bdube: client entities
#include "client/ClientEffect.h"
// shouchard: ban list support
#define BANLIST_FILENAME "banlist.txt"
// RAVEN END
/*
===============================================================================
Client running game code:
- entity events don't work and should not be issued
- entities should never be spawned outside idGameLocal::ClientReadSnapshot
===============================================================================
*/
// adds tags to the network protocol to detect when things go bad ( internal consistency )
// NOTE: this changes the network protocol
#ifndef ASYNC_WRITE_TAGS
#define ASYNC_WRITE_TAGS 1
#endif
idCVar net_clientShowSnapshot( "net_clientShowSnapshot", "0", CVAR_GAME | CVAR_INTEGER, "", 0, 3, idCmdSystem::ArgCompletion_Integer<0,3> );
idCVar net_clientShowSnapshotRadius( "net_clientShowSnapshotRadius", "128", CVAR_GAME | CVAR_FLOAT, "" );
idCVar net_clientMaxPrediction( "net_clientMaxPrediction", "1000", CVAR_SYSTEM | CVAR_INTEGER | CVAR_NOCHEAT, "maximum number of milliseconds a client can predict ahead of server." );
idCVar net_clientLagOMeter( "net_clientLagOMeter", "0", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT | PC_CVAR_ARCHIVE, "draw prediction graph" );
idCVar net_clientLagOMeterResolution( "net_clientLagOMeterResolution", "16", CVAR_GAME | CVAR_INTEGER | CVAR_NOCHEAT | PC_CVAR_ARCHIVE, "resolution for predict ahead graph (upper part of lagometer)", 1, 100 );
// RAVEN BEGIN
// ddynerman: performance profiling
int net_entsInSnapshot;
int net_snapshotSize;
extern const int ASYNC_PLAYER_FRAG_BITS;
// RAVEN END
// message senders
idNullMessageSender nullSender;
idServerReliableMessageSender serverReliableSender;
idRepeaterReliableMessageSender repeaterReliableSender;
/*
================
idGameLocal::InitAsyncNetwork
================
*/
void idGameLocal::InitAsyncNetwork( void ) {
memset( clientEntityStates, 0, sizeof( clientEntityStates ) );
memset( clientPVS, 0, sizeof( clientPVS ) );
memset( clientSnapshots, 0, sizeof( clientSnapshots ) );
memset( viewerEntityStates, 0, sizeof( *viewerEntityStates ) * maxViewers );
memset( viewerPVS, 0, sizeof( *viewerPVS ) * maxViewers );
memset( viewerSnapshots, 0, sizeof( *viewerSnapshots ) * maxViewers );
memset( viewerUnreliableMessages, 0, sizeof (*viewerUnreliableMessages) * maxViewers );
eventQueue.Init();
// we used to have some special case -1 value, but we don't anymore so this is always >= 0 now
entityDefBits = idMath::BitsForInteger( declManager->GetNumDecls( DECL_ENTITYDEF ) ) + 1;
localClientNum = 0; // on a listen server SetLocalUser will set this right
realClientTime = 0;
isNewFrame = true;
nextLagoCheck = 0;
}
/*
================
idGameLocal::ShutdownAsyncNetwork
================
*/
void idGameLocal::ShutdownAsyncNetwork( void ) {
entityStateAllocator.Shutdown();
snapshotAllocator.Shutdown();
eventQueue.Shutdown();
memset( clientEntityStates, 0, sizeof( clientEntityStates ) );
memset( clientPVS, 0, sizeof( clientPVS ) );
memset( clientSnapshots, 0, sizeof( clientSnapshots ) );
memset( viewerEntityStates, 0, sizeof( *viewerEntityStates ) * maxViewers );
memset( viewerPVS, 0, sizeof( *viewerPVS ) * maxViewers );
memset( viewerSnapshots, 0, sizeof( *viewerSnapshots ) * maxViewers );
memset( viewerUnreliableMessages, 0, sizeof (*viewerUnreliableMessages) * maxViewers );
}
/*
================
idGameLocal::InitLocalClient
================
*/
void idGameLocal::InitLocalClient( int clientNum ) {
isServer = false;
isClient = true;
localClientNum = clientNum;
if ( clientNum == MAX_CLIENTS && !entities[ ENTITYNUM_NONE ] ) {
SpawnPlayer( ENTITYNUM_NONE );
idPlayer *player = gameLocal.GetLocalPlayer();
assert( player );
player->SpawnFromSpawnSpot();
}
}
/*
================
idGameLocal::ServerAllowClient
clientId is the ID of the connecting client - can later be mapped to a clientNum by calling networkSystem->ServerGetClientNum( clientId )
================
*/
allowReply_t idGameLocal::ServerAllowClient( int clientId, int numClients, const char *IP, const char *guid, const char *password, const char *privatePassword, char reason[ MAX_STRING_CHARS ] ) {
reason[0] = '\0';
// RAVEN BEGIN
// shouchard: ban support
if ( IsGuidBanned( guid ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107239" );
return ALLOW_NO;
}
// RAVEN END
if ( serverInfo.GetInt( "si_pure" ) && !mpGame.IsPureReady() ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107139" );
return ALLOW_NOTYET;
}
if ( !serverInfo.GetInt( "si_maxPlayers" ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107140" );
return ALLOW_NOTYET;
}
// completely full
if ( numClients >= serverInfo.GetInt( "si_maxPlayers" ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107141" );
return ALLOW_NOTYET;
}
// check private clients
if( serverInfo.GetInt( "si_privatePlayers" ) > 0 ) {
// just in case somehow we have a stale private clientId that matches a new client
mpGame.RemovePrivatePlayer( clientId );
const char *privatePass = cvarSystem->GetCVarString( "g_privatePassword" );
if( privatePass[ 0 ] == '\0' ) {
common->Warning( "idGameLocal::ServerAllowClient() - si_privatePlayers > 0 with no g_privatePassword" );
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "say si_privatePlayers is set but g_privatePassword is empty" );
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107142" );
return ALLOW_NOTYET;
}
int numPrivateClients = cvarSystem->GetCVarInteger( "si_numPrivatePlayers" );
// private clients that take up public slots are considered public clients
numPrivateClients = idMath::ClampInt( 0, serverInfo.GetInt( "si_privatePlayers" ), numPrivateClients );
if ( !idStr::Cmp( privatePass, privatePassword ) ) {
// once this client spawns in, they'll be marked private
mpGame.AddPrivatePlayer( clientId );
} else if( (numClients - numPrivateClients) >= (serverInfo.GetInt( "si_maxPlayers" ) - serverInfo.GetInt( "si_privatePlayers" )) ) {
// if the number of public clients is greater than or equal to the number of public slots, require a private slot
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107141" );
return ALLOW_NOTYET;
}
}
if ( !cvarSystem->GetCVarBool( "si_usePass" ) ) {
return ALLOW_YES;
}
const char *pass = cvarSystem->GetCVarString( "g_password" );
if ( pass[ 0 ] == '\0' ) {
common->Warning( "si_usePass is set but g_password is empty" );
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "say si_usePass is set but g_password is empty" );
// avoids silent misconfigured state
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107142" );
return ALLOW_NOTYET;
}
if ( !idStr::Cmp( pass, password ) ) {
return ALLOW_YES;
}
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107143" );
Printf( "Rejecting client %s from IP %s: invalid password\n", guid, IP );
return ALLOW_BADPASS;
}
/*
================
idGameLocal::ReallocViewers
Allocate/Reallocate space for viewers
================
*/
template<typename T> static ID_INLINE void ReallocateZero( T *&var, int oldSize, int newSize ) {
T *new_var = newSize ? new T[ newSize ] : NULL;
SIMDProcessor->Memcpy( new_var, var, sizeof(*new_var) * Min( newSize, oldSize ) );
delete[] var;
var = new_var;
if ( newSize > oldSize ) {
SIMDProcessor->Memset( var + oldSize, 0, sizeof(*var) * (newSize - oldSize) );
}
}
static ID_INLINE void ReallocateZeroClearInfo( viewer_t *&var, int oldSize, int newSize ) {
int minBound = Min( newSize, oldSize ), i;
viewer_t *new_var = newSize ? new viewer_t[ newSize ] : NULL;
for (i = 0; i < minBound; i++ ) {
new_var[ i ] = var[ i ];
}
for (i = 0; i < oldSize; i++ ) {
var[ i ].info.Clear();
}
delete[] var;
var = new_var;
for (i = oldSize; i < newSize; i++) {
var[i].connected = var[i].active = var[i].priv = var[i].nopvs = false;
var[i].pvsArea = -1;
}
}
void idGameLocal::ReallocViewers( int newMaxViewers ) {
int i;
if ( newMaxViewers == maxViewers ) {
return;
}
if ( newMaxViewers > 0 ) { // zinx: during shutdown we clear everything, but there are still connected viewers.
for ( i = newMaxViewers; i < maxViewers; i++ ) {
if ( viewers[ i ].connected ) {
// this should never happen
Error( "Too many active viewers for ri_maxViewers change" );
}
}
assert( maxViewer <= newMaxViewers );
} else {
maxViewer = 0;
}
ReallocateZeroClearInfo( viewers, maxViewers, newMaxViewers );
ReallocateZero( viewerEntityStates, maxViewers, newMaxViewers );
ReallocateZero( viewerPVS, maxViewers, newMaxViewers );
ReallocateZero( viewerSnapshots, maxViewers, newMaxViewers );
ReallocateZero( viewerUnreliableMessages, maxViewers, newMaxViewers );
maxViewers = newMaxViewers;
UpdateRepeaterInfo();
}
/*
================
idGameLocal::RepeaterAllowClient
clientId is the ID of the connecting client - can later be mapped to a clientNum by calling networkSystem->ServerGetClientNum( clientId )
================
*/
allowReply_t idGameLocal::RepeaterAllowClient( int clientId, int numClients, const char *IP, const char *guid, bool repeater, const char *password, const char *privatePassword, char reason[ MAX_STRING_CHARS ] ) {
reason[0] = '\0';
if ( IsGuidBanned( guid ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107239" );
return ALLOW_NO;
}
if ( serverInfo.GetInt( "si_pure" ) != 0 && !mpGame.IsPureReady() ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107139" );
return ALLOW_NOTYET;
}
if ( !cvarSystem->GetCVarInteger( "ri_maxViewers" ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_123000" );
return ALLOW_NOTYET;
}
// completely full
if ( numClients >= cvarSystem->GetCVarInteger( "ri_maxViewers" ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_123000" );
return ALLOW_NOTYET;
}
// check private clients
// just in case somehow we have a stale private clientId that matches a new client
privateViewerIds.Remove( clientId );
nopvsViewerIds.Remove( clientId );
const char *privatePass = cvarSystem->GetCVarString( "g_privateViewerPassword" );
if ( privatePass[ 0 ] == '\0' && ri_privateViewers.GetInteger() > 0 ) {
common->Warning( "idGameLocal::RepeaterAllowClient() - ri_privateViewers > 0 with no g_privateViewerPassword" );
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "say ri_privateViewers is set but g_privateViewerPassword is empty" );
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107142" );
return ALLOW_NOTYET;
}
int numPrivateClients = privateViewerIds.Num();
// private clients that take up public slots are considered public clients
numPrivateClients = idMath::ClampInt( 0, ri_privateViewers.GetInteger(), numPrivateClients );
if ( repeater ) {
const char *nopvsPass = cvarSystem->GetCVarString( "g_repeaterPassword" );
if ( nopvsPass[ 0 ] != '\0' ) {
if ( idStr::Cmp( nopvsPass, privatePassword ) ) {
// password is set, and they don't match.
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107143" );
Printf( "Rejecting viewer %s from IP %s: invalid password for repeater\n", guid, IP );
return ALLOW_BADPASS;
}
// once this client spawns in, they'll be marked private
privateViewerIds.Append( clientId );
} else {
if ( privatePass[ 0 ] != '\0' && !idStr::Cmp( privatePass, privatePassword ) ) {
// once this client spawns in, they'll be marked private
privateViewerIds.Append( clientId );
}
}
// once this client spawns in, they'll be marked as a broadcaster
nopvsViewerIds.Append( clientId );
} else if ( privatePass[ 0 ] != '\0' && !idStr::Cmp( privatePass, privatePassword ) ) {
// once this client spawns in, they'll be marked private
privateViewerIds.Append( clientId );
} else if( (numClients - numPrivateClients) >= ( cvarSystem->GetCVarInteger( "ri_maxViewers" ) - ri_privateViewers.GetInteger() ) ) {
// if the number of public clients is greater than or equal to the number of public slots, require a private slot
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107141" );
return ALLOW_NOTYET;
}
if ( !ri_useViewerPass.GetBool() ) {
return ALLOW_YES;
}
const char *pass = cvarSystem->GetCVarString( "g_viewerPassword" );
if ( pass[ 0 ] == '\0' ) {
common->Warning( "ri_useViewerPass is set but g_viewerPassword is empty" );
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "say ri_useViewerPass is set but g_viewerPassword is empty" );
// avoids silent misconfigured state
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107142" );
return ALLOW_NOTYET;
}
if ( !idStr::Cmp( pass, password ) ) {
return ALLOW_YES;
}
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107143" );
Printf( "Rejecting viewer %s from IP %s: invalid password\n", guid, IP );
return ALLOW_BADPASS;
}
/*
================
idGameLocal::ServerClientConnect
================
*/
void idGameLocal::ServerClientConnect( int clientNum, const char *guid ) {
// make sure no parasite entity is left
if ( entities[ clientNum ] ) {
common->DPrintf( "ServerClientConnect: remove old player entity\n" );
delete entities[ clientNum ];
}
unreliableMessages[ clientNum ].Init( 0 );
userInfo[ clientNum ].Clear();
mpGame.ServerClientConnect( clientNum );
Printf( "client %d connected.\n", clientNum );
}
/*
================
idGameLocal::RepeaterClientConnect
================
*/
void idGameLocal::RepeaterClientConnect( int clientNum ) {
// ensure that we have enough slots for this client
assert( cvarSystem->GetCVarInteger( "ri_maxViewers" ) > clientNum );
ReallocViewers( cvarSystem->GetCVarInteger( "ri_maxViewers" ) );
viewers[ clientNum ].connected = true;
viewers[ clientNum ].active = false;
if ( maxViewer <= clientNum ) {
maxViewer = clientNum + 1;
}
// mark them as private/nopvs
for ( int i = 0; i < privateViewerIds.Num(); i++ ) {
int num = networkSystem->RepeaterGetClientNum( privateViewerIds[ i ] );
// check for timed out clientids
if ( num < 0 || (num == clientNum && viewers[ clientNum ].priv) ) {
privateViewerIds.RemoveIndex( i );
i--;
continue;
}
if ( num == clientNum ) {
viewers[ clientNum ].priv = true;
continue;
}
}
for ( int i = 0; i < nopvsViewerIds.Num(); i++ ) {
int num = networkSystem->RepeaterGetClientNum( nopvsViewerIds[ i ] );
// check for timed out clientids
if ( num < 0 || (num == clientNum && viewers[ clientNum ].nopvs) ) {
nopvsViewerIds.RemoveIndex( i );
i--;
continue;
}
if ( num == clientNum ) {
viewers[ clientNum ].nopvs = true;
continue;
}
}
Printf( "viewer %d connected%s.\n", clientNum, viewers[ clientNum ].nopvs ? " (repeater)" : "" );
// count up viewer slots so players know when servers are full
int numClients = 0;
for ( int i = 0; i < maxViewer; i++ ) {
if ( !viewers[ i ].connected ) {
continue;
}
++numClients;
}
int numPrivateClients = privateViewerIds.Num();
// private clients that take up public slots are considered public clients
numPrivateClients = idMath::ClampInt( 0, ri_privateViewers.GetInteger(), numPrivateClients );
ri_numViewers.SetInteger( numClients );
ri_numPrivateViewers.SetInteger( numPrivateClients );
UpdateRepeaterInfo();
}
/*
================
idGameLocal::ServerClientBegin
================
*/
void idGameLocal::ServerClientBegin( int clientNum ) {
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
// spawn the player
SpawnPlayer( clientNum );
if ( clientNum == localClientNum ) {
mpGame.EnterGame( clientNum );
}
// ddynerman: connect time
((idPlayer*)entities[ clientNum ])->SetConnectTime( time );
// send message to spawn the player at the clients
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_SPAWN_PLAYER );
outMsg.WriteByte( clientNum );
outMsg.WriteLong( spawnIds[ clientNum ] );
networkSystem->ServerSendReliableMessage( -1, outMsg );
if( gameType != GAME_TOURNEY ) {
((idPlayer*)entities[ clientNum ])->JoinInstance( 0 );
} else {
// instance 0 might be empty in Tourney
((idPlayer*)entities[ clientNum ])->JoinInstance( ((rvTourneyGameState*)gameLocal.mpGame.GetGameState())->GetNextActiveArena( 0 ) );
}
//RAVEN BEGIN
//asalmon: This client has finish loading and will be spawned mark them as ready.
#ifdef _XENON
Live()->ClientReady(clientNum);
#endif
//RAVEN END
}
/*
================
idGameLocal::RepeaterClientBegin
================
*/
void idGameLocal::RepeaterClientBegin( int clientNum ) {
viewers[ clientNum ].active = true;
}
/*
================
idGameLocal::ServerClientDisconnect
clientNum == MAX_CLIENTS for cleanup of server demo recording data
================
*/
void idGameLocal::ServerClientDisconnect( int clientNum ) {
int i;
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
if ( clientNum < MAX_CLIENTS ) {
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_DELETE_ENT );
outMsg.WriteBits( ( spawnIds[ clientNum ] << GENTITYNUM_BITS ) | clientNum, 32 ); // see GetSpawnId
networkSystem->ServerSendReliableMessage( -1, outMsg );
}
// free snapshots stored for this client
FreeSnapshotsOlderThanSequence( clientNum, 0x7FFFFFFF );
// free entity states stored for this client
for ( i = 0; i < MAX_GENTITIES; i++ ) {
if ( clientEntityStates[ clientNum ][ i ] ) {
entityStateAllocator.Free( clientEntityStates[ clientNum ][ i ] );
clientEntityStates[ clientNum ][ i ] = NULL;
}
}
// clear the client PVS
memset( clientPVS[ clientNum ], 0, sizeof( clientPVS[ clientNum ] ) );
if ( clientNum == MAX_CLIENTS ) {
return;
}
// only drop MP clients if we're in multiplayer and the server isn't going down
if ( gameLocal.isMultiplayer && !(gameLocal.isListenServer && clientNum == gameLocal.localClientNum ) ) {
// idMultiplayerGame::DisconnectClient will do the delete in MP
mpGame.DisconnectClient( clientNum );
} else {
// delete the player entity
delete entities[ clientNum ];
}
}
/*
================
idGameLocal::RepeaterClientDisconnect
================
*/
void idGameLocal::RepeaterClientDisconnect( int clientNum ) {
int i;
if ( clientNum >= maxViewers ) {
// this can happen during shutdown, because repeater clients are
// discarded when the (shared) entity states/snapshots of the other
// clients are freed
return;
}
// free snapshots stored for this client
FreeSnapshotsOlderThanSequence( viewerSnapshots[ clientNum ], 0x7FFFFFFF );
// free entity states stored for this client
for ( i = 0; i < MAX_GENTITIES; i++ ) {
if ( viewerEntityStates[ clientNum ][ i ] ) {
entityStateAllocator.Free( viewerEntityStates[ clientNum ][ i ] );
viewerEntityStates[ clientNum ][ i ] = NULL;
}
}
// clear the client PVS
memset( viewerPVS[ clientNum ], 0, sizeof( viewerPVS[ clientNum ] ) );
viewerUnreliableMessages[ clientNum ].Init( 0 );
viewers[ clientNum ].connected = false;
viewers[ clientNum ].active = false;
viewers[ clientNum ].priv = false;
viewers[ clientNum ].nopvs = false;
if ( maxViewer <= (clientNum+1) ) {
// find the new highest client
for ( maxViewer = clientNum; maxViewer >= 0 && !viewers[ maxViewer ].connected; maxViewer-- ) ;
maxViewer++;
}
// remove them from private/nopvs lists
for ( int i = 0; i < privateViewerIds.Num(); i++ ) {
int num = networkSystem->RepeaterGetClientNum( privateViewerIds[ i ] );
// check for timed out clientids
if ( num < 0 ) {
nopvsViewerIds.Remove( privateViewerIds[ i ] );
privateViewerIds.RemoveIndex( i );
i--;
continue;
}
if ( num == clientNum ) {
nopvsViewerIds.Remove( privateViewerIds[ i ] );
privateViewerIds.RemoveIndex( i );
i--;
continue;
}
}
// count up viewer slots so players know when servers are full
int numClients = 0;
for ( int i = 0; i < maxViewer; i++ ) {
if ( !viewers[ i ].connected ) {
continue;
}
++numClients;
}
int numPrivateClients = privateViewerIds.Num();
// private clients that take up public slots are considered public clients
numPrivateClients = idMath::ClampInt( 0, ri_privateViewers.GetInteger(), numPrivateClients );
ri_numViewers.SetInteger( numClients );
ri_numPrivateViewers.SetInteger( numPrivateClients );
UpdateRepeaterInfo();
}
/*
================
idGameLocal::ServerWriteInitialReliableMessages
Send reliable messages to initialize the client game up to a certain initial state.
================
*/
void idGameLocal::ServerWriteInitialReliableMessages( int clientNum ) {
int i;
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
// spawn players
for ( i = 0; i < MAX_CLIENTS; i++ ) {
if ( entities[i] == NULL || i == clientNum ) {
continue;
}
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting( );
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_SPAWN_PLAYER );
outMsg.WriteByte( i );
outMsg.WriteLong( spawnIds[ i ] );
networkSystem->ServerSendReliableMessage( clientNum, outMsg, true );
}
// update portals for opened doors
int numPortals = gameRenderWorld->NumPortals();
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_PORTALSTATES );
outMsg.WriteLong( numPortals );
for ( i = 0; i < numPortals; i++ ) {
outMsg.WriteBits( gameRenderWorld->GetPortalState( (qhandle_t) (i+1) ) , NUM_RENDER_PORTAL_BITS );
}
networkSystem->ServerSendReliableMessage( clientNum, outMsg, true );
mpGame.ServerWriteInitialReliableMessages( serverReliableSender.To( clientNum, true ), clientNum );
}
/*
================
idGameLocal::RepeaterWriteInitialReliableMessages
Send reliable messages to initialize the client game up to a certain initial state.
================
*/
void idGameLocal::RepeaterWriteInitialReliableMessages( int clientNum ) {
int i;
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
// spawn players
for ( i = 0; i < MAX_CLIENTS; i++ ) {
if ( entities[i] == NULL ) {
continue;
}
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting( );
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_SPAWN_PLAYER );
outMsg.WriteByte( i );
outMsg.WriteLong( spawnIds[ i ] );
networkSystem->RepeaterSendReliableMessage( clientNum, outMsg );
}
// update portals for opened doors
int numPortals = gameRenderWorld->NumPortals();
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_PORTALSTATES );
outMsg.WriteLong( numPortals );
for ( i = 0; i < numPortals; i++ ) {
outMsg.WriteBits( gameRenderWorld->GetPortalState( (qhandle_t) (i+1) ) , NUM_RENDER_PORTAL_BITS );
}
networkSystem->RepeaterSendReliableMessage( clientNum, outMsg );
mpGame.ServerWriteInitialReliableMessages( repeaterReliableSender.To( clientNum ), ENTITYNUM_NONE );
}
/*
================
idGameLocal::FreeSnapshotsOlderThanSequence
================
*/
void idGameLocal::FreeSnapshotsOlderThanSequence( snapshot_t *&clientSnapshot, int sequence ) {
snapshot_t *snapshot, *lastSnapshot, *nextSnapshot;
entityState_t *state;
for ( lastSnapshot = NULL, snapshot = clientSnapshot; snapshot; snapshot = nextSnapshot ) {
nextSnapshot = snapshot->next;
if ( snapshot->sequence < sequence ) {
for ( state = snapshot->firstEntityState; state; state = snapshot->firstEntityState ) {
snapshot->firstEntityState = snapshot->firstEntityState->next;
entityStateAllocator.Free( state );
}
if ( lastSnapshot ) {
lastSnapshot->next = snapshot->next;
} else {
clientSnapshot = snapshot->next;
}
snapshotAllocator.Free( snapshot );
} else {
lastSnapshot = snapshot;
}
}
}
/*
================
idGameLocal::FreeSnapshotsOlderThanSequence
================
*/
void idGameLocal::FreeSnapshotsOlderThanSequence( int clientNum, int sequence ) {
FreeSnapshotsOlderThanSequence( clientSnapshots[ clientNum ], sequence );
}
/*
================
idGameLocal::ApplySnapshot
================
*/
bool idGameLocal::ApplySnapshot( snapshot_t *&clientSnapshot, entityState_t *entityStates[MAX_GENTITIES], int PVS[ENTITY_PVS_SIZE], int sequence ) {
snapshot_t *snapshot, *lastSnapshot, *nextSnapshot;
entityState_t *state;
FreeSnapshotsOlderThanSequence( clientSnapshot, sequence );
for ( lastSnapshot = NULL, snapshot = clientSnapshot; snapshot; snapshot = nextSnapshot ) {
nextSnapshot = snapshot->next;
if ( snapshot->sequence == sequence ) {
for ( state = snapshot->firstEntityState; state; state = state->next ) {
if ( entityStates[state->entityNumber] ) {
entityStateAllocator.Free( entityStates[state->entityNumber] );
}
entityStates[state->entityNumber] = state;
}
// ~512 bytes
memcpy( PVS, snapshot->pvs, sizeof( snapshot->pvs ) );
if ( lastSnapshot ) {
lastSnapshot->next = nextSnapshot;
} else {
clientSnapshot = nextSnapshot;
}
snapshotAllocator.Free( snapshot );
return true;
} else {
lastSnapshot = snapshot;
}
}
return false;
}
/*
================
idGameLocal::ApplySnapshot
================
*/
bool idGameLocal::ApplySnapshot( int clientNum, int sequence ) {
return ApplySnapshot( clientSnapshots[ clientNum ], clientEntityStates[ clientNum ], clientPVS[ clientNum ], sequence );
}
/*
================
idGameLocal::WriteGameStateToSnapshot
================
*/
void idGameLocal::WriteGameStateToSnapshot( idBitMsgDelta &msg ) const {
int i;
for( i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++ ) {
msg.WriteFloat( globalShaderParms[i] );
}
mpGame.WriteToSnapshot( msg );
}
/*
================
idGameLocal::ReadGameStateFromSnapshot
================
*/
void idGameLocal::ReadGameStateFromSnapshot( const idBitMsgDelta &msg ) {
int i;
for( i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++ ) {
globalShaderParms[i] = msg.ReadFloat();
}
mpGame.ReadFromSnapshot( msg );
}
/*
================
idGameLocal::WriteSnapshot
Write a snapshot of the current game state for the given client.
================
*/
void idGameLocal::WriteSnapshot( snapshot_t *&clientSnapshot, entityState_t *entityStates[MAX_GENTITIES], int PVS[ENTITY_PVS_SIZE], idMsgQueue &unreliable, int sequence, idBitMsg &msg, int transmitEntity, int transmitEntity2, int instance, bool doPVS, const idBounds &pvs_bounds, int lastSnapshotFrame ) {
int i, msgSize, msgWriteBit;
idEntity *ent;
pvsHandle_t pvsHandle = { 0, 0 }; // shut warning
idBitMsgDelta deltaMsg;
snapshot_t *snapshot;
entityState_t *base, *newBase;
int numSourceAreas, sourceAreas[ idEntity::MAX_PVS_AREAS ];
// free too old snapshots
// ( that's a security, normal acking from server keeps a smaller backlog of snaps )
FreeSnapshotsOlderThanSequence( clientSnapshot, sequence - 64 );
// allocate new snapshot
snapshot = snapshotAllocator.Alloc();
snapshot->sequence = sequence;
snapshot->firstEntityState = NULL;
snapshot->next = clientSnapshot;
clientSnapshot = snapshot;
memset( snapshot->pvs, 0, sizeof( snapshot->pvs ) );
if ( doPVS ) {
// get PVS for this player
// don't use PVSAreas for networking - PVSAreas depends on animations (and md5 bounds), which are not synchronized
numSourceAreas = gameRenderWorld->BoundsInAreas( pvs_bounds, sourceAreas, idEntity::MAX_PVS_AREAS );
pvsHandle = gameLocal.pvs.SetupCurrentPVS( sourceAreas, numSourceAreas, PVS_NORMAL );
}
#if ASYNC_WRITE_TAGS
idRandom tagRandom;
tagRandom.SetSeed( random.RandomInt() );
msg.WriteLong( tagRandom.GetSeed() );
#endif
// write unreliable messages
unreliable.WriteTo( msg ); // NOTE: No flush
#if ASYNC_WRITE_TAGS
msg.WriteLong( tagRandom.RandomInt() );
#endif
// create the snapshot
for( ent = spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) {
// local fake client
if ( ent->entityNumber == ENTITYNUM_NONE ) {
continue;
}
// if the entity is not in the player PVS
if ( doPVS && !ent->PhysicsTeamInPVS( pvsHandle ) && ent->entityNumber != transmitEntity && ent->entityNumber != transmitEntity2 ) {
continue;
}
if ( ent->GetInstance() != instance ) {
continue;
}
// if the entity is a map entity, mark it in PVS
if ( isMapEntity[ ent->entityNumber ] ) {
snapshot->pvs[ ent->entityNumber >> 5 ] |= 1 << ( ent->entityNumber & 31 );
}
// if that entity is not marked for network synchronization
if ( !ent->fl.networkSync ) {
continue;
}
// add the entity to the snapshot PVS
snapshot->pvs[ ent->entityNumber >> 5 ] |= 1 << ( ent->entityNumber & 31 );
// save the write state to which we can revert when the entity didn't change at all
msg.SaveWriteState( msgSize, msgWriteBit );
// write the entity to the snapshot
msg.WriteBits( ent->entityNumber, GENTITYNUM_BITS );
base = entityStates[ent->entityNumber];
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ent->entityNumber;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitWriting( base ? &base->state : NULL, &newBase->state, &msg );
deltaMsg.WriteBits( spawnIds[ ent->entityNumber ], 32 - GENTITYNUM_BITS );
assert( ent->entityDefNumber > 0 );
deltaMsg.WriteBits( ent->entityDefNumber, entityDefBits );
// write the class specific data to the snapshot
ent->WriteToSnapshot( deltaMsg );
// if this is a player and a transmit of the player state has been requested, write the player state
if ( ent->entityNumber < MAX_CLIENTS ) {
if ( transmitEntity < 0 || transmitEntity == ent->entityNumber || transmitEntity2 == ent->entityNumber ) {
assert( ent->IsType( idPlayer::GetClassType() ) );
deltaMsg.WriteBits( 1, 1 );
static_cast< idPlayer * >( ent )->WritePlayerStateToSnapshot( lastSnapshotFrame, deltaMsg );
} else {
deltaMsg.WriteBits( 0, 1 );
}
}
if ( !deltaMsg.HasChanged() ) {
msg.RestoreWriteState( msgSize, msgWriteBit );
entityStateAllocator.Free( newBase );
} else {
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
#if ASYNC_WRITE_TAGS
msg.WriteLong( tagRandom.RandomInt() );
#endif
}
}
msg.WriteBits( ENTITYNUM_NONE, GENTITYNUM_BITS );
// write the PVS to the snapshot
#if ASYNC_WRITE_PVS
if ( doPVS ) {
for ( i = 0; i < idEntity::MAX_PVS_AREAS; i++ ) {
if ( i < numSourceAreas ) {
msg.WriteLong( sourceAreas[ i ] );
} else {
msg.WriteLong( 0 );
}
}
gameLocal.pvs.WritePVS( pvsHandle, msg );
}
#endif
// always write the entity pvs, even when doPVS isn't set
for ( i = 0; i < ENTITY_PVS_SIZE; i++ ) {
msg.WriteDeltaLong( PVS[i], snapshot->pvs[i] );
}
if ( doPVS ) {
// free the PVS
pvs.FreeCurrentPVS( pvsHandle );
}
// write the game state to the snapshot
base = entityStates[ENTITYNUM_NONE]; // ENTITYNUM_NONE is used for the game state
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ENTITYNUM_NONE;
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitWriting( base ? &base->state : NULL, &newBase->state, &msg );
WriteGameStateToSnapshot( deltaMsg );
}
/*
================
idGameLocal::ServerWriteSnapshot
Write a snapshot of the current game state for the given client.
================
*/
void idGameLocal::ServerWriteSnapshot( int clientNum, int sequence, idBitMsg &msg, dword *clientInPVS, int numPVSClients, int lastSnapshotFrame ) {
int i;
idPlayer *player, *spectated = NULL;
player = static_cast<idPlayer *>( entities[ clientNum ] );
assert( player );
if ( player->spectating && player->spectator != clientNum && entities[ player->spectator ] ) {
spectated = static_cast< idPlayer * >( entities[ player->spectator ] );
} else {