-
Notifications
You must be signed in to change notification settings - Fork 15
/
game_base.cpp
4892 lines (3867 loc) · 159 KB
/
game_base.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
/*
ent-ghost
Copyright [2011-2013] [Jack Lu]
This file is part of the ent-ghost source code.
ent-ghost 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.
ent-ghost 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 ent-ghost source code. If not, see <http://www.gnu.org/licenses/>.
ent-ghost is modified from GHost++ (http://ghostplusplus.googlecode.com/)
GHost++ is Copyright [2008] [Trevor Hogan]
*/
#include "ghost.h"
#include "util.h"
#include "config.h"
#include "language.h"
#include "socket.h"
#include "ghostdb.h"
#include "bnet.h"
#include "map.h"
#include "packed.h"
#include "savegame.h"
#include "replay.h"
#include "gameplayer.h"
#include "gameprotocol.h"
#include "game_base.h"
#include <cmath>
#include <string.h>
#include <time.h>
#include "next_combination.h"
//
// CBaseGame
//
CBaseGame :: CBaseGame( CGHost *nGHost, CMap *nMap, CSaveGame *nSaveGame, uint16_t nHostPort, unsigned char nGameState, string nGameName, string nOwnerName, string nCreatorName, string nCreatorServer ) : m_GHost( nGHost ), m_SaveGame( nSaveGame ), m_Replay( NULL ), m_Exiting( false ), m_Saving( false ), m_HostPort( nHostPort ), m_GameState( nGameState ), m_VirtualHostPID( 255 ), m_GProxyEmptyActions( 0 ), m_GameName( nGameName ), m_LastGameName( nGameName ), m_VirtualHostName( m_GHost->m_VirtualHostName ), m_OwnerName( nOwnerName ), m_CreatorName( nCreatorName ), m_CreatorServer( nCreatorServer ), m_HCLCommandString( nMap->GetMapDefaultHCL( ) ), m_RandomSeed( GetTicks( ) ), m_HostCounter( m_GHost->m_HostCounter++ ), m_EntryKey( rand( ) ), m_Latency( m_GHost->m_Latency ), m_SyncLimit( m_GHost->m_SyncLimit ), m_SyncCounter( 0 ), m_GameTicks( 0 ), m_CreationTime( GetTime( ) ), m_LastPingTime( GetTime( ) ), m_LastRefreshTime( GetTime( ) ), m_LastDownloadTicks( GetTime( ) ), m_DownloadCounter( 0 ), m_LastDownloadCounterResetTicks( GetTime( ) ), m_LastAnnounceTime( 0 ), m_AnnounceInterval( 0 ), m_LastAutoStartTime( GetTime( ) ), m_AutoStartPlayers( 0 ), m_LastCountDownTicks( 0 ), m_CountDownCounter( 0 ), m_StartedLoadingTicks( 0 ), m_StartPlayers( 0 ), m_LastLagScreenResetTime( 0 ), m_LastActionSentTicks( 0 ), m_LastActionLateBy( 0 ), m_StartedLaggingTime( 0 ), m_LastLagScreenTime( 0 ), m_LastReservedSeen( GetTime( ) ), m_StartedKickVoteTime( 0 ), m_StartedVoteStartTime( 0 ), m_GameOverTime( 0 ), m_LastPlayerLeaveTicks( 0 ), m_MinimumScore( 0. ), m_MaximumScore( 0. ), m_SlotInfoChanged( false ), m_Locked( false ), m_RefreshMessages( m_GHost->m_RefreshMessages ), m_RefreshError( false ), m_RefreshRehosted( false ), m_MuteAll( false ), m_MuteLobby( false ), m_CountDownStarted( false ), m_GameLoading( false ), m_GameLoaded( false ), m_LoadInGame( nMap->GetMapLoadInGame( ) ), m_Lagging( false ), m_AutoSave( m_GHost->m_AutoSave ), m_MatchMaking( false ), m_LocalAdminMessages( m_GHost->m_LocalAdminMessages ), m_DoDelete( 0 ), m_LastReconnectHandleTime( 0 ), m_League( false ), m_Tournament( false ), m_TournamentMatchID( 0 ), m_TournamentChatID( 0 ), m_SoftGameOver( false ), m_AllowDownloads( true )
{
m_Socket = new CTCPServer( );
m_Protocol = new CGameProtocol( m_GHost );
m_Map = new CMap( *nMap );
m_MapName = m_Map->GetMapPath( );
m_DatabaseID = 0;
if( m_GHost->m_SaveReplays && !m_SaveGame )
m_Replay = new CReplay( );
if( m_Map->GetMapTournament( ) )
m_Tournament = true;
// wait time of 1 minute = 0 empty actions required
// wait time of 2 minutes = 1 empty action required
// etc...
if( m_GHost->m_ReconnectWaitTime != 0 )
{
m_GProxyEmptyActions = m_GHost->m_ReconnectWaitTime - 1;
// clamp to 9 empty actions (10 minutes)
if( m_GProxyEmptyActions > 9 )
m_GProxyEmptyActions = 9;
}
if( m_SaveGame )
{
m_EnforceSlots = m_SaveGame->GetSlots( );
m_Slots = m_SaveGame->GetSlots( );
// the savegame slots contain player entries
// we really just want the open/closed/computer entries
// so open all the player slots
for( vector<CGameSlot> :: iterator i = m_Slots.begin( ); i != m_Slots.end( ); ++i )
{
if( (*i).GetSlotStatus( ) == SLOTSTATUS_OCCUPIED && (*i).GetComputer( ) == 0 )
{
(*i).SetPID( 0 );
(*i).SetDownloadStatus( 255 );
(*i).SetSlotStatus( SLOTSTATUS_OPEN );
}
}
}
else
m_Slots = m_Map->GetSlots( );
if( !m_GHost->m_IPBlackListFile.empty( ) )
{
ifstream in;
in.open( m_GHost->m_IPBlackListFile.c_str( ) );
if( in.fail( ) )
CONSOLE_Print( "[GAME: " + m_GameName + "] error loading IP blacklist file [" + m_GHost->m_IPBlackListFile + "]" );
else
{
CONSOLE_Print( "[GAME: " + m_GameName + "] loading IP blacklist file [" + m_GHost->m_IPBlackListFile + "]" );
string Line;
while( !in.eof( ) )
{
getline( in, Line );
// ignore blank lines and comments
if( Line.empty( ) || Line[0] == '#' )
continue;
// remove newlines and partial newlines to help fix issues with Windows formatted files on Linux systems
Line.erase( remove( Line.begin( ), Line.end( ), ' ' ), Line.end( ) );
Line.erase( remove( Line.begin( ), Line.end( ), '\r' ), Line.end( ) );
Line.erase( remove( Line.begin( ), Line.end( ), '\n' ), Line.end( ) );
// ignore lines that don't look like IP addresses
if( Line.find_first_not_of( "1234567890." ) != string :: npos )
continue;
m_IPBlackList.insert( Line );
}
in.close( );
CONSOLE_Print( "[GAME: " + m_GameName + "] loaded " + UTIL_ToString( m_IPBlackList.size( ) ) + " lines from IP blacklist file" );
}
}
// start listening for connections
if( !m_GHost->m_BindAddress.empty( ) )
CONSOLE_Print( "[GAME: " + m_GameName + "] attempting to bind to address [" + m_GHost->m_BindAddress + "]" );
else
CONSOLE_Print( "[GAME: " + m_GameName + "] attempting to bind to all available addresses" );
if( m_Socket->Listen( "", m_HostPort ) )
CONSOLE_Print( "[GAME: " + m_GameName + "] listening on port " + UTIL_ToString( m_HostPort ) );
else
{
CONSOLE_Print( "[GAME: " + m_GameName + "] error listening on port " + UTIL_ToString( m_HostPort ) );
m_Exiting = true;
}
}
CBaseGame :: ~CBaseGame( )
{
delete m_Socket;
delete m_Protocol;
delete m_Map;
delete m_Replay;
for( vector<CPotentialPlayer *> :: iterator i = m_Potentials.begin( ); i != m_Potentials.end( ); ++i )
delete *i;
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
delete *i;
boost::mutex::scoped_lock lock( m_GHost->m_CallablesMutex );
for( vector<CCallableConnectCheck *> :: iterator i = m_ConnectChecks.begin( ); i != m_ConnectChecks.end( ); ++i )
m_GHost->m_Callables.push_back( *i );
for( vector<CCallableScoreCheck *> :: iterator i = m_ScoreChecks.begin( ); i != m_ScoreChecks.end( ); ++i )
m_GHost->m_Callables.push_back( *i );
for( vector<CCallableLeagueCheck *> :: iterator i = m_LeagueChecks.begin( ); i != m_LeagueChecks.end( ); ++i )
m_GHost->m_Callables.push_back( *i );
// if tournament, update tournament database status
if( m_Tournament && m_TournamentMatchID != 0 )
{
m_GHost->m_Callables.push_back( m_GHost->m_DB->ThreadedTournamentUpdate( m_TournamentMatchID, m_GameName, 4 ) );
}
lock.unlock( );
while( !m_Actions.empty( ) )
{
delete m_Actions.front( );
m_Actions.pop( );
}
}
void CBaseGame :: doDelete( )
{
m_DoDelete = 1;
}
bool CBaseGame :: readyDelete( )
{
return m_DoDelete == 2;
}
void CBaseGame :: loop( )
{
while( m_DoDelete == 0 )
{
fd_set fd;
fd_set send_fd;
FD_ZERO( &fd );
FD_ZERO( &send_fd );
int nfds = 0;
unsigned int NumFDs = SetFD( &fd, &send_fd, &nfds );
long usecBlock = 50000;
if( GetNextTimedActionTicks( ) * 1000 < usecBlock )
usecBlock = GetNextTimedActionTicks( ) * 1000;
if(usecBlock < 1000) usecBlock = 1000;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = usecBlock;
struct timeval send_tv;
send_tv.tv_sec = 0;
send_tv.tv_usec = 0;
#ifdef WIN32
select( 1, &fd, NULL, NULL, &tv );
select( 1, NULL, &send_fd, NULL, &send_tv );
#else
select( nfds + 1, &fd, NULL, NULL, &tv );
select( nfds + 1, NULL, &send_fd, NULL, &send_tv );
#endif
if( NumFDs == 0 )
{
// select will return immediately and we'll chew up the CPU if we let it loop so just sleep for 50ms to kill some time
MILLISLEEP( 50 );
}
if( Update( &fd, &send_fd ) )
{
CONSOLE_Print( "[GameThread] deleting game [" + GetGameName( ) + "]" );
m_DoDelete = 3;
break;
}
else
{
UpdatePost( &send_fd );
}
}
// save replay
if( m_Replay && ( m_GameLoading || m_GameLoaded ) )
{
time_t Now = time( NULL );
char Time[17];
memset( Time, 0, sizeof( char ) * 17 );
strftime( Time, sizeof( char ) * 17, "%Y-%m-%d %H-%M", localtime( &Now ) );
string MinString = UTIL_ToString( ( m_GameTicks / 1000 ) / 60 );
string SecString = UTIL_ToString( ( m_GameTicks / 1000 ) % 60 );
if( MinString.size( ) == 1 )
MinString.insert( 0, "0" );
if( SecString.size( ) == 1 )
SecString.insert( 0, "0" );
m_Replay->BuildReplay( m_GameName, m_StatString, m_GHost->m_ReplayWar3Version, m_GHost->m_ReplayBuildNumber );
if(m_DatabaseID == 0) {
m_Replay->Save( m_GHost->m_TFT, m_GHost->m_ReplayPath + UTIL_FileSafeName( "GHost++ " + string( Time ) + " " + m_GameName + " (" + MinString + "m" + SecString + "s).w3g" ) );
} else {
m_Replay->Save( m_GHost->m_TFT, m_GHost->m_ReplayPath + UTIL_FileSafeName( UTIL_ToString( m_DatabaseID ) + ".w3g" ) );
}
}
if(m_DoDelete == 1)
delete this;
else
m_DoDelete = 2;
}
uint32_t CBaseGame :: GetNextTimedActionTicks( )
{
// return the number of ticks (ms) until the next "timed action", which for our purposes is the next game update
// the main GHost++ loop will make sure the next loop update happens at or before this value
// note: there's no reason this function couldn't take into account the game's other timers too but they're far less critical
// warning: this function must take into account when actions are not being sent (e.g. during loading or lagging)
if( !m_GameLoaded || m_Lagging )
return 50;
uint32_t TicksSinceLastUpdate = GetTicks( ) - m_LastActionSentTicks;
if( TicksSinceLastUpdate > m_Latency - m_LastActionLateBy )
return 0;
else
return m_Latency - m_LastActionLateBy - TicksSinceLastUpdate;
}
uint32_t CBaseGame :: GetSlotsOccupied( )
{
uint32_t NumSlotsOccupied = 0;
for( vector<CGameSlot> :: iterator i = m_Slots.begin( ); i != m_Slots.end( ); ++i )
{
if( (*i).GetSlotStatus( ) == SLOTSTATUS_OCCUPIED )
++NumSlotsOccupied;
}
return NumSlotsOccupied;
}
uint32_t CBaseGame :: GetSlotsAllocated( )
{
uint32_t SlotsOccupied = GetSlotsOccupied( );
uint32_t NumPlayers = m_Players.size( );
if( NumPlayers > SlotsOccupied )
return NumPlayers;
else
return SlotsOccupied;
}
uint32_t CBaseGame :: GetSlotsOpen( )
{
uint32_t NumSlotsOpen = 0;
for( vector<CGameSlot> :: iterator i = m_Slots.begin( ); i != m_Slots.end( ); ++i )
{
if( (*i).GetSlotStatus( ) == SLOTSTATUS_OPEN )
++NumSlotsOpen;
}
return NumSlotsOpen;
}
uint32_t CBaseGame :: GetNumPlayers( )
{
return GetNumHumanPlayers( ) + m_FakePlayers.size( );
}
uint32_t CBaseGame :: GetNumHumanPlayers( )
{
uint32_t NumHumanPlayers = 0;
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
if( !(*i)->GetLeftMessageSent( ) )
++NumHumanPlayers;
}
return NumHumanPlayers;
}
string CBaseGame :: GetDescription( )
{
string Description = m_GameName + " : " + m_OwnerName + " : " + UTIL_ToString( GetNumHumanPlayers( ) ) + "/" + UTIL_ToString( m_GameLoading || m_GameLoaded ? m_StartPlayers : m_Slots.size( ) );
if( m_GameLoading || m_GameLoaded )
Description += " : " + UTIL_ToString( ( m_GameTicks / 1000 ) / 60 ) + "m";
else
Description += " : " + UTIL_ToString( ( GetTime( ) - m_CreationTime ) / 60 ) + "m";
return Description;
}
void CBaseGame :: SetAnnounce( uint32_t interval, string message )
{
m_AnnounceInterval = interval;
m_AnnounceMessage = message;
m_LastAnnounceTime = GetTime( );
}
unsigned int CBaseGame :: SetFD( void *fd, void *send_fd, int *nfds )
{
unsigned int NumFDs = 0;
if( m_Socket )
{
m_Socket->SetFD( (fd_set *)fd, (fd_set *)send_fd, nfds );
++NumFDs;
}
for( vector<CPotentialPlayer *> :: iterator i = m_Potentials.begin( ); i != m_Potentials.end( ); ++i )
{
if( (*i)->GetSocket( ) )
{
(*i)->GetSocket( )->SetFD( (fd_set *)fd, (fd_set *)send_fd, nfds );
++NumFDs;
}
}
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
if( (*i)->GetSocket( ) )
{
(*i)->GetSocket( )->SetFD( (fd_set *)fd, (fd_set *)send_fd, nfds );
++NumFDs;
}
}
return NumFDs;
}
bool CBaseGame :: Update( void *fd, void *send_fd )
{
// update callables
for( vector<CCallableScoreCheck *> :: iterator i = m_ScoreChecks.begin( ); i != m_ScoreChecks.end( ); )
{
if( (*i)->GetReady( ) )
{
double *Score = (*i)->GetResult( );
if( Score != NULL )
{
for( vector<CPotentialPlayer *> :: iterator j = m_Potentials.begin( ); j != m_Potentials.end( ); ++j )
{
if( (*j)->GetJoinPlayer( ) && (*j)->GetJoinPlayer( )->GetName( ) == (*i)->GetName( ) )
EventPlayerJoined( *j, (*j)->GetJoinPlayer( ), Score );
}
}
else
{
// this is bad, it means that the score check failed
// we ignore and eventually player will be kicked
}
m_GHost->m_DB->RecoverCallable( *i );
delete *i;
i = m_ScoreChecks.erase( i );
}
else
++i;
}
for( vector<CCallableLeagueCheck *> :: iterator i = m_LeagueChecks.begin( ); i != m_LeagueChecks.end( ); )
{
if( (*i)->GetReady( ) )
{
double SID = (*i)->GetResult( ); //convert to double so we don't need another parameter
double *Array = new double[2];
Array[0] = SID;
Array[1] = 1000.0;
for( vector<CPotentialPlayer *> :: iterator j = m_Potentials.begin( ); j != m_Potentials.end( ); ++j )
{
if( (*j)->GetJoinPlayer( ) && (*j)->GetJoinPlayer( )->GetName( ) == (*i)->GetName( ) )
EventPlayerJoined( *j, (*j)->GetJoinPlayer( ), Array );
}
m_GHost->m_DB->RecoverCallable( *i );
delete *i;
delete [] Array;
i = m_LeagueChecks.erase( i );
}
else
++i;
}
for( vector<CCallableConnectCheck *> :: iterator i = m_ConnectChecks.begin( ); i != m_ConnectChecks.end( ); )
{
if( (*i)->GetReady( ) )
{
bool Check = (*i)->GetResult( );
for( vector<CGamePlayer *> :: iterator j = m_Players.begin( ); j != m_Players.end( ); ++j )
{
if( (*j)->GetName( ) == (*i)->GetName( ) )
{
if( Check )
{
(*j)->SetSpoofed( true );
(*j)->SetSpoofedRealm( "wc3connect" );
}
else
{
(*j)->SetDeleteMe( true );
(*j)->SetLeftReason( "invalid session" );
(*j)->SetLeftCode( PLAYERLEAVE_LOBBY );
m_GHost->DenyIP( (*j)->GetExternalIPString( ), 20000, "kicked for invalid session" );
OpenSlot( GetSIDFromPID( (*j)->GetPID( ) ), false );
}
break;
}
}
m_GHost->m_DB->RecoverCallable( *i );
delete *i;
i = m_ConnectChecks.erase( i );
}
else
++i;
}
// update players
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); )
{
if( (*i)->Update( fd ) )
{
EventPlayerDeleted( *i );
delete *i;
i = m_Players.erase( i );
}
else
++i;
}
for( vector<CPotentialPlayer *> :: iterator i = m_Potentials.begin( ); i != m_Potentials.end( ); )
{
if( (*i)->Update( fd ) )
{
// flush the socket (e.g. in case a rejection message is queued)
if( (*i)->GetSocket( ) )
(*i)->GetSocket( )->DoSend( (fd_set *)send_fd );
delete *i;
i = m_Potentials.erase( i );
}
else
++i;
}
// create the virtual host player
if( !m_GameLoading && !m_GameLoaded && GetSlotsAllocated() < m_Slots.size() )
CreateVirtualHost( );
// unlock the game
if( m_Locked && !GetPlayerFromName( m_OwnerName, false ) )
{
SendAllChat( m_GHost->m_Language->GameUnlocked( ) );
m_Locked = false;
}
// ping every 5 seconds
// changed this to ping during game loading as well to hopefully fix some problems with people disconnecting during loading
// changed this to ping during the game as well
if( GetTime( ) - m_LastPingTime >= 5 )
{
// note: we must send pings to players who are downloading the map because Warcraft III disconnects from the lobby if it doesn't receive a ping every ~90 seconds
// so if the player takes longer than 90 seconds to download the map they would be disconnected unless we keep sending pings
// todotodo: ignore pings received from players who have recently finished downloading the map
SendAll( m_Protocol->SEND_W3GS_PING_FROM_HOST( ) );
// we also broadcast the game to the local network every 5 seconds so we hijack this timer for our nefarious purposes
// however we only want to broadcast if the countdown hasn't started
// see the !sendlan code later in this file for some more information about how this works
// todotodo: should we send a game cancel message somewhere? we'll need to implement a host counter for it to work
if( !m_CountDownStarted )
{
// construct a fixed host counter which will be used to identify players from this "realm" (i.e. LAN)
// the fixed host counter's 4 most significant bits will contain a 4 bit ID (0-15)
// the rest of the fixed host counter will contain the 28 least significant bits of the actual host counter
// since we're destroying 4 bits of information here the actual host counter should not be greater than 2^28 which is a reasonable assumption
// when a player joins a game we can obtain the ID from the received host counter
// note: LAN broadcasts use an ID of 0, battle.net refreshes use an ID of 1-10, the rest are unused
uint32_t FixedHostCounter = m_HostCounter & 0x0FFFFFFF;
// we send 12 for SlotsTotal because this determines how many PID's Warcraft 3 allocates
// we need to make sure Warcraft 3 allocates at least SlotsTotal + 1 but at most 12 PID's
// this is because we need an extra PID for the virtual host player (but we always delete the virtual host player when the 12th person joins)
// however, we can't send 13 for SlotsTotal because this causes Warcraft 3 to crash when sharing control of units
// nor can we send SlotsTotal because then Warcraft 3 crashes when playing maps with less than 12 PID's (because of the virtual host player taking an extra PID)
// we also send 12 for SlotsOpen because Warcraft 3 assumes there's always at least one player in the game (the host)
// so if we try to send accurate numbers it'll always be off by one and results in Warcraft 3 assuming the game is full when it still needs one more player
// the easiest solution is to simply send 12 for both so the game will always show up as (1/12) players
uint32_t slotstotal = m_Slots.size( );
uint32_t slotsopen = GetSlotsOpen();
if (slotsopen<2) slotsopen = 2;
if(slotstotal > 12) slotstotal = 12;
if( m_SaveGame )
{
// note: the PrivateGame flag is not set when broadcasting to LAN (as you might expect)
uint32_t MapGameType = MAPGAMETYPE_SAVEDGAME;
BYTEARRAY MapWidth;
MapWidth.push_back( 0 );
MapWidth.push_back( 0 );
BYTEARRAY MapHeight;
MapHeight.push_back( 0 );
MapHeight.push_back( 0 );
m_GHost->m_UDPSocket->Broadcast( 6112, m_Protocol->SEND_W3GS_GAMEINFO( m_GHost->m_TFT, m_GHost->m_LANWar3Version, UTIL_CreateByteArray( MapGameType, false ), m_Map->GetMapGameFlags( ), MapWidth, MapHeight, m_GameName, "Varlock", GetTime( ) - m_CreationTime, "Save\\Multiplayer\\" + m_SaveGame->GetFileNameNoPath( ), m_SaveGame->GetMagicNumber( ), slotstotal, slotsopen, m_HostPort, FixedHostCounter, m_EntryKey ) );
m_GHost->m_LocalSocket->Broadcast( 6112, m_Protocol->SEND_W3GS_GAMEINFO( m_GHost->m_TFT, m_GHost->m_LANWar3Version, UTIL_CreateByteArray( MapGameType, false ), m_Map->GetMapGameFlags( ), MapWidth, MapHeight, m_GameName, "Varlock", GetTime( ) - m_CreationTime, "Save\\Multiplayer\\" + m_SaveGame->GetFileNameNoPath( ), m_SaveGame->GetMagicNumber( ), slotstotal, slotsopen, m_HostPort, FixedHostCounter, m_EntryKey ) );
}
else
{
// note: the PrivateGame flag is not set when broadcasting to LAN (as you might expect)
// note: we do not use m_Map->GetMapGameType because none of the filters are set when broadcasting to LAN (also as you might expect)
uint32_t MapGameType = MAPGAMETYPE_UNKNOWN0;
m_GHost->m_UDPSocket->Broadcast( 6112, m_Protocol->SEND_W3GS_GAMEINFO( m_GHost->m_TFT, m_GHost->m_LANWar3Version, UTIL_CreateByteArray( MapGameType, false ), m_Map->GetMapGameFlags( ), m_Map->GetMapWidth( ), m_Map->GetMapHeight( ), m_GameName, "Varlock", GetTime( ) - m_CreationTime, m_Map->GetMapPath( ), m_Map->GetMapCRC( ), slotstotal, slotsopen, m_HostPort, FixedHostCounter, m_EntryKey ) );
m_GHost->m_LocalSocket->Broadcast( 6112, m_Protocol->SEND_W3GS_GAMEINFO( m_GHost->m_TFT, m_GHost->m_LANWar3Version, UTIL_CreateByteArray( MapGameType, false ), m_Map->GetMapGameFlags( ), m_Map->GetMapWidth( ), m_Map->GetMapHeight( ), m_GameName, "Varlock", GetTime( ) - m_CreationTime, m_Map->GetMapPath( ), m_Map->GetMapCRC( ), slotstotal, slotsopen, m_HostPort, FixedHostCounter, m_EntryKey ) );
if( m_GameState == GAME_PUBLIC && !m_GHost->m_BNETs.empty( ) )
{
m_GHost->m_GamelistSocket->Broadcast( 8112, m_Protocol->SEND_CUSTOM_GAMELIST( m_GHost->m_UserName, m_GameName, m_OwnerName, slotstotal - slotsopen, slotstotal ) );
m_GHost->m_GamelistSocket->Broadcast( 8112, m_Protocol->SEND_W3GS_GAMEINFO( m_GHost->m_TFT, m_GHost->m_LANWar3Version, UTIL_CreateByteArray( MapGameType, false ), m_Map->GetMapGameFlags( ), m_Map->GetMapWidth( ), m_Map->GetMapHeight( ), m_GameName, "Varlock", GetTime( ) - m_CreationTime, m_Map->GetMapPath( ), m_Map->GetMapCRC( ), slotstotal, slotsopen, m_HostPort, FixedHostCounter, m_EntryKey ) );
}
}
}
m_LastPingTime = GetTime( );
}
// auto rehost if there was a refresh error in autohosted games
if( m_RefreshError && !m_CountDownStarted && m_GameState == GAME_PUBLIC && !m_GHost->m_AutoHostGameName.empty( ) && m_GHost->m_AutoHostMaximumGames != 0 && m_GHost->m_AutoHostAutoStartPlayers != 0 && m_AutoStartPlayers != 0 && GetTicks( ) - m_RefreshErrorTicks > 10000 )
{
// there's a slim chance that this isn't actually an autohosted game since there is no explicit autohost flag
// however, if autohosting is enabled and this game is public and this game is set to autostart, it's probably autohosted
// so rehost it using the current autohost game name
string GameName = m_GHost->m_AutoHostGameName + " #" + UTIL_ToString( m_GHost->m_HostCounter % 100 );
CONSOLE_Print( "[GAME: " + m_GameName + "] automatically trying to rehost as public game [" + GameName + "] due to refresh failure" );
//need to synchronize here because we're using host counter variable from GHost
// and also gamenames are used in some functions accessed externally
boost::mutex::scoped_lock lock( m_GHost->m_GamesMutex );
m_LastGameName = m_GameName;
m_GameName = GameName;
m_HostCounter = m_GHost->m_HostCounter++;
m_RefreshError = false;
for( vector<CBNET *> :: iterator i = m_GHost->m_BNETs.begin( ); i != m_GHost->m_BNETs.end( ); ++i )
{
(*i)->QueueGameUncreate( );
(*i)->QueueEnterChat( );
// the game creation message will be sent on the next refresh
}
m_CreationTime = GetTime( );
m_LastRefreshTime = GetTime( );
lock.unlock( );
}
// refresh every 3 seconds
if( !m_RefreshError && !m_CountDownStarted && m_GameState == GAME_PUBLIC && GetSlotsOpen( ) > 0 && GetTime( ) - m_LastRefreshTime >= 3 )
{
// send a game refresh packet to each battle.net connection
bool Refreshed = false;
for( vector<CBNET *> :: iterator i = m_GHost->m_BNETs.begin( ); i != m_GHost->m_BNETs.end( ); ++i )
{
// don't queue a game refresh message if the queue contains more than 1 packet because they're very low priority
if( (*i)->GetOutPacketsQueued( ) <= 1 )
{
(*i)->QueueGameRefresh( m_GameState, m_GameName, string( ), m_Map, m_SaveGame, 1, m_HostCounter );
Refreshed = true;
}
}
// only print the "game refreshed" message if we actually refreshed on at least one battle.net server
if( m_RefreshMessages && Refreshed )
SendAllChat( m_GHost->m_Language->GameRefreshed( ) );
m_LastRefreshTime = GetTime( );
}
// send more map data
if( !m_GameLoading && !m_GameLoaded && GetTicks( ) - m_LastDownloadCounterResetTicks >= 1000 )
{
// hackhack: another timer hijack is in progress here
// since the download counter is reset once per second it's a great place to update the slot info if necessary
if( m_SlotInfoChanged )
SendAllSlotInfo( );
m_DownloadCounter = 0;
m_LastDownloadCounterResetTicks = GetTicks( );
}
if( !m_GameLoading && !m_GameLoaded && GetTicks( ) - m_LastDownloadTicks >= 100 )
{
uint32_t Downloaders = 0;
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
if( (*i)->GetDownloadStarted( ) && !(*i)->GetDownloadFinished( ) )
{
++Downloaders;
if( m_GHost->m_MaxDownloaders > 0 && Downloaders > m_GHost->m_MaxDownloaders )
break;
// send up to 100 pieces of the map at once so that the download goes faster
// if we wait for each MAPPART packet to be acknowledged by the client it'll take a long time to download
// this is because we would have to wait the round trip time (the ping time) between sending every 1442 bytes of map data
// doing it this way allows us to send at least 140 KB in each round trip interval which is much more reasonable
// the theoretical throughput is [140 KB * 1000 / ping] in KB/sec so someone with 100 ping (round trip ping, not LC ping) could download at 1400 KB/sec
// note: this creates a queue of map data which clogs up the connection when the client is on a slower connection (e.g. dialup)
// in this case any changes to the lobby are delayed by the amount of time it takes to send the queued data (i.e. 140 KB, which could be 30 seconds or more)
// for example, players joining and leaving, slot changes, chat messages would all appear to happen much later for the low bandwidth player
// note: the throughput is also limited by the number of times this code is executed each second
// e.g. if we send the maximum amount (140 KB) 10 times per second the theoretical throughput is 1400 KB/sec
// therefore the maximum throughput is 1400 KB/sec regardless of ping and this value slowly diminishes as the player's ping increases
// in addition to this, the throughput is limited by the configuration value bot_maxdownloadspeed
// in summary: the actual throughput is MIN( 140 * 1000 / ping, 1400, bot_maxdownloadspeed ) in KB/sec assuming only one player is downloading the map
uint32_t MapSize = UTIL_ByteArrayToUInt32( m_Map->GetMapSize( ), false );
while( (*i)->GetLastMapPartSent( ) < (*i)->GetLastMapPartAcked( ) + 1442 * 100 && (*i)->GetLastMapPartSent( ) < MapSize )
{
if( (*i)->GetLastMapPartSent( ) == 0 )
{
// overwrite the "started download ticks" since this is the first time we've sent any map data to the player
// prior to this we've only determined if the player needs to download the map but it's possible we could have delayed sending any data due to download limits
(*i)->SetStartedDownloadingTicks( GetTicks( ) );
}
// limit the download speed if we're sending too much data
// the download counter is the # of map bytes downloaded in the last second (it's reset once per second)
if( m_GHost->m_MaxDownloadSpeed > 0 && m_DownloadCounter > m_GHost->m_MaxDownloadSpeed * 1024 )
break;
Send( *i, m_Protocol->SEND_W3GS_MAPPART( GetHostPID( ), (*i)->GetPID( ), (*i)->GetLastMapPartSent( ), m_Map->GetMapData( ) ) );
(*i)->SetLastMapPartSent( (*i)->GetLastMapPartSent( ) + 1442 );
m_DownloadCounter += 1442;
}
}
}
m_LastDownloadTicks = GetTicks( );
}
// announce every m_AnnounceInterval seconds
if( !m_AnnounceMessage.empty( ) && !m_CountDownStarted && GetTime( ) - m_LastAnnounceTime >= m_AnnounceInterval )
{
SendAllChat( m_AnnounceMessage );
m_LastAnnounceTime = GetTime( );
}
// handle saygames vector
boost::mutex::scoped_lock lock( m_SayGamesMutex );
if( !m_DoSayGames.empty( ) )
{
for( vector<string> :: iterator i = m_DoSayGames.begin( ); i != m_DoSayGames.end( ); ++i )
{
if( (*i)[0] == ':' )
SendAllChat( (*i).substr(1) );
else if( (*i)[0] == '/' )
{
string Command;
string Payload;
string Message = *i;
string :: size_type PayloadStart = Message.find( " " );
if( PayloadStart != string :: npos )
{
Command = Message.substr( 1, PayloadStart - 1 );
Payload = Message.substr( PayloadStart + 1 );
}
else
Command = Message.substr( 1 );
transform( Command.begin( ), Command.end( ), Command.begin( ), (int(*)(int))tolower );
CONSOLE_Print( "[GAME: " + m_GameName + "] received command from announce [" + Command + "] with payload [" + Payload + "]" );
if( Command == "kick" )
{
CGamePlayer *LastMatch = NULL;
uint32_t Matches = GetPlayerFromNamePartial( Payload, &LastMatch );
if( Matches == 1 )
{
LastMatch->SetDeleteMe( true );
LastMatch->SetLeftReason( m_GHost->m_Language->WasKickedByPlayer( "Admin" ) );
m_GHost->DenyIP( LastMatch->GetExternalIPString( ), 60000, "was kicked by !kick" );
if( !m_GameLoading && !m_GameLoaded )
LastMatch->SetLeftCode( PLAYERLEAVE_LOBBY );
else
LastMatch->SetLeftCode( PLAYERLEAVE_LOST );
if( !m_GameLoading && !m_GameLoaded )
OpenSlot( GetSIDFromPID( LastMatch->GetPID( ) ), false );
}
}
}
else
SendAllChat( "ANNOUNCEMENT: " + *i );
}
m_DoSayGames.clear( );
}
lock.unlock( );
// handle add to spoofed vector
if( !m_DoSpoofAdd.empty( ) )
{
boost::mutex::scoped_lock lock( m_SpoofAddMutex );
for( vector<QueuedSpoofAdd> :: iterator i = m_DoSpoofAdd.begin( ); i != m_DoSpoofAdd.end( ); ++i )
{
if( (*i).failMessage.empty( ) )
AddToSpoofed( (*i).server, (*i).name, (*i).sendMessage );
else
SendAllChat( (*i).failMessage );
}
m_DoSpoofAdd.clear( );
lock.unlock( );
}
// kick players who don't spoof check within 30 seconds when spoof checks are required and the game is autohosted
if( !m_CountDownStarted && m_GHost->m_RequireSpoofChecks && m_GameState == GAME_PUBLIC && !m_GHost->m_AutoHostGameName.empty( ) && m_GHost->m_AutoHostMaximumGames != 0 && m_GHost->m_AutoHostAutoStartPlayers != 0 && m_AutoStartPlayers != 0 )
{
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
if( !(*i)->GetSpoofed( ) && GetTime( ) - (*i)->GetJoinTime( ) >= 30 )
{
(*i)->SetDeleteMe( true );
(*i)->SetLeftReason( m_GHost->m_Language->WasKickedForNotSpoofChecking( ) );
(*i)->SetLeftCode( PLAYERLEAVE_LOBBY );
m_GHost->DenyIP( (*i)->GetExternalIPString( ), 20000, "kicked for spoof check" );
OpenSlot( GetSIDFromPID( (*i)->GetPID( ) ), false );
}
}
}
// try to auto start every 10 seconds
if( !m_CountDownStarted && m_AutoStartPlayers != 0 && GetTime( ) - m_LastAutoStartTime >= 10 )
{
StartCountDownAuto( m_GHost->m_RequireSpoofChecks );
m_LastAutoStartTime = GetTime( );
}
// countdown every 500 ms
if( m_CountDownStarted && GetTicks( ) - m_LastCountDownTicks >= 500 )
{
if( m_CountDownCounter > 0 )
{
// we use a countdown counter rather than a "finish countdown time" here because it might alternately round up or down the count
// this sometimes resulted in a countdown of e.g. "6 5 3 2 1" during my testing which looks pretty dumb
// doing it this way ensures it's always "5 4 3 2 1" but each interval might not be *exactly* the same length
SendAllChat( UTIL_ToString( m_CountDownCounter ) + ". . ." );
--m_CountDownCounter;
}
else if( !m_GameLoading && !m_GameLoaded )
EventGameStarted( );
m_LastCountDownTicks = GetTicks( );
}
// check if the lobby is "abandoned" and needs to be closed since it will never start
if( !m_GameLoading && !m_GameLoaded && m_GHost->m_LobbyTimeLimit > 0 && ( m_GHost->m_AutoHostGameName.empty( ) || m_GHost->m_AutoHostMaximumGames == 0 || m_GHost->m_AutoHostAutoStartPlayers == 0 || m_AutoStartPlayers == 0 ) )
{
// check if there's a player with reserved status in the game
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
if( (*i)->GetReserved( ) )
m_LastReservedSeen = GetTime( );
}
// check if we've hit the time limit
if( GetTime( ) - m_LastReservedSeen >= m_GHost->m_LobbyTimeLimit * 60 && !m_League )
{
CONSOLE_Print( "[GAME: " + m_GameName + "] is over (lobby time limit hit)" );
return true;
}
}
// check if the game is loaded
if( m_GameLoading )
{
// drop players who have not loaded if it's been a long time
bool DropLoading = GetTicks( ) - m_StartedLoadingTicks > 240000;
bool FinishedLoading = true;
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
FinishedLoading = (*i)->GetFinishedLoading( );
if( !FinishedLoading )
{
if( DropLoading )
{
(*i)->SetDeleteMe( true );
(*i)->SetLeftCode( PLAYERLEAVE_LOBBY );
m_GHost->DenyIP( (*i)->GetExternalIPString( ), 180000, "player has not yet finished loading" );
}
else
break;
}
}
if( FinishedLoading )
{
m_LastActionSentTicks = GetTicks( );
m_GameLoading = false;
m_GameLoaded = true;
EventGameLoaded( );
}
else
{
// reset the "lag" screen (the load-in-game screen) every 30 seconds
if( m_LoadInGame && GetTime( ) - m_LastLagScreenResetTime >= 30 )
{
bool UsingGProxy = false;
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
if( (*i)->GetGProxy( ) )
UsingGProxy = true;
}
for( vector<CGamePlayer *> :: iterator i = m_Players.begin( ); i != m_Players.end( ); ++i )
{
if( (*i)->GetFinishedLoading( ) )
{
// stop the lag screen
for( vector<CGamePlayer *> :: iterator j = m_Players.begin( ); j != m_Players.end( ); ++j )
{
if( !(*j)->GetFinishedLoading( ) )
Send( *i, m_Protocol->SEND_W3GS_STOP_LAG( *j, true ) );
}
// send an empty update
// this resets the lag screen timer but creates a rather annoying problem
// in order to prevent a desync we must make sure every player receives the exact same "desyncable game data" (updates and player leaves) in the exact same order
// unfortunately we cannot send updates to players who are still loading the map, so we buffer the updates to those players (see the else clause a few lines down for the code)
// in addition to this we must ensure any player leave messages are sent in the exact same position relative to these updates so those must be buffered too
if( UsingGProxy && !(*i)->GetGProxy( ) )
{
// we must send empty actions to non-GProxy++ players
// GProxy++ will insert these itself so we don't need to send them to GProxy++ players
// empty actions are used to extend the time a player can use when reconnecting
for( unsigned char j = 0; j < m_GProxyEmptyActions; ++j )
Send( *i, m_Protocol->SEND_W3GS_INCOMING_ACTION( queue<CIncomingAction *>( ), 0 ) );
}
Send( *i, m_Protocol->SEND_W3GS_INCOMING_ACTION( queue<CIncomingAction *>( ), 0 ) );
// start the lag screen
Send( *i, m_Protocol->SEND_W3GS_START_LAG( m_Players, true ) );
}
else
{
// buffer the empty update since the player is still loading the map
if( UsingGProxy && !(*i)->GetGProxy( ) )
{
// we must send empty actions to non-GProxy++ players
// GProxy++ will insert these itself so we don't need to send them to GProxy++ players
// empty actions are used to extend the time a player can use when reconnecting
for( unsigned char j = 0; j < m_GProxyEmptyActions; ++j )
(*i)->AddLoadInGameData( m_Protocol->SEND_W3GS_INCOMING_ACTION( queue<CIncomingAction *>( ), 0 ) );
}