forked from spring/spring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameServer.cpp
More file actions
3022 lines (2446 loc) · 93.8 KB
/
GameServer.cpp
File metadata and controls
3022 lines (2446 loc) · 93.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "System/Net/UDPListener.h"
#include "System/Net/UDPConnection.h"
#include <functional>
#if defined DEDICATED || defined DEBUG
#include <iostream>
#endif
#include "GameServer.h"
#include "GameParticipant.h"
#include "GameSkirmishAI.h"
#include "AutohostInterface.h"
#include "Game/ClientSetup.h"
#include "Game/GameSetup.h"
#include "Game/Action.h"
#include "Game/ChatMessage.h"
#include "Game/CommandMessage.h"
#include "Game/GlobalUnsynced.h" // for syncdebug
#ifndef DEDICATED
#include "Game/IVideoCapturing.h"
#endif
#include "Game/Players/Player.h"
#include "Game/Players/PlayerHandler.h"
#include "Net/Protocol/BaseNetProtocol.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 "System/CRC.h"
#include "System/GlobalConfig.h"
#include "System/MsgStrings.h"
#include "System/SpringMath.h"
#include "System/SpringExitCode.h"
#include "System/SpringFormat.h"
#include "System/TdfParser.h"
#include "System/StringUtil.h"
#include "System/Config/ConfigHandler.h"
#include "System/FileSystem/SimpleParser.h"
#include "System/Net/Connection.h"
#include "System/Net/LocalConnection.h"
#include "System/Net/UnpackPacket.h"
#include "System/LoadSave/DemoRecorder.h"
#include "System/LoadSave/DemoReader.h"
#include "System/Log/ILog.h"
#include "System/Platform/errorhandler.h"
#include "System/Platform/Threading.h"
#include "System/Threading/SpringThreading.h"
#ifndef DEDICATED
#include "lib/luasocket/src/restrictions.h"
#endif
#define ALLOW_DEMO_GODMODE
using netcode::RawPacket;
CONFIG(int, AutohostPort).defaultValue(0);
CONFIG(int, ServerSleepTime).defaultValue(5).description("number of milliseconds to sleep per tick");
CONFIG(int, SpeedControl).defaultValue(1).minimumValue(1).maximumValue(2)
.description("Sets how server adjusts speed according to player's load (CPU), 1: use average, 2: use highest");
CONFIG(bool, AllowSpectatorJoin).defaultValue(true).description("allow any unauthenticated clients to join as spectator with any name, name will be prefixed with ~");
CONFIG(bool, WhiteListAdditionalPlayers).defaultValue(true);
CONFIG(bool, ServerRecordDemos).defaultValue(false).dedicatedValue(true);
CONFIG(bool, ServerLogInfoMessages).defaultValue(false);
CONFIG(bool, ServerLogDebugMessages).defaultValue(false);
CONFIG(std::string, AutohostIP).defaultValue("127.0.0.1");
// use the specific section for all LOG*() calls in this source file
#define LOG_SECTION_GAMESERVER "GameServer"
#ifdef LOG_SECTION_CURRENT
#undef LOG_SECTION_CURRENT
#endif
#define LOG_SECTION_CURRENT LOG_SECTION_GAMESERVER
LOG_REGISTER_SECTION_GLOBAL(LOG_SECTION_GAMESERVER)
/// frames until a synccheck will time out and a warning is given out
static constexpr unsigned SYNCCHECK_TIMEOUT = 300;
/// used to prevent msg spam
static constexpr unsigned SYNCCHECK_MSG_TIMEOUT = 400;
/// The time interval in msec for sending player statistics to each client
static const spring_time playerInfoTime = spring_secs(2);
/// every n'th frame will be a keyframe (and contain the server's framenumber)
static constexpr unsigned serverKeyframeInterval = 16;
/// players incoming bandwidth new allowance every X milliseconds
static constexpr unsigned playerBandwidthInterval = 100;
/// every 10 sec we'll broadcast current frame in a message that skips queue & cache
/// to let clients that are fast-forwarding to current point to know their loading %
static constexpr unsigned gameProgressFrameInterval = GAME_SPEED * 10;
static constexpr unsigned syncResponseEchoInterval = GAME_SPEED * 2;
//FIXME remodularize server commands, so they get registered in word completion etc.
static const std::array<std::string, 23> SERVER_COMMANDS = {
"kick", "kickbynum",
"mute", "mutebynum",
"setminspeed", "setmaxspeed",
"nopause", "nohelp", "cheat", "godmode", "globallos",
"nocost", "forcestart", "nospectatorchat", "nospecdraw",
"skip", "reloadcob", "reloadcegs", "devlua", "editdefs",
"singlestep", "spec", "specbynum"
};
std::array<std::string, 23> CGameServer::commandBlacklist = SERVER_COMMANDS;
CGameServer* gameServer = nullptr;
CGameServer::CGameServer(
const std::shared_ptr<const ClientSetup> newClientSetup,
const std::shared_ptr<const GameData> newGameData,
const std::shared_ptr<const CGameSetup> newGameSetup
)
: serverFrameNum(-1)
, serverStartTime(spring_gettime())
, readyTime(spring_notime)
, gameEndTime(spring_notime)
, lastPlayerInfo(serverStartTime)
, lastUpdate(serverStartTime)
, modGameTime(0.0f)
, gameTime(0.0f)
, startTime(0.0f)
, frameTimeLeft(0.0f)
, isPaused(false)
, gamePausable(true)
, userSpeedFactor(1.0f)
, internalSpeed(1.0f)
, medianCpu(0.0f)
, medianPing(0)
, cheating(false)
, noHelperAIs(false)
, canReconnect(false)
, allowSpecDraw(true)
, syncErrorFrame(0)
, syncWarningFrame(0)
, localClientNumber(-1u)
, gameHasStarted(false)
, generatedGameID(false)
, reloadingServer(false)
, quitServer(false)
{
myClientSetup = newClientSetup;
myGameData = newGameData;
myGameSetup = newGameSetup;
Initialize();
}
CGameServer::~CGameServer()
{
quitServer = true;
LOG_L(L_INFO, "[%s][1]", __FUNCTION__);
thread.join();
LOG_L(L_INFO, "[%s][2]", __FUNCTION__);
// after this, demoRecorder goes out of scope and its dtor is called
WriteDemoData();
}
void CGameServer::Initialize()
{
// configs
curSpeedCtrl = configHandler->GetInt("SpeedControl");
allowSpecJoin = configHandler->GetBool("AllowSpectatorJoin") || myGameSetup->onlyLocal; ///!!! mantis #4418
whiteListAdditionalPlayers = configHandler->GetBool("WhiteListAdditionalPlayers");
logInfoMessages = configHandler->GetBool("ServerLogInfoMessages");
logDebugMessages = configHandler->GetBool("ServerLogDebugMessages");
rng.Seed((myGameData->GetSetupText()).length());
// start network
if (!myGameSetup->onlyLocal)
UDPNet.reset(new netcode::UDPListener(myClientSetup->hostPort, myClientSetup->hostIP));
AddAutohostInterface(StringToLower(configHandler->GetString("AutohostIP")), configHandler->GetInt("AutohostPort"));
Message(spring::format(ServerStart, myClientSetup->hostPort), false);
// start script
maxUserSpeed = myGameSetup->maxSpeed;
minUserSpeed = myGameSetup->minSpeed;
noHelperAIs = myGameSetup->noHelperAIs;
StripGameSetupText(myGameData.get());
// load demo (if there is one)
if (myGameSetup->hostDemo) {
Message(spring::format(PlayingDemo, myGameSetup->demoName.c_str()));
demoReader.reset(new CDemoReader(myGameSetup->demoName, modGameTime + 0.1f));
}
// initialize players, teams & ais
{
pingTimeFilter.fill(spring_notime);
clientDrawFilter.fill({spring_notime, 0});
clientMuteFilter.fill({false, false});
const std::vector<PlayerBase>& playerStartData = myGameSetup->GetPlayerStartingDataCont();
const std::vector<TeamBase>& teamStartData = myGameSetup->GetTeamStartingDataCont();
const std::vector<SkirmishAIData>& aiStartData = myGameSetup->GetAIStartingDataCont();
players.reserve(MAX_PLAYERS); // no reallocation please
teams.resize(teamStartData.size());
players.resize(playerStartData.size());
if (demoReader != nullptr) {
const size_t demoPlayers = demoReader->GetFileHeader().numPlayers;
players.resize(std::max(demoPlayers, playerStartData.size()));
if (players.size() >= MAX_PLAYERS) {
Message(spring::format("Too many Players (%d) in the demo", players.size()));
}
}
std::copy(playerStartData.begin(), playerStartData.end(), players.begin());
std::copy(teamStartData.begin(), teamStartData.end(), teams.begin());
//FIXME move playerID to PlayerBase, so it gets copied from playerStartData
for (size_t n = 0; n < players.size(); n++)
players[n].id = n;
skirmishAIs.clear();
skirmishAIs.resize(MAX_AIS, {false, {}});
freeSkirmishAIs.clear();
freeSkirmishAIs.resize(MAX_AIS, 0);
std::for_each(freeSkirmishAIs.begin(), freeSkirmishAIs.end(), [&](const uint8_t& id) { freeSkirmishAIs[&id - &freeSkirmishAIs[0]] = &id - &freeSkirmishAIs[0]; });
std::reverse(freeSkirmishAIs.begin(), freeSkirmishAIs.end());
for (const SkirmishAIData& skd: aiStartData) {
const uint8_t skirmishAIId = ReserveSkirmishAIId();
if (skirmishAIId == MAX_AIS) {
Message(spring::format("Too many AIs (%d) specified in game-setup script", aiStartData.size()));
break;
}
players[skd.hostPlayer].aiClientLinks[skirmishAIId] = {};
skirmishAIs[skirmishAIId] = std::make_pair(true, skd);
teams[skd.team].SetActive(true);
if (!teams[skd.team].HasLeader())
teams[skd.team].SetLeader(skd.hostPlayer);
}
}
{
// std::copy(SERVER_COMMANDS.begin(), SERVER_COMMANDS.end(), commandBlacklist.begin());
std::sort(commandBlacklist.begin(), commandBlacklist.end());
}
if (configHandler->GetBool("ServerRecordDemos")) {
demoRecorder.reset(new CDemoRecorder(myGameSetup->mapName, myGameSetup->modName, true));
demoRecorder->WriteSetupText(myGameData->GetSetupText());
const netcode::RawPacket* ret = myGameData->Pack();
demoRecorder->SaveToDemo(ret->data, ret->length, GetDemoTime());
delete ret;
}
loopSleepTime = configHandler->GetInt("ServerSleepTime");
lastNewFrameTick = spring_gettime();
linkMinPacketSize = globalConfig.linkIncomingMaxPacketRate > 0 ? (globalConfig.linkIncomingSustainedBandwidth / globalConfig.linkIncomingMaxPacketRate) : 1;
lastBandwidthUpdate = spring_gettime();
thread = std::move(spring::thread(std::bind(&CGameServer::UpdateLoop, this)));
// Something in CGameServer::CGameServer borks the FPU control word
// maybe the threading, or something in CNet::InitServer() ??
// Set single precision floating point math.
streflop::streflop_init<streflop::Simple>();
if (!demoReader) {
GenerateAndSendGameID();
rng.Seed(gameID.intArray[0] ^ gameID.intArray[1] ^ gameID.intArray[2] ^ gameID.intArray[3]);
Broadcast(CBaseNetProtocol::Get().SendRandSeed(rng()));
}
}
void CGameServer::PostLoad(int newServerFrameNum)
{
std::lock_guard<spring::recursive_mutex> scoped_lock(gameServerMutex);
serverFrameNum = newServerFrameNum;
gameHasStarted = !PreSimFrame();
// for all GameParticipant's
for (GameParticipant& p: players) {
p.lastFrameResponse = newServerFrameNum;
}
}
void CGameServer::Reload(const std::shared_ptr<const CGameSetup> newGameSetup)
{
const std::shared_ptr<const ClientSetup> clientSetup = gameServer->GetClientSetup();
const std::shared_ptr<const GameData> gameData = gameServer->GetGameData();
delete gameServer;
// transfer ownership to new instance (assume only GameSetup changes)
gameServer = new CGameServer(clientSetup, gameData, newGameSetup);
}
void CGameServer::WriteDemoData()
{
if (demoRecorder == nullptr)
return;
// there is always at least one non-Gaia team (numTeams > 0)
// the Gaia team itself does not count toward the statistics
demoRecorder->SetTime(serverFrameNum / GAME_SPEED, spring_tomsecs(spring_gettime() - serverStartTime) / 1000);
demoRecorder->InitializeStats(players.size(), int((myGameSetup->GetTeamStartingDataCont()).size()) - myGameSetup->useLuaGaia);
// Pass the winners to the CDemoRecorder.
demoRecorder->SetWinningAllyTeams(winningAllyTeams);
for (GameParticipant& p: players) {
demoRecorder->SetPlayerStats(p.id, p.lastStats);
}
/*
// TODO?
for (size_t i = 0; i < skirmishAIs.size(); ++i) {
if (!skirmishAIs[i].first)
continue;
demoRecorder->SetSkirmishAIStats(i, skirmishAIs[i].second.lastStats);
}
for (int i = 0; i < numTeams; ++i) {
record->SetTeamStats(i, teamHandler.Team(i)->statHistory);
}
*/
}
void CGameServer::StripGameSetupText(const GameData* newGameData)
{
// modify and save GameSetup text (remove passwords)
TdfParser parser((newGameData->GetSetupText()).c_str(), (newGameData->GetSetupText()).length());
TdfParser::TdfSection* rootSec = parser.GetRootSection()->sections["game"];
for (const auto& item: rootSec->sections) {
const std::string& sectionKey = StringToLower(item.first);
if (!StringStartsWith(sectionKey, "player"))
continue;
TdfParser::TdfSection* playerSec = item.second;
playerSec->remove("password", false);
}
std::ostringstream strbuf;
parser.print(strbuf);
GameData* modGameData = new GameData(*newGameData);
modGameData->SetSetupText(strbuf.str());
myGameData.reset(modGameData);
}
void CGameServer::AddLocalClient(const std::string& myName, const std::string& myVersion, const std::string& myPlatform)
{
std::lock_guard<spring::recursive_mutex> scoped_lock(gameServerMutex);
assert(!HasLocalClient());
localClientNumber = BindConnection(std::shared_ptr<netcode::CConnection>(new netcode::CLocalConnection()), myName, "", myVersion, myPlatform, true);
}
void CGameServer::AddAutohostInterface(const std::string& autohostIP, const int autohostPort)
{
if (autohostPort <= 0)
return;
if (autohostIP == "localhost") {
LOG_L(L_ERROR, "Autohost IP address not in x.y.z.w format!");
return;
}
#ifndef DEDICATED
// disallow luasockets access to autohost interface
luaSocketRestrictions->addRule(CLuaSocketRestrictions::UDP_CONNECT, autohostIP, autohostPort, false);
#endif
if (!hostif) {
hostif.reset(new AutohostInterface(autohostIP, autohostPort));
if (hostif->IsInitialized()) {
hostif->SendStart();
Message(spring::format(ConnectAutohost, autohostPort), false);
} else {
// Quit if we are instructed to communicate with an auto-host,
// but are unable to do so: we do not want an auto-host running
// a spring game that it has no control over. If we get here,
// it suggests a configuration problem in the auto-host.
hostif.reset();
Message(spring::format(ConnectAutohostFailed, autohostIP.c_str(), autohostPort), false);
quitServer = true;
}
}
}
void CGameServer::SkipTo(int targetFrameNum)
{
const bool wasPaused = isPaused;
if (!gameHasStarted) { return; }
if (serverFrameNum >= targetFrameNum) { return; }
if (demoReader == nullptr) { return; }
CommandMessage startMsg(spring::format("skip start %d", targetFrameNum), SERVER_PLAYER);
CommandMessage endMsg("skip end", SERVER_PLAYER);
Broadcast(std::shared_ptr<const netcode::RawPacket>(startMsg.Pack()));
// fast-read and send demo data
//
// note that we must maintain <modGameTime> ourselves
// since we do we NOT go through ::Update when skipping
while (SendDemoData(targetFrameNum)) {
gameTime = GetDemoTime();
modGameTime = demoReader->GetModGameTime() + 0.001f;
if (UDPNet == nullptr) { continue; }
if ((serverFrameNum % 20) != 0) { continue; }
// send data every few frames, as otherwise packets would grow too big
UDPNet->Update();
}
Broadcast(std::shared_ptr<const netcode::RawPacket>(endMsg.Pack()));
if (UDPNet) {
UDPNet->Update();
}
lastUpdate = spring_gettime();
isPaused = wasPaused;
}
std::string CGameServer::GetPlayerNames(const std::vector<int>& indices) const
{
std::string playerstring;
for (int id: indices) {
if (!playerstring.empty())
playerstring += ", ";
playerstring += players[id].name;
}
return playerstring;
}
bool CGameServer::SendDemoData(int targetFrameNum)
{
bool ret = false;
netcode::RawPacket* buf = nullptr;
// if we reached EOS before, demoReader has become NULL
if (demoReader == nullptr)
return ret;
// get all packets from the stream up to <modGameTime>
while ((buf = demoReader->GetData(modGameTime))) {
std::shared_ptr<const RawPacket> rpkt(buf);
if (buf->length <= 0) {
Message("Warning: Discarding zero size packet in demo");
continue;
}
const unsigned msgCode = buf->data[0];
switch (msgCode) {
case NETMSG_NEWFRAME:
case NETMSG_KEYFRAME: {
// we can't use CreateNewFrame() here
lastNewFrameTick = spring_gettime();
serverFrameNum++;
#ifdef SYNCCHECK
if (targetFrameNum == -1) {
// not skipping
outstandingSyncFrames.insert(serverFrameNum);
}
CheckSync();
#endif
Broadcast(rpkt);
break;
}
case NETMSG_CREATE_NEWPLAYER: {
try {
netcode::UnpackPacket pckt(rpkt, 3);
unsigned char spectator, team, playerNum;
std::string name;
pckt >> playerNum;
pckt >> spectator;
pckt >> team;
pckt >> name;
AddAdditionalUser(name, "", true, (bool)spectator, (int)team, playerNum); // even though this is a demo, keep the players vector properly updated
} catch (const netcode::UnpackPacketException& ex) {
Message(spring::format("Warning: Discarding invalid new player packet in demo: %s", ex.what()));
continue;
}
Broadcast(rpkt);
break;
}
case NETMSG_GAMEDATA:
case NETMSG_SETPLAYERNUM:
case NETMSG_USER_SPEED:
case NETMSG_INTERNAL_SPEED: {
// never send these from demos
break;
}
case NETMSG_CCOMMAND: {
try {
CommandMessage msg(rpkt);
const Action& action = msg.GetAction();
if (msg.GetPlayerID() == SERVER_PLAYER && action.command == "cheat")
InverseOrSetBool(cheating, action.extra);
} catch (const netcode::UnpackPacketException& ex) {
Message(spring::format("Warning: Discarding invalid command message packet in demo: %s", ex.what()));
continue;
}
Broadcast(rpkt);
break;
}
default: {
Broadcast(rpkt);
break;
}
}
}
if (targetFrameNum > 0) {
// skipping
ret = (serverFrameNum < targetFrameNum);
}
if (demoReader->ReachedEnd()) {
demoReader.reset();
Message(DemoEnd);
gameEndTime = spring_gettime();
ret = false;
}
return ret;
}
void CGameServer::Broadcast(std::shared_ptr<const netcode::RawPacket> packet)
{
for (GameParticipant& p: players) {
p.SendData(packet);
}
if (canReconnect || allowSpecJoin || !gameHasStarted)
packetCache.push_back(packet);
if (demoRecorder != nullptr)
demoRecorder->SaveToDemo(packet->data, packet->length, GetDemoTime());
}
void CGameServer::Message(const std::string& message, bool broadcast, bool internal)
{
if (!internal) {
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 != nullptr)
hostif->Message(message);
}
#ifdef DEDICATED
LOG("%s", message.c_str());
#endif
}
void CGameServer::PrivateMessage(int playerNum, const std::string& message) {
players[playerNum].SendData(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, message));
}
void CGameServer::CheckSync()
{
#ifdef SYNCCHECK
std::vector< std::pair<unsigned, unsigned> > checksums; // <response checkum, #clients matching checksum>
std::vector<int> noSyncResponsePlayers;
std::map<unsigned, std::vector<int> > desyncGroups; // <desync-checksum, [desynced players]>
std::map<int, unsigned> desyncSpecs; // <playerNum, desync-checksum>
auto outstandingSyncFrameIt = outstandingSyncFrames.begin();
while (outstandingSyncFrameIt != outstandingSyncFrames.end()) {
const unsigned outstandingSyncFrame = *outstandingSyncFrameIt;
unsigned correctChecksum = 0;
// maximum number of matched checksums
unsigned maxChecksumCount = 0;
bool haveCorrectChecksum = false;
bool completeResponseSet = true;
if (HasLocalClient()) {
// dictatorship; all player checksums must match the local client's for this frame
const auto it = players[localClientNumber].syncResponse.find(outstandingSyncFrame);
if (it != players[localClientNumber].syncResponse.end()) {
correctChecksum = it->second;
haveCorrectChecksum = true;
}
} else {
// democracy; use the checksum that most players agree on as baseline
checksums.clear();
checksums.reserve(players.size());
for (const GameParticipant& p: players) {
if (p.clientLink == nullptr)
continue;
const auto pChecksumIt = p.syncResponse.find(outstandingSyncFrame);
if (pChecksumIt == p.syncResponse.end())
continue;
const unsigned pChecksum = pChecksumIt->second;
// const unsigned cChecksum = checksums[0].first;
bool checksumFound = false;
// compare player <p>'s sync-response checksum for the
// outstanding frame to all others we have seen so far
for (auto& checksumPair: checksums) {
const unsigned cChecksum = checksumPair.first;
unsigned& cChecksumCount = checksumPair.second;
if (cChecksum != pChecksum)
continue;
checksumFound = true;
if (maxChecksumCount < (++cChecksumCount)) {
maxChecksumCount = cChecksumCount;
correctChecksum = cChecksum;
}
}
if (checksumFound)
continue;
// first time we have seen this checksum
checksums.emplace_back(pChecksum, 1);
if (maxChecksumCount == 0) {
maxChecksumCount = 1;
correctChecksum = pChecksum;
}
}
haveCorrectChecksum = (maxChecksumCount > 0);
}
noSyncResponsePlayers.clear();
noSyncResponsePlayers.reserve(players.size());
desyncGroups.clear();
desyncSpecs.clear();
for (GameParticipant& p: players) {
if (p.clientLink == nullptr)
continue;
const auto pChecksumIt = p.syncResponse.find(outstandingSyncFrame);
if (pChecksumIt == p.syncResponse.end()) {
if (outstandingSyncFrame >= (serverFrameNum - static_cast<int>(SYNCCHECK_TIMEOUT)))
completeResponseSet = false;
else if (outstandingSyncFrame < p.lastFrameResponse)
noSyncResponsePlayers.push_back(p.id);
continue;
}
const unsigned pChecksum = pChecksumIt->second;
if ((p.desynced = (haveCorrectChecksum && pChecksum != correctChecksum))) {
if (demoReader || !p.spectator) {
desyncGroups[pChecksum].push_back(p.id);
} else {
desyncSpecs[p.id] = pChecksum;
}
}
}
// warn about clients that failed to provide a sync-response checksum in time
if (!noSyncResponsePlayers.empty()) {
if (!syncWarningFrame || ((outstandingSyncFrame - syncWarningFrame) > static_cast<int>(SYNCCHECK_MSG_TIMEOUT))) {
syncWarningFrame = outstandingSyncFrame;
const std::string& playerNames = GetPlayerNames(noSyncResponsePlayers);
Message(spring::format(NoSyncResponse, playerNames.c_str(), outstandingSyncFrame));
}
}
// If anything's in it, we have a desync.
// TODO take care of !completeResponseSet case?
// Should we start resync then immediately or wait for the missing packets (while paused)?
if (/*completeResponseSet && */ (!desyncGroups.empty() || !desyncSpecs.empty())) {
if (syncErrorFrame == 0 || (outstandingSyncFrame - syncErrorFrame > static_cast<int>(SYNCCHECK_MSG_TIMEOUT))) {
syncErrorFrame = outstandingSyncFrame;
#ifdef SYNCDEBUG
CSyncDebugger::GetInstance()->ServerTriggerSyncErrorHandling(serverFrameNum);
if (demoReader) // pause is a synced message, thus demo spectators may not pause for real
Message(spring::format("%s paused the demo", players[gu->myPlayerNum].name.c_str()));
else
Broadcast(CBaseNetProtocol::Get().SendPause(gu->myPlayerNum, true));
isPaused = true;
Broadcast(CBaseNetProtocol::Get().SendSdCheckrequest(serverFrameNum));
#endif
#ifndef DEDICATED
// DS exit-codes are not used
spring::exitCode = spring::EXIT_CODE_DESYNC;
#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.
for (const auto& desyncGroup: desyncGroups) {
const std::string& playerNames = GetPlayerNames(desyncGroup.second);
Message(spring::format(SyncError, playerNames.c_str(), outstandingSyncFrame, desyncGroup.first, correctChecksum));
}
// send spectator desyncs as private messages to reduce spam
for (const auto& p: desyncSpecs) {
LOG_L(L_ERROR, "%s", spring::format(SyncError, players[p.first].name.c_str(), outstandingSyncFrame, p.second, correctChecksum).c_str());
Message(spring::format(SyncError, players[p.first].name.c_str(), outstandingSyncFrame, p.second, correctChecksum));
PrivateMessage(p.first, spring::format(SyncError, players[p.first].name.c_str(), outstandingSyncFrame, p.second, correctChecksum));
}
}
}
// Remove complete sets (for which all player's checksums have been received).
if (completeResponseSet) {
for (GameParticipant& p: players) {
if (p.myState < GameParticipant::DISCONNECTED)
p.syncResponse.erase(outstandingSyncFrame);
}
outstandingSyncFrameIt = outstandingSyncFrames.erase(outstandingSyncFrameIt);
continue;
}
++outstandingSyncFrameIt;
}
#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() const {
if (!gameHasStarted) return gameTime;
return (startTime + serverFrameNum / float(GAME_SPEED));
}
void CGameServer::Update()
{
const float tdif = spring_tomsecs(spring_gettime() - lastUpdate) * 0.001f;
gameTime += tdif;
lastUpdate = spring_gettime();
if (!isPaused && gameHasStarted) {
// if we are not playing a demo, or have no local client, or the
// local client is less than <GAME_SPEED> frames behind, advance
// <modGameTime>
if (demoReader == nullptr || !HasLocalClient() || (serverFrameNum - players[localClientNumber].lastFrameResponse) < GAME_SPEED)
modGameTime += (tdif * internalSpeed);
}
if (lastPlayerInfo < (spring_gettime() - playerInfoTime)) {
lastPlayerInfo = spring_gettime();
if (!PreSimFrame()) {
LagProtection();
} else {
for (GameParticipant& p: players) {
if (p.isFromDemo)
continue;
switch (p.myState) {
case GameParticipant::CONNECTED: {
// send pathing status
if (p.cpuUsage > 0)
Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(p.id, p.cpuUsage, PATHING_FLAG));
} break;
case GameParticipant::INGAME:
case GameParticipant::DISCONNECTED: {
Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(p.id, 0, 0)); // reset status
} break;
case GameParticipant::UNCONNECTED:
default: break;
}
}
}
}
if (!gameHasStarted)
CheckForGameStart();
else if (!PreSimFrame() || demoReader != nullptr)
CreateNewFrame(true, false);
if (hostif != nullptr) {
const 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
PushAction(Action(msg.substr(1)), true);
}
}
}
const bool pregameTimeoutReached = (spring_gettime() > (serverStartTime + spring_secs(globalConfig.initialNetworkTimeout)));
const bool canCheckForPlayers = (pregameTimeoutReached || gameHasStarted);
if (canCheckForPlayers) {
bool hasPlayers = false;
for (const GameParticipant& p: players) {
if ((hasPlayers |= (p.clientLink != nullptr)))
break;
}
if ((quitServer = (quitServer || !hasPlayers)))
Message(NoClientsExit);
}
}
void CGameServer::LagProtection()
{
std::vector<float> cpu;
std::vector<int> ping;
cpu.reserve(players.size());
ping.reserve(players.size());
// detect reference cpu usage ( highest )
float refCpuUsage = 0.0f;
for (GameParticipant& player: players) {
if (player.myState == GameParticipant::INGAME) {
// send info about the players
const int curPing = ((serverFrameNum - player.lastFrameResponse) * 1000) / (GAME_SPEED * internalSpeed);
Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(player.id, player.cpuUsage, curPing));
const float playerCpuUsage = player.cpuUsage;
const float correctedCpu = Clamp(playerCpuUsage, 0.0f, 1.0f);
if (player.isReconn && curPing < 2 * GAME_SPEED)
player.isReconn = false;
if ((player.isLocal) || (demoReader ? !player.isFromDemo : !player.spectator)) {
if (!player.isReconn && correctedCpu > refCpuUsage)
refCpuUsage = correctedCpu;
cpu.push_back(correctedCpu);
ping.push_back(curPing);
}
}
}
// calculate median values
medianCpu = 0.0f;
medianPing = 0;
if (curSpeedCtrl == 1 && !cpu.empty()) {
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;
}
refCpuUsage = medianCpu;
}
// adjust game speed
if (refCpuUsage > 0.0f && !isPaused) {
//userSpeedFactor holds the wanted speed adjusted manually by user ( normally 1)
//internalSpeed holds the current speed the sim is running
//refCpuUsage holds the highest cpu if curSpeedCtrl == 0 or median if curSpeedCtrl == 1
// aim for 60% cpu usage if median is used as reference and 75% cpu usage if max is the reference
float wantedCpuUsage = (curSpeedCtrl == 1) ? 0.60f : 0.75f;
//the following line can actually make it go faster than wanted normal speed ( userSpeedFactor )
//if the current cpu of the target is smaller than the aimed cpu target but the clamp will cap it
// the clamp will throttle it to the wanted one, otherwise it's a simple linear proportion aiming
// to keep cpu load constant
float newSpeed = internalSpeed / refCpuUsage * wantedCpuUsage;
newSpeed = Clamp(newSpeed, 0.1f, userSpeedFactor);
//average to smooth the speed change over time to reduce the impact of cpu spikes in the players
newSpeed = (newSpeed + internalSpeed) * 0.5f;
#ifndef DEDICATED
// in non-dedicated hosting, we'll add an additional safeguard to make sure the host can keep up with the game's speed
// adjust game speed to localclient's (:= host) maximum SimFrame rate
const float invSimDrawFract = 1.0f - CGlobalUnsynced::reconnectSimDrawBalance;
const float maxSimFrameRate = (1000.0f / gu->avgSimFrameTime) * invSimDrawFract;
newSpeed = Clamp(newSpeed, 0.1f, ((maxSimFrameRate / GAME_SPEED) + internalSpeed) * 0.5f);
#endif
if (newSpeed != internalSpeed)
InternalSpeedChange(newSpeed);
}
}
/// 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 (const GameParticipant& p: players) {
// do not count spectators, or demos will desync
if (!p.spectator && (p.team == teamId))
playersInTeam.push_back(p.id);
}
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)
{