/
GameServer.cpp
2233 lines (1993 loc) · 71.3 KB
/
GameServer.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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#ifdef _MSC_VER
# include "StdAfx.h"
#elif defined(_WIN32)
# include <windows.h>
#endif
#include "Net/UDPListener.h"
#include "Net/UDPConnection.h"
#include <stdarg.h>
#include <ctime>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/version.hpp>
#include <boost/ptr_container/ptr_deque.hpp>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/shared_ptr.hpp>
#include <deque>
#if defined DEDICATED || defined DEBUG
#include <iostream>
#endif
#include <stdlib.h> // why is this here?
#include "Net/Connection.h"
#include "mmgr.h"
#include "GameServer.h"
#include "LogOutput.h"
#include "GameSetup.h"
#include "Action.h"
#include "ChatMessage.h"
#include "CommandMessage.h"
#include "BaseNetProtocol.h"
#include "PlayerHandler.h"
#include "Net/LocalConnection.h"
#include "Net/UnpackPacket.h"
#include "LoadSave/DemoReader.h"
#ifdef DEDICATED
#include "LoadSave/DemoRecorder.h"
#endif
#include "AutohostInterface.h"
#include "Util.h"
#include "TdfParser.h"
#include "GlobalUnsynced.h" // for syncdebug
#include "Sim/Misc/GlobalConstants.h"
#include "ConfigHandler.h"
#include "FileSystem/CRC.h"
#include "FileSystem/SimpleParser.h"
#include "Player.h"
#include "IVideoCapturing.h"
#include "Server/GameParticipant.h"
#include "Server/GameSkirmishAI.h"
// This undef is needed, as somewhere there is a type interface specified,
// which we need not!
// (would cause problems in ExternalAI/Interface/SAIInterfaceLibrary.h)
#ifdef interface
#undef interface
#endif
#include "Server/MsgStrings.h"
#define PKTCACHE_VECSIZE 1000
using netcode::RawPacket;
/// frames until a syncchech will time out and a warning is given out
const unsigned SYNCCHECK_TIMEOUT = 300;
/// used to prevent msg spam
const unsigned SYNCCHECK_MSG_TIMEOUT = 400;
///msecs to wait until the game starts after all players are ready
const spring_duration gameStartDelay = spring_secs(4);
/// The time intervall in msec for sending player statistics to each client
const spring_duration playerInfoTime = spring_secs(2);
/// every n'th frame will be a keyframe (and contain the server's framenumber)
const unsigned serverKeyframeIntervall = 16;
const std::string commands[numCommands] = {
"kick", "kickbynum", "setminspeed", "setmaxspeed",
"nopause", "nohelp", "cheat", "godmode", "globallos",
"nocost", "forcestart", "nospectatorchat", "nospecdraw",
"skip", "reloadcob", "devlua", "editdefs", "luagaia",
"singlestep"
};
using boost::format;
namespace {
void SetBoolArg(bool& value, const std::string& str)
{
if (str.empty()) { // toggle
value = !value;
}
else { // set
const int num = atoi(str.c_str());
value = (num != 0);
}
}
}
CGameServer* gameServer=0;
CGameServer::CGameServer(int hostport, bool onlyLocal, const GameData* const newGameData, const CGameSetup* const mysetup)
: setup(mysetup)
{
assert(setup);
serverStartTime = spring_gettime();
lastUpdate = serverStartTime;
lastPlayerInfo = serverStartTime;
syncErrorFrame=0;
syncWarningFrame=0;
serverframenum=0;
timeLeft=0;
modGameTime = 0.0f;
gameTime = 0.0f;
startTime = 0.0f;
quitServer=false;
hasLocalClient = false;
localClientNumber = 0;
isPaused = false;
userSpeedFactor = 1.0f;
internalSpeed = 1.0f;
gamePausable = true;
noHelperAIs = false;
allowSpecDraw = true;
cheating = false;
gameHasStarted = false;
gameEndTime = spring_notime;
readyTime = spring_notime;
medianCpu = 0.0f;
medianPing = 0;
// speedControl - throttles speed based on:
// 0 : players (max cpu)
// 1 : players (median cpu)
// 2 : (same as 0)
// -x: same as x, but ignores votes from players that may change the speed control mode
curSpeedCtrl = 0;
speedControl = configHandler->Get("SpeedControl", 0);
UpdateSpeedControl(--speedControl + 1);
allowAdditionalPlayers = configHandler->Get("AllowAdditionalPlayers", false);
whiteListAdditionalPlayers = configHandler->Get("WhiteListAdditionalPlayers", true);
if (!onlyLocal)
UDPNet.reset(new netcode::UDPListener(hostport));
std::string autohostip = configHandler->Get("AutohostIP", std::string("localhost"));
int autohostport = configHandler->Get("AutohostPort", 0);
if (autohostport > 0)
AddAutohostInterface(autohostip, autohostport);
rng.Seed(newGameData->GetSetup().length());
Message(str(format(ServerStart) %hostport), false);
lastTick = spring_gettime();
maxUserSpeed = setup->maxSpeed;
minUserSpeed = setup->minSpeed;
noHelperAIs = (bool)setup->noHelperAIs;
{ // modify and save GameSetup text (remove passwords)
TdfParser parser(newGameData->GetSetup().c_str(), newGameData->GetSetup().length());
TdfParser::TdfSection* root = parser.GetRootSection();
for (TdfParser::TdfSection::sectionsMap::iterator it = root->sections.begin(); it != root->sections.end(); ++it) {
if (it->first.substr(0, 6) == "PLAYER")
it->second->remove("Password");
}
std::ostringstream strbuf;
parser.print(strbuf);
std::string cleanedSetupText = strbuf.str();
GameData* newData = new GameData(*newGameData);
newData->SetSetup(cleanedSetupText);
gameData.reset(newData);
}
if (setup->hostDemo) {
Message(str(format(PlayingDemo) %setup->demoName));
demoReader.reset(new CDemoReader(setup->demoName, modGameTime + 0.1f));
}
players.resize(setup->playerStartingData.size());
std::copy(setup->playerStartingData.begin(), setup->playerStartingData.end(), players.begin());
UpdatePlayerNumberMap();
for (size_t a = 0; a < setup->GetSkirmishAIs().size(); ++a) {
const size_t skirmishAIId = ReserveNextAvailableSkirmishAIId();
ais[skirmishAIId] = setup->GetSkirmishAIs()[a];
}
teams.resize(setup->teamStartingData.size());
std::copy(setup->teamStartingData.begin(), setup->teamStartingData.end(), teams.begin());
commandBlacklist = std::set<std::string>(commands, commands+numCommands);
#ifdef DEDICATED
demoRecorder.reset(new CDemoRecorder());
demoRecorder->SetName(setup->mapName, setup->modName);
demoRecorder->WriteSetupText(gameData->GetSetup());
const netcode::RawPacket* ret = gameData->Pack();
demoRecorder->SaveToDemo(ret->data, ret->length, GetDemoTime());
delete ret;
#endif
// AIs do not join in here, so just set their teams as active
for (std::map<size_t, GameSkirmishAI>::const_iterator ai = ais.begin(); ai != ais.end(); ++ai) {
const int t = ai->second.team;
teams[t].active = true;
if (teams[t].leader < 0) { // CAUTION, default value is 0, not -1
teams[t].leader = ai->second.hostPlayer;
}
}
canReconnect = false;
thread = new boost::thread(boost::bind<void, CGameServer, CGameServer*>(&CGameServer::UpdateLoop, this));
#ifdef STREFLOP_H
// Something in CGameServer::CGameServer borks the FPU control word
// maybe the threading, or something in CNet::InitServer() ??
// Set single precision floating point math.
streflop_init<streflop::Simple>();
#endif
}
CGameServer::~CGameServer()
{
quitServer=true;
thread->join();
delete thread;
#ifdef DEDICATED
// TODO: move this to a method in CTeamHandler
int numTeams = (int)setup->teamStartingData.size();
if (setup->useLuaGaia)
--numTeams;
demoRecorder->SetTime(serverframenum / 30, spring_tomsecs(spring_gettime()-serverStartTime)/1000);
demoRecorder->InitializeStats(players.size(), numTeams);
// Pass the winners to the CDemoRecorder.
demoRecorder->SetWinningAllyTeams(winningAllyTeams);
for (size_t i = 0; i < players.size(); ++i) {
demoRecorder->SetPlayerStats(i, players[i].lastStats);
}
/*for (size_t i = 0; i < ais.size(); ++i) {
demoRecorder->SetSkirmishAIStats(i, ais[i].lastStats);
}*/
/*for (int i = 0; i < numTeams; ++i) {
record->SetTeamStats(i, teamHandler->Team(i)->statHistory);
}*/ //TODO add
#endif // DEDICATED
}
void CGameServer::AddLocalClient(const std::string& myName, const std::string& myVersion)
{
boost::recursive_mutex::scoped_lock scoped_lock(gameServerMutex);
assert(!hasLocalClient);
hasLocalClient = true;
localClientNumber = BindConnection(myName, "", myVersion, true, boost::shared_ptr<netcode::CConnection>(new netcode::CLocalConnection()));
}
void CGameServer::AddAutohostInterface(const std::string& autohostip, const int remotePort)
{
if (!hostif) {
hostif.reset(new AutohostInterface(autohostip, remotePort));
hostif->SendStart();
Message(str(format(ConnectAutohost) %remotePort), false);
}
}
void CGameServer::PostLoad(unsigned newlastTick, int newserverframenum)
{
boost::recursive_mutex::scoped_lock scoped_lock(gameServerMutex);
#if SPRING_TIME
lastTick = newlastTick;
#else
//lastTick = boost::some_time; FIXME
#endif
serverframenum = newserverframenum;
std::vector<GameParticipant>::iterator it;
for (it = players.begin(); it != players.end(); ++it) {
it->lastFrameResponse = newserverframenum;
}
}
void CGameServer::SkipTo(int targetframe)
{
const bool wasPaused = isPaused;
if ((serverframenum < targetframe) && demoReader) {
CommandMessage msg(str(boost::format("skip start %d") %targetframe), SERVER_PLAYER);
Broadcast(boost::shared_ptr<const netcode::RawPacket>(msg.Pack()));
// fast-read and send demo data
// if SendDemoData reaches EOS, demoReader becomes NULL
while ((serverframenum < targetframe) && demoReader) {
float toSkipSecs = 0.1f; // ~ 3 frames
if ((targetframe - serverframenum) < 10) {
// we only want to advance one frame at most, so
// the next time-index must be "close enough" not
// to move past more than 1 NETMSG_NEWFRAME
toSkipSecs = (1.0f / (GAME_SPEED * 2)); // 1 frame
}
// skip time
gameTime += toSkipSecs;
modGameTime += toSkipSecs;
SendDemoData(true);
if (((serverframenum % 20) == 0) && UDPNet) {
// send data every few frames, as otherwise packets would grow too big
UDPNet->Update();
}
}
CommandMessage msg2("skip end", SERVER_PLAYER);
Broadcast(boost::shared_ptr<const netcode::RawPacket>(msg2.Pack()));
if (UDPNet)
UDPNet->Update();
lastUpdate = spring_gettime();
}
// note: unnecessary, pause-commands from
// demos are not broadcast anyway so /skip
// cannot change the state
isPaused = wasPaused;
}
std::string CGameServer::GetPlayerNames(const std::vector<int>& indices) const
{
std::string playerstring;
std::vector<int>::const_iterator p = indices.begin();
for (; p != indices.end(); ++p) {
if (!playerstring.empty())
playerstring += ", ";
playerstring += players[*p].name;
}
return playerstring;
}
void CGameServer::UpdatePlayerNumberMap() {
unsigned char player = 0;
for (int i = 0; i < 256; ++i, ++player) {
if (i < players.size() && !players[i].isFromDemo)
++player;
playerNumberMap[i] = (i < 250) ? player : i; // ignore SERVER_PLAYER, ChatMessage::TO_XXX etc
}
}
void CGameServer::AdjustPlayerNumber(const unsigned char msg, unsigned char &player) {
// spectators watching the demo will offset the demo spectators, compensate for this
player = playerNumberMap[player];
if (player >= players.size() && player < 250) // ignore SERVER_PLAYER, ChatMessage::TO_XXX etc
Message(str(format("Warning: Invalid player number in demo msg id %d") %(int)msg));
}
void CGameServer::SendDemoData(const bool skipping)
{
netcode::RawPacket* buf = 0;
while ((buf = demoReader->GetData(modGameTime))) {
unsigned msgCode = buf->data[0];
switch (msgCode) {
case NETMSG_NEWFRAME:
case NETMSG_KEYFRAME: {
// we can't use CreateNewFrame() here
lastTick = spring_gettime();
serverframenum++;
#ifdef SYNCCHECK
if (!skipping)
outstandingSyncFrames.push_back(serverframenum);
CheckSync();
#endif
Broadcast(boost::shared_ptr<const RawPacket>(buf));
break;
}
case NETMSG_AI_STATE_CHANGED: /* many of these messages are not likely to be sent by a spec, but there are cheats */
case NETMSG_ALLIANCE:
case NETMSG_CUSTOM_DATA:
case NETMSG_DC_UPDATE:
case NETMSG_DIRECT_CONTROL:
case NETMSG_PATH_CHECKSUM:
case NETMSG_PAUSE: /* this is a synced message and must not be excluded */
case NETMSG_PLAYERINFO:
case NETMSG_PLAYERLEFT:
case NETMSG_PLAYERSTAT:
case NETMSG_SETSHARE:
case NETMSG_SHARE:
case NETMSG_STARTPOS:
case NETMSG_REGISTER_NETMSG:
case NETMSG_TEAM:
case NETMSG_UNREGISTER_NETMSG: {
// TODO: more messages may need adjusted player numbers, or maybe there is a better solution
AdjustPlayerNumber(msgCode, buf->data[1]);
Broadcast(boost::shared_ptr<const RawPacket>(buf));
break;
}
case NETMSG_AI_CREATED:
case NETMSG_MAPDRAW:
case NETMSG_PLAYERNAME: {
AdjustPlayerNumber(msgCode, buf->data[2]);
Broadcast(boost::shared_ptr<const RawPacket>(buf));
break;
}
case NETMSG_CHAT: {
AdjustPlayerNumber(msgCode, buf->data[2]);
AdjustPlayerNumber(msgCode, buf->data[3]);
Broadcast(boost::shared_ptr<const RawPacket>(buf));
break;
}
case NETMSG_AICOMMAND:
case NETMSG_AISHARE:
case NETMSG_COMMAND:
case NETMSG_LUAMSG:
case NETMSG_SELECT:
case NETMSG_SYSTEMMSG: {
AdjustPlayerNumber(msgCode, buf->data[3]);
Broadcast(boost::shared_ptr<const RawPacket>(buf));
break;
}
case NETMSG_CREATE_NEWPLAYER: {
buf->data[3] = players.size();
try {
netcode::UnpackPacket pckt(boost::shared_ptr<const RawPacket>(buf), 3);
unsigned char spectator, team, playerNum;
std::string name;
pckt >> playerNum;
pckt >> spectator;
pckt >> team;
pckt >> name;
AddAdditionalUser(name, "", true); // even though this is a demo, keep the players vector properly updated
} catch (netcode::UnpackPacketException &e) {
logOutput.Print("Warning: Invalid new player in demo msg: %s", e.err.c_str());
}
Broadcast(boost::shared_ptr<const RawPacket>(buf));
break;
}
case NETMSG_GAMEDATA:
case NETMSG_SETPLAYERNUM:
case NETMSG_USER_SPEED:
case NETMSG_INTERNAL_SPEED: {
// dont send these from demo
break;
}
default: {
Broadcast(boost::shared_ptr<const RawPacket>(buf));
break;
}
}
}
if (demoReader->ReachedEnd()) {
demoReader.reset();
Message(DemoEnd);
gameEndTime = spring_gettime();
}
}
void CGameServer::Broadcast(boost::shared_ptr<const netcode::RawPacket> packet)
{
for (size_t p = 0; p < players.size(); ++p)
players[p].SendData(packet);
if (canReconnect || allowAdditionalPlayers || !gameHasStarted)
AddToPacketCache(packet);
#ifdef DEDICATED
if (demoRecorder)
demoRecorder->SaveToDemo(packet->data, packet->length, GetDemoTime());
#endif
}
void CGameServer::Message(const std::string& message, bool broadcast)
{
if (broadcast) {
Broadcast(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, message));
}
else if (hasLocalClient) {
// host should see
players[localClientNumber].SendData(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, message));
}
if (hostif)
hostif->Message(message);
#if defined DEDICATED
std::cout << message << std::endl;
#endif
}
void CGameServer::PrivateMessage(int playernum, const std::string& message) {
players[playernum].SendData(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, message));
}
void CGameServer::CheckSync()
{
#ifdef SYNCCHECK
// Check sync
std::deque<int>::iterator f = outstandingSyncFrames.begin();
while (f != outstandingSyncFrames.end()) {
unsigned correctChecksum = 0;
bool bGotCorrectChecksum = false;
if (hasLocalClient) {
// dictatorship
std::map<int, unsigned>::iterator it = players[localClientNumber].syncResponse.find(*f);
if (it != players[localClientNumber].syncResponse.end()) {
correctChecksum = it->second;
bGotCorrectChecksum = true;
}
}
else {
// democracy
typedef std::vector< std::pair<unsigned, unsigned> > chkList;
chkList checksums;
unsigned checkMaxCount = 0;
for (size_t a = 0; a < players.size(); ++a) {
if (!players[a].link)
continue;
std::map<int, unsigned>::const_iterator it = players[a].syncResponse.find(*f);
if (it != players[a].syncResponse.end()) {
bool found = false;
for (chkList::iterator it2 = checksums.begin(); it2 != checksums.end(); ++it2) {
if (it2->first == it->second) {
found = true;
it2->second++;
if (checkMaxCount < it2->second) {
checkMaxCount = it2->second;
correctChecksum = it2->first;
}
}
}
if (!found) {
checksums.push_back(std::pair<unsigned, unsigned>(it->second, 1));
if (checkMaxCount == 0) {
checkMaxCount = 1;
correctChecksum = it->second;
}
}
}
}
bGotCorrectChecksum = (checkMaxCount > 0);
}
std::vector<int> noSyncResponse;
// maps incorrect checksum to players with that checksum
std::map<unsigned, std::vector<int> > desyncGroups;
std::map<int, unsigned> desyncSpecs;
bool bComplete = true;
for (size_t a = 0; a < players.size(); ++a) {
if (!players[a].link) {
continue;
}
std::map<int, unsigned>::iterator it = players[a].syncResponse.find(*f);
if (it == players[a].syncResponse.end()) {
if (*f >= serverframenum - static_cast<int>(SYNCCHECK_TIMEOUT))
bComplete = false;
else if (*f < players[a].lastFrameResponse)
noSyncResponse.push_back(a);
} else {
if (bGotCorrectChecksum && it->second != correctChecksum) {
players[a].desynced = true;
if (demoReader || !players[a].spectator)
desyncGroups[it->second].push_back(a);
else
desyncSpecs[a] = it->second;
}
else
players[a].desynced = false;
}
}
if (!noSyncResponse.empty()) {
if (!syncWarningFrame || (*f - syncWarningFrame > static_cast<int>(SYNCCHECK_MSG_TIMEOUT))) {
syncWarningFrame = *f;
std::string playernames = GetPlayerNames(noSyncResponse);
Message(str(format(NoSyncResponse) %playernames %(*f)));
}
}
// If anything's in it, we have a desync.
// TODO take care of !bComplete case?
// Should we start resync then immediately or wait for the missing packets (while paused)?
if (/*bComplete && */ (!desyncGroups.empty() || !desyncSpecs.empty())) {
if (!syncErrorFrame || (*f - syncErrorFrame > static_cast<int>(SYNCCHECK_MSG_TIMEOUT))) {
syncErrorFrame = *f;
// TODO enable this when we have resync
//serverNet->SendPause(SERVER_PLAYER, true);
#ifdef SYNCDEBUG
CSyncDebugger::GetInstance()->ServerTriggerSyncErrorHandling(serverframenum);
if (demoReader) // pause is a synced message, thus demo spectators may not pause for real
Message(str(format("%s paused the demo") %players[gu->myPlayerNum].name));
else
Broadcast(CBaseNetProtocol::Get().SendPause(gu->myPlayerNum, true));
isPaused = true;
Broadcast(CBaseNetProtocol::Get().SendSdCheckrequest(serverframenum));
#endif
// For each group, output a message with list of player names in it.
// TODO this should be linked to the resync system so it can roundrobin
// the resync checksum request packets to multiple clients in the same group.
std::map<unsigned, std::vector<int> >::const_iterator g = desyncGroups.begin();
for (; g != desyncGroups.end(); ++g) {
std::string playernames = GetPlayerNames(g->second);
Message(str(format(SyncError) %playernames %(*f) %(g->first ^ correctChecksum)));
}
// send spectator desyncs as private messages to reduce spam
for(std::map<int, unsigned>::const_iterator s = desyncSpecs.begin(); s != desyncSpecs.end(); ++s) {
int playernum = s->first;
PrivateMessage(playernum, str(format(SyncError) %players[playernum].name %(*f) %(s->second ^ correctChecksum)));
}
}
}
// Remove complete sets (for which all player's checksums have been received).
if (bComplete) {
// Message(str (boost::format("Succesfully purged outstanding sync frame %d from the deque") %(*f)));
for (size_t a = 0; a < players.size(); ++a) {
if (players[a].myState < GameParticipant::DISCONNECTED)
players[a].syncResponse.erase(*f);
}
f = outstandingSyncFrames.erase(f);
} else
++f;
}
#else
// Make it clear this build isn't suitable for release.
if (!syncErrorFrame || (serverframenum - syncErrorFrame > SYNCCHECK_MSG_TIMEOUT)) {
syncErrorFrame = serverframenum;
Message(NoSyncCheck);
}
#endif
}
float CGameServer::GetDemoTime() {
return !gameHasStarted ? gameTime : startTime + (float)serverframenum / (float)GAME_SPEED;
}
void CGameServer::Update()
{
float tdif = float(spring_tomsecs(spring_gettime() - lastUpdate)) * 0.001f;
gameTime += tdif;
if (!isPaused && gameHasStarted) {
if (!demoReader || !hasLocalClient || (serverframenum - players[localClientNumber].lastFrameResponse) < GAME_SPEED)
modGameTime += tdif * internalSpeed;
}
lastUpdate = spring_gettime();
if (lastPlayerInfo < (spring_gettime() - playerInfoTime)) {
lastPlayerInfo = spring_gettime();
if (serverframenum > 0) {
//send info about the players
std::vector<float> cpu;
std::vector<int> ping;
float refCpu = 0.0f;
for (size_t a = 0; a < players.size(); ++a) {
if (players[a].myState == GameParticipant::INGAME) {
int curPing = (serverframenum - players[a].lastFrameResponse);
if (players[a].isReconn && curPing < 2 * GAME_SPEED)
players[a].isReconn = false;
Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, players[a].cpuUsage, curPing));
float correctedCpu = players[a].isLocal ? players[a].cpuUsage :
std::max(0.0f, std::min(players[a].cpuUsage - 0.0025f * (float)players[a].luaDrawTime, 1.0f));
if (demoReader ? !players[a].isFromDemo : !players[a].spectator) {
if (!players[a].isReconn && correctedCpu > refCpu)
refCpu = correctedCpu;
cpu.push_back(correctedCpu);
ping.push_back(curPing);
}
}
}
medianCpu = 0.0f;
medianPing = 0;
if (curSpeedCtrl > 0 && cpu.size() > 0) {
std::sort(cpu.begin(), cpu.end());
std::sort(ping.begin(), ping.end());
int midpos = cpu.size() / 2;
medianCpu = cpu[midpos];
medianPing = ping[midpos];
if (midpos * 2 == cpu.size()) {
medianCpu = (medianCpu + cpu[midpos - 1]) / 2.0f;
medianPing = (medianPing + ping[midpos - 1]) / 2;
}
refCpu = medianCpu;
}
if (refCpu > 0.0f) {
// aim for 60% cpu usage if median is used as reference and 75% cpu usage if max is the reference
float wantedCpu = (curSpeedCtrl > 0) ? 0.6f + (1 - internalSpeed / userSpeedFactor) * 0.5f : 0.75f + (1 - internalSpeed / userSpeedFactor) * 0.5f;
float newSpeed = internalSpeed * wantedCpu / refCpu;
// float speedMod=1+wantedCpu-refCpu;
// logOutput.Print("Speed REF %f MED %f WANT %f SPEEDM %f NSPEED %f",refCpu,medianCpu,wantedCpu,speedMod,newSpeed);
newSpeed = (newSpeed + internalSpeed) * 0.5f;
newSpeed = std::max(newSpeed, (curSpeedCtrl > 0) ? userSpeedFactor * 0.8f : userSpeedFactor * 0.5f);
if (newSpeed > userSpeedFactor)
newSpeed = userSpeedFactor;
if (newSpeed < 0.1f)
newSpeed = 0.1f;
if (newSpeed != internalSpeed)
InternalSpeedChange(newSpeed);
}
}
else {
for (size_t a = 0; a < players.size(); ++a) {
if (!players[a].isFromDemo) {
if (players[a].myState == GameParticipant::CONNECTED) { // send pathing status
if (players[a].cpuUsage > 0)
Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, players[a].cpuUsage, PATHING_FLAG));
}
else {
Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, 0, 0)); // reset status
}
}
}
}
}
if (!gameHasStarted)
CheckForGameStart();
else if (serverframenum > 0 || demoReader)
CreateNewFrame(true, false);
if (hostif) {
std::string msg = hostif->GetChatMessage();
if (!msg.empty()) {
if (msg.at(0) != '/') { // normal chat message
GotChatMessage(ChatMessage(SERVER_PLAYER, ChatMessage::TO_EVERYONE, msg));
}
else if (msg.at(0) == '/' && msg.size() > 1 && msg.at(1) == '/') { // chatmessage with prefixed '/'
GotChatMessage(ChatMessage(SERVER_PLAYER, ChatMessage::TO_EVERYONE, msg.substr(1)));
}
else if (msg.size() > 1) { // command
Action buf(msg.substr(1));
PushAction(buf);
}
}
}
if (spring_gettime() > serverStartTime + spring_secs(gc->initialNetworkTimeout) || gameHasStarted) {
bool hasPlayers = false;
for (size_t i = 0; i < players.size(); ++i) {
if (players[i].link) {
hasPlayers = true;
break;
}
}
if (!hasPlayers) {
Message(NoClientsExit);
quitServer = true;
}
}
}
/// has to be consistent with Game.cpp/CPlayerHandler
static std::vector<int> getPlayersInTeam(const std::vector<GameParticipant>& players, const int teamId) {
std::vector<int> playersInTeam;
for (size_t p = 0; p < players.size(); ++p) {
// do not count spectators, or demos will desync
if (!players[p].spectator && (players[p].team == teamId))
playersInTeam.push_back(p);
}
return playersInTeam;
}
/**
* Duplicates functionality of CPlayerHandler::ActivePlayersInTeam(int teamId)
* as playerHandler is not available on the server
*/
static int countNumPlayersInTeam(const std::vector<GameParticipant>& players, const int teamId) {
return getPlayersInTeam(players, teamId).size();
}
/// has to be consistent with Game.cpp/CSkirmishAIHandler
static std::vector<size_t> getSkirmishAIIds(const std::map<size_t, GameSkirmishAI>& ais, const int teamId, const int hostPlayer = -2) {
std::vector<size_t> skirmishAIIds;
for (std::map<size_t, GameSkirmishAI>::const_iterator ai = ais.begin(); ai != ais.end(); ++ai) {
if ((ai->second.team == teamId) && ((hostPlayer == -2) || (ai->second.hostPlayer == hostPlayer)))
skirmishAIIds.push_back(ai->first);
}
return skirmishAIIds;
}
/**
* Duplicates functionality of CSkirmishAIHandler::GetSkirmishAIsInTeam(const int teamId)
* as skirmishAIHandler is not available on the server
*/
static int countNumSkirmishAIsInTeam(const std::map<size_t, GameSkirmishAI>& ais, const int teamId) {
return getSkirmishAIIds(ais, teamId).size();
}
void CGameServer::ProcessPacket(const unsigned playernum, boost::shared_ptr<const netcode::RawPacket> packet)
{
const boost::uint8_t* inbuf = packet->data;
const unsigned a = playernum;
unsigned msgCode = (unsigned) inbuf[0];
switch (msgCode) {
case NETMSG_KEYFRAME: {
const int frameNum = *(int*)&inbuf[1];
players[a].lastFrameResponse = frameNum;
break;
}
case NETMSG_PAUSE:
if (inbuf[1] != a) {
Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
break;
}
if (!inbuf[2]) // reset sync checker
syncErrorFrame = 0;
if (gamePausable || players[a].isLocal) { // allow host to pause even if nopause is set
if (!players[a].isLocal && players[a].spectator && !demoReader) {
PrivateMessage(a, "Spectators cannot pause the game");
}
else if (curSpeedCtrl > 0 && !isPaused && !players[a].isLocal &&
(players[a].spectator || (curSpeedCtrl > 0 &&
(players[a].cpuUsage - medianCpu > std::min(0.2f, std::max(0.0f, 0.8f - medianCpu)) ||
(serverframenum - players[a].lastFrameResponse) - medianPing > internalSpeed * GAME_SPEED / 2)))) {
PrivateMessage(a, "Pausing rejected (cpu load or ping is too high)");
}
else {
timeLeft=0;
if ((isPaused != !!inbuf[2]) || demoReader)
isPaused = !isPaused;
if (demoReader) // pause is a synced message, thus demo spectators may not pause for real
Message(str(format("%s %s the demo") %players[a].name %(isPaused ? "paused" : "unpaused")));
else
Broadcast(CBaseNetProtocol::Get().SendPause(a, inbuf[2]));
}
}
break;
case NETMSG_USER_SPEED: {
if (!players[a].isLocal && players[a].spectator && !demoReader) {
PrivateMessage(a, "Spectators cannot change game speed");
}
else {
float speed = *((float*) &inbuf[2]);
UserSpeedChange(speed, a);
}
} break;
case NETMSG_CPU_USAGE:
players[a].cpuUsage = *((float*)&inbuf[1]);
break;
case NETMSG_CUSTOM_DATA: {
unsigned playerNum = inbuf[1];
if (playerNum != a) {
Message(str(format(WrongPlayer) %msgCode %a %playerNum));
break;
}
switch(inbuf[2]) {
case CUSTOM_DATA_SPEEDCONTROL:
players[a].speedControl = *((int*)&inbuf[3]);
UpdateSpeedControl(speedControl);
break;
case CUSTOM_DATA_LUADRAWTIME:
players[a].luaDrawTime = *((int*)&inbuf[3]);
break;
default:
Message(str(format("Player %s sent invalid CustomData type %d") %players[a].name %inbuf[2]));
}
break;
}
case NETMSG_QUIT: {
Message(str(format(PlayerLeft) %players[a].GetType() %players[a].name %" normal quit"));
Broadcast(CBaseNetProtocol::Get().SendPlayerLeft(a, 1));
players[a].Kill("User exited");
UpdateSpeedControl(speedControl);
if (hostif)
hostif->SendPlayerLeft(a, 1);
break;
}
case NETMSG_PLAYERNAME: {
try {
netcode::UnpackPacket pckt(packet, 2);
unsigned char playerNum;
pckt >> playerNum;
if (playerNum != a) {
Message(str(format(WrongPlayer) %msgCode %a %playerNum));
break;
}
pckt >> players[playerNum].name;
players[playerNum].myState = GameParticipant::INGAME;
Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, 0, 0)); // reset pathing display
Message(str(format(PlayerJoined) %players[playerNum].GetType() %players[playerNum].name), false);
Broadcast(CBaseNetProtocol::Get().SendPlayerName(playerNum, players[playerNum].name));
if (hostif)
hostif->SendPlayerJoined(playerNum, players[playerNum].name);
} catch (netcode::UnpackPacketException &e) {
Message(str(format("Player %d sent invalid PlayerName: %s") %a %e.err));
}
break;
}
case NETMSG_PATH_CHECKSUM: {
const unsigned char playerNum = inbuf[1];
const boost::uint32_t playerCheckSum = *(boost::uint32_t*) &inbuf[2];
if (playerNum != a) {
Message(str(format(WrongPlayer) %msgCode %a %playerNum));
break;
}
Broadcast(CBaseNetProtocol::Get().SendPathCheckSum(playerNum, playerCheckSum));
} break;
case NETMSG_CHAT: {
try {
ChatMessage msg(packet);
if (static_cast<unsigned>(msg.fromPlayer) != a) {
Message(str(format(WrongPlayer) %msgCode %a %(unsigned)msg.fromPlayer));
break;
}
GotChatMessage(msg);
} catch (netcode::UnpackPacketException &e) {
Message(str(format("Player %s sent invalid ChatMessage: %s") %players[a].name %e.err));
}
break;
}
case NETMSG_SYSTEMMSG:
try {
netcode::UnpackPacket pckt(packet, 3);
unsigned char playerNum;
pckt >> playerNum;
std::string strmsg;
pckt >> strmsg;
if (playerNum != a) {
Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
break;
}
Broadcast(CBaseNetProtocol::Get().SendSystemMessage(playerNum, strmsg));
} catch (netcode::UnpackPacketException &e) {
Message(str(format("Player %d sent invalid SystemMessage: %s") %a %e.err));
}
break;
case NETMSG_STARTPOS: {
const unsigned player = inbuf[1];
if (player != a) {
Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
break;
}
if (setup->startPosType == CGameSetup::StartPos_ChooseInGame) {
const unsigned team = (unsigned)inbuf[2];
if (team >= teams.size()) {
Message(str(boost::format("Invalid teamID %d in NETMSG_STARTPOS from player %d") %team %player));
} else if (getSkirmishAIIds(ais, team, player).empty() && ((team != players[player].team) || (players[player].spectator))) {
Message(str(boost::format("Player %d sent spoofed NETMSG_STARTPOS with teamID %d") %player %team));
} else {
teams[team].startPos = float3(*((float*)&inbuf[4]), *((float*)&inbuf[8]), *((float*)&inbuf[12]));
if (inbuf[3] == 1) {
players[player].readyToStart = static_cast<bool>(inbuf[3]);
}
Broadcast(CBaseNetProtocol::Get().SendStartPos(inbuf[1],team, inbuf[3], *((float*)&inbuf[4]), *((float*)&inbuf[8]), *((float*)&inbuf[12]))); //forward data
if (hostif)
hostif->SendPlayerReady(a, inbuf[3]);
}
}
else {
Message(str(format(NoStartposChange) %a));
}
break;
}
case NETMSG_COMMAND:
try {
netcode::UnpackPacket pckt(packet, 3);
unsigned char playerNum;
pckt >> playerNum;
if (playerNum != a) {
Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
break;
}
if (!demoReader)
Broadcast(packet); //forward data
} catch (netcode::UnpackPacketException &e) {