• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Return-To-The-Roots / s25client / 15686629494

16 Jun 2025 04:38PM UTC coverage: 50.442% (-0.03%) from 50.467%
15686629494

Pull #1534

github

web-flow
Merge 0307ea36d into 67a057674
Pull Request #1534: Portrait support

58 of 162 new or added lines in 17 files covered. (35.8%)

23 existing lines in 5 files now uncovered.

22502 of 44610 relevant lines covered (50.44%)

33921.51 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

4.58
/libs/s25main/network/GameServer.cpp
1
// Copyright (C) 2005 - 2024 Settlers Freaks (sf-team at siedler25.org)
2
//
3
// SPDX-License-Identifier: GPL-2.0-or-later
4

5
#include "GameServer.h"
6
#include "Debug.h"
7
#include "GameMessage.h"
8
#include "GameMessage_GameCommand.h"
9
#include "GameServerPlayer.h"
10
#include "GlobalGameSettings.h"
11
#include "JoinPlayerInfo.h"
12
#include "RTTR_Version.h"
13
#include "RttrConfig.h"
14
#include "Savegame.h"
15
#include "Settings.h"
16
#include "commonDefines.h"
17
#include "files.h"
18
#include "helpers/containerUtils.h"
19
#include "helpers/mathFuncs.h"
20
#include "helpers/random.h"
21
#include "network/CreateServerInfo.h"
22
#include "network/GameMessages.h"
23
#include "random/randomIO.h"
24
#include "gameTypes/LanGameInfo.h"
25
#include "gameTypes/TeamTypes.h"
26
#include "gameData/GameConsts.h"
27
#include "gameData/LanDiscoveryCfg.h"
28
#include "gameData/MaxPlayers.h"
29
#include "gameData/PortraitConsts.h"
30
#include "liblobby/LobbyClient.h"
31
#include "libsiedler2/ArchivItem_Map.h"
32
#include "libsiedler2/ArchivItem_Map_Header.h"
33
#include "libsiedler2/prototypen.h"
34
#include "s25util/SocketSet.h"
35
#include "s25util/colors.h"
36
#include "s25util/utf8.h"
37
#include <boost/container/static_vector.hpp>
38
#include <boost/filesystem.hpp>
39
#include <boost/nowide/convert.hpp>
40
#include <boost/nowide/fstream.hpp>
41
#include <helpers/chronoIO.h>
42
#include <iomanip>
43
#include <iterator>
44
#include <mygettext/mygettext.h>
45

46
struct GameServer::AsyncLog
47
{
48
    uint8_t playerId;
49
    bool done;
50
    AsyncChecksum checksum;
51
    std::string addData;
52
    std::vector<RandomEntry> randEntries;
53
    AsyncLog(uint8_t playerId, AsyncChecksum checksum) : playerId(playerId), done(false), checksum(checksum) {}
×
54
};
55

56
GameServer::ServerConfig::ServerConfig()
×
57
{
58
    Clear();
×
59
}
×
60

61
void GameServer::ServerConfig::Clear()
×
62
{
63
    servertype = ServerType::Local;
×
64
    gamename.clear();
×
65
    password.clear();
×
66
    port = 0;
×
67
    ipv6 = false;
×
68
}
×
69

70
GameServer::CountDown::CountDown() : isActive(false), remainingSecs(0) {}
×
71

72
void GameServer::CountDown::Start(unsigned timeInSec)
×
73
{
74
    isActive = true;
×
75
    remainingSecs = timeInSec;
×
76
    lasttime = SteadyClock::now();
×
77
}
×
78

79
void GameServer::CountDown::Stop()
×
80
{
81
    isActive = false;
×
82
}
×
83

84
bool GameServer::CountDown::Update()
×
85
{
86
    RTTR_Assert(isActive);
×
87
    SteadyClock::time_point curTime = SteadyClock::now();
×
88

89
    // Check if 1s has passed
90
    if(curTime - lasttime < std::chrono::seconds(1))
×
91
        return false;
×
92
    if(remainingSecs == 0)
×
93
    {
94
        Stop();
×
95
        return true;
×
96
    }
97
    // 1s has passed -> Reduce remaining time
98
    lasttime = curTime;
×
99
    remainingSecs--;
×
100
    return true;
×
101
}
102

UNCOV
103
GameServer::GameServer() : skiptogf(0), state(ServerState::Stopped), currentGF(0), lanAnnouncer(LAN_DISCOVERY_CFG) {}
×
104

UNCOV
105
GameServer::~GameServer()
×
106
{
107
    Stop();
×
108
}
×
109

110
///////////////////////////////////////////////////////////////////////////////
111
// Spiel hosten
112
bool GameServer::Start(const CreateServerInfo& csi, const MapDescription& map, const std::string& hostPw)
×
113
{
114
    Stop();
×
115

116
    // Name, Password und Kartenname kopieren
117
    config.gamename = csi.gameName;
×
118
    config.hostPassword = hostPw;
×
119
    config.password = csi.password;
×
120
    config.servertype = csi.type;
×
121
    config.port = csi.port;
×
122
    config.ipv6 = csi.ipv6;
×
123
    mapinfo.type = map.map_type;
×
124
    mapinfo.filepath = map.map_path;
×
125

126
    // Maps, Random-Maps, Savegames - Header laden und relevante Informationen rausschreiben (Map-Titel, Spieleranzahl)
127
    switch(mapinfo.type)
×
128
    {
129
        // Altes S2-Mapformat von BB
130
        case MapType::OldMap:
×
131
        {
132
            libsiedler2::Archiv map;
×
133

134
            // Karteninformationen laden
135
            if(libsiedler2::loader::LoadMAP(mapinfo.filepath, map, true) != 0)
×
136
            {
137
                LOG.write("GameServer::Start: ERROR: Map %1%, couldn't load header!\n") % mapinfo.filepath;
×
138
                return false;
×
139
            }
140
            const libsiedler2::ArchivItem_Map_Header& header =
141
              checkedCast<const libsiedler2::ArchivItem_Map*>(map.get(0))->getHeader();
×
142

143
            playerInfos.resize(header.getNumPlayers());
×
144
            mapinfo.title = s25util::ansiToUTF8(header.getName());
×
145
            ggs_.LoadSettings();
×
146
            currentGF = 0;
×
147
        }
148
        break;
×
149
        // Gespeichertes Spiel
150
        case MapType::Savegame:
×
151
        {
152
            Savegame save;
×
153

154
            if(!save.Load(mapinfo.filepath, SaveGameDataToLoad::HeaderAndSettings))
×
155
                return false;
×
156

157
            // Spieleranzahl
158
            playerInfos.resize(save.GetNumPlayers());
×
159
            mapinfo.title = save.GetMapName();
×
160

161
            for(unsigned i = 0; i < playerInfos.size(); ++i)
×
162
            {
163
                playerInfos[i] = JoinPlayerInfo(save.GetPlayer(i));
×
164
                // If it was a human we make it free, so someone can join
165
                if(playerInfos[i].ps == PlayerState::Occupied)
×
166
                    playerInfos[i].ps = PlayerState::Free;
×
167
            }
168

169
            ggs_ = save.ggs;
×
170
            currentGF = save.start_gf;
×
171
        }
172
        break;
×
173
    }
174

175
    if(playerInfos.empty())
×
176
    {
177
        LOG.write("Map %1% has no players!\n") % mapinfo.filepath;
×
178
        return false;
×
179
    }
180

181
    if(!mapinfo.mapData.CompressFromFile(mapinfo.filepath, &mapinfo.mapChecksum))
×
182
        return false;
×
183

184
    if(map.lua_path.has_value() && !bfs::is_regular_file(*map.lua_path))
×
185
        return false;
×
186

187
    bfs::path luaFilePath = map.lua_path.get_value_or(bfs::path(mapinfo.filepath).replace_extension("lua"));
×
188
    if(bfs::is_regular_file(luaFilePath))
×
189
    {
190
        if(!mapinfo.luaData.CompressFromFile(luaFilePath, &mapinfo.luaChecksum))
×
191
            return false;
×
192
        mapinfo.luaFilepath = luaFilePath;
×
193
    } else
194
        RTTR_Assert(mapinfo.luaFilepath.empty() && mapinfo.luaChecksum == 0);
×
195

196
    if(!mapinfo.verifySize())
×
197
    {
198
        LOG.write("Map %1% is to large!\n") % mapinfo.filepath;
×
199
        return false;
×
200
    }
201

202
    // ab in die Konfiguration
203
    state = ServerState::Config;
×
204

205
    // und das socket in listen-modus schicken
206
    if(!serversocket.Listen(config.port, config.ipv6, csi.use_upnp))
×
207
    {
208
        LOG.write("GameServer::Start: ERROR: Listening on port %d failed!\n") % config.port;
×
209
        LOG.writeLastError("Fehler");
×
210
        return false;
×
211
    }
212

213
    if(config.servertype == ServerType::LAN)
×
214
        lanAnnouncer.Start();
×
215
    else if(config.servertype == ServerType::Lobby)
×
216
    {
217
        LOBBYCLIENT.AddServer(config.gamename, mapinfo.title, (!config.password.empty()), config.port);
×
218
        LOBBYCLIENT.AddListener(this);
×
219
    }
220
    AnnounceStatusChange();
×
221

222
    return true;
×
223
}
224

225
unsigned GameServer::GetNumFilledSlots() const
×
226
{
227
    unsigned numFilled = 0;
×
228
    for(const JoinPlayerInfo& player : playerInfos)
×
229
    {
230
        if(player.ps != PlayerState::Free)
×
231
            ++numFilled;
×
232
    }
233
    return numFilled;
×
234
}
235

236
void GameServer::AnnounceStatusChange()
×
237
{
238
    if(config.servertype == ServerType::LAN)
×
239
    {
240
        LanGameInfo info;
×
241
        info.name = config.gamename;
×
242
        info.hasPwd = !config.password.empty();
×
243
        info.map = mapinfo.title;
×
244
        info.curNumPlayers = GetNumFilledSlots();
×
245
        info.maxNumPlayers = playerInfos.size();
×
246
        info.port = config.port;
×
247
        info.isIPv6 = config.ipv6;
×
248
        info.version = rttr::version::GetReadableVersion();
×
249
        info.revision = rttr::version::GetRevision();
×
250
        Serializer ser;
×
251
        info.Serialize(ser);
×
252
        lanAnnouncer.SetPayload(ser.GetData(), ser.GetLength());
×
253
    } else if(config.servertype == ServerType::Lobby)
×
254
    {
255
        if(LOBBYCLIENT.IsIngame())
×
256
            LOBBYCLIENT.UpdateServerNumPlayers(GetNumFilledSlots(), playerInfos.size());
×
257
    }
258
}
×
259

260
void GameServer::LC_Status_Error(const std::string& /*error*/)
×
261
{
262
    // Error during adding of server to lobby -> Stop
263
    Stop();
×
264
}
×
265

266
void GameServer::LC_Created()
×
267
{
268
    // All good -> Don't listen anymore
269
    LOBBYCLIENT.RemoveListener(this);
×
270
    AnnounceStatusChange();
×
271
}
×
272

UNCOV
273
void GameServer::Run()
×
274
{
275
    if(state == ServerState::Stopped)
×
276
        return;
×
277

278
    // auf tote Clients prüfen
279
    ClientWatchDog();
×
280

281
    // auf neue Clients warten
282
    if(state == ServerState::Config)
×
283
        RunStateConfig();
×
284
    else if(state == ServerState::Loading)
×
285
        RunStateLoading();
×
286
    else if(state == ServerState::Game)
×
287
        RunStateGame();
×
288

289
    // post zustellen
290
    FillPlayerQueues();
×
291

292
    // Execute messages
293
    for(GameServerPlayer& player : networkPlayers)
×
294
    {
295
        // Ignore kicked players
296
        if(!player.socket.isValid())
×
297
            continue;
×
298
        player.executeMsgs(*this);
×
299
    }
300
    // Send afterwards as most messages are relayed which should be done as fast as possible
301
    for(GameServerPlayer& player : networkPlayers)
×
302
    {
303
        // Ignore kicked players
304
        if(!player.socket.isValid())
×
305
            continue;
×
306
        player.sendMsgs(10);
×
307
    }
308
    helpers::erase_if(networkPlayers, [](const auto& player) { return !player.socket.isValid(); });
×
309

310
    lanAnnouncer.Run();
×
311
}
312

313
void GameServer::RunStateConfig()
×
314
{
315
    WaitForClients();
×
316
    if(countdown.IsActive() && countdown.Update())
×
317
    {
318
        // nun echt starten
319
        if(!countdown.IsActive())
×
320
        {
321
            if(!StartGame())
×
322
            {
323
                Stop();
×
324
                return;
×
325
            }
326
        } else
327
            SendToAll(GameMessage_Countdown(countdown.GetRemainingSecs()));
×
328
    }
329
}
330

331
void GameServer::RunStateLoading()
×
332
{
333
    if(!nwfInfo.isReady())
×
334
    {
335
        if(SteadyClock::now() - loadStartTime > std::chrono::seconds(LOAD_TIMEOUT))
×
336
        {
337
            for(const NWFPlayerInfo& player : nwfInfo.getPlayerInfos())
×
338
            {
339
                if(player.isLagging)
×
340
                    KickPlayer(player.id, KickReason::PingTimeout, __LINE__);
×
341
            }
342
        }
343
        return;
×
344
    }
345
    LOG.write("SERVER: Game loaded by all players after %1%\n")
×
346
      % helpers::withUnit(std::chrono::duration_cast<std::chrono::seconds>(SteadyClock::now() - loadStartTime));
×
347
    // The first NWF is ready. Server has to set up "missing" commands so every future command is for the correct NWF as
348
    // specified with cmdDelay. We have commands for NWF 0. When clients execute this they will send the commands for
349
    // NWF cmdDelay. So commands for NWF 1..cmdDelay-1 are missing. Do this here and before the NWFDone is sent,
350
    // otherwise we might get them in a wrong order when messages are sent asynchronously
351
    for(unsigned i = 1; i < nwfInfo.getCmdDelay(); i++)
×
352
    {
353
        for(const NWFPlayerInfo& player : nwfInfo.getPlayerInfos())
×
354
        {
355
            GameMessage_GameCommand msg(player.id, nwfInfo.getPlayerCmds(player.id).checksum,
×
356
                                        std::vector<gc::GameCommandPtr>());
×
357
            SendToAll(msg);
×
358
            nwfInfo.addPlayerCmds(player.id, msg.cmds);
×
359
        }
360
    }
361

362
    NWFServerInfo serverInfo = nwfInfo.getServerInfo();
×
363
    // Send cmdDelay NWFDone messages
364
    // First send the OK for NWF 0 which is also the game ready command
365
    // Note: Do not store. It already is in NWFInfo
366
    SendToAll(GameMessage_Server_NWFDone(serverInfo.gf, serverInfo.newGFLen, serverInfo.nextNWF));
×
367
    RTTR_Assert(framesinfo.nwf_length > 0);
×
368
    // Then the remaining OKs for the commands sent above
369
    for(unsigned i = 1; i < nwfInfo.getCmdDelay(); i++)
×
370
    {
371
        serverInfo.gf = serverInfo.nextNWF;
×
372
        serverInfo.nextNWF += framesinfo.nwf_length;
×
373
        SendNWFDone(serverInfo);
×
374
    }
375

376
    // And go!
377
    framesinfo.lastTime = FramesInfo::UsedClock::now();
×
378
    state = ServerState::Game;
×
379
}
380

381
void GameServer::RunStateGame()
×
382
{
383
    if(!framesinfo.isPaused)
×
384
        ExecuteGameFrame();
×
385
}
×
386

UNCOV
387
void GameServer::Stop()
×
388
{
389
    if(state == ServerState::Stopped)
×
390
        return;
×
391

392
    // player verabschieden
393
    playerInfos.clear();
×
394
    networkPlayers.clear();
×
395

396
    // aufräumen
397
    framesinfo.Clear();
×
398
    config.Clear();
×
399
    mapinfo.Clear();
×
400
    countdown.Stop();
×
401

402
    // laden dicht machen
403
    serversocket.Close();
×
404
    // clear jump target
405
    skiptogf = 0;
×
406

407
    // clear async logs
408
    asyncLogs.clear();
×
409

410
    lanAnnouncer.Stop();
×
411

412
    if(LOBBYCLIENT.IsLoggedIn()) // steht die Lobbyverbindung noch?
×
413
        LOBBYCLIENT.DeleteServer();
×
414
    LOBBYCLIENT.RemoveListener(this);
×
415

416
    // status
417
    state = ServerState::Stopped;
×
418
    LOG.write("server state changed to stop\n");
×
419
}
420

421
// Check if there are players that have not been assigned a team but only a random team.
422
// Those players are assigned a team now optionally trying to balance the number of players per team.
423
// Returns true iff players have been assigned.
424
bool GameServer::assignPlayersOfRandomTeams(std::vector<JoinPlayerInfo>& playerInfos)
43✔
425
{
426
    static_assert(NUM_TEAMS == 4, "Expected exactly 4 playable teams!");
427
    RTTR_Assert(playerInfos.size() <= MAX_PLAYERS);
43✔
428

429
    using boost::container::static_vector;
430
    using PlayerIndex = unsigned;
431
    using TeamIndex = unsigned;
432
    const auto teamIdxToTeam = [](const TeamIndex teamNum) {
143✔
433
        RTTR_Assert(teamNum < NUM_TEAMS);
143✔
434
        return Team(static_cast<TeamIndex>(Team::Team1) + teamNum);
143✔
435
    };
436

437
    std::array<unsigned, NUM_TEAMS> numPlayersInTeam{};
43✔
438
    struct AssignPlayer
439
    {
440
        PlayerIndex player;
441
        static_vector<TeamIndex, NUM_TEAMS> possibleTeams;
442
        TeamIndex chosenTeam = 0;
443
    };
444

445
    static_vector<AssignPlayer, MAX_PLAYERS> playersToAssign;
×
446
    auto rng = helpers::getRandomGenerator();
43✔
447

448
    bool playerWasAssigned = false;
43✔
449

450
    // Assign (fully) random teams, count players in team and sort into playersToAssign
451
    for(PlayerIndex player = 0; player < playerInfos.size(); ++player)
279✔
452
    {
453
        auto& playerInfo = playerInfos[player];
236✔
454
        if(playerInfo.team == Team::Random)
236✔
455
        {
456
            const TeamIndex randTeam = std::uniform_int_distribution<TeamIndex>{0, NUM_TEAMS - 1u}(rng);
2✔
457
            playerInfo.team = teamIdxToTeam(randTeam);
2✔
458
            playerWasAssigned = true;
2✔
459
        }
460
        switch(playerInfo.team)
236✔
461
        {
462
            case Team::Team1: ++numPlayersInTeam[0]; break;
43✔
463
            case Team::Team2: ++numPlayersInTeam[1]; break;
7✔
464
            case Team::Team3: ++numPlayersInTeam[2]; break;
39✔
465
            case Team::Team4: ++numPlayersInTeam[3]; break;
4✔
466
            case Team::Random1To2: playersToAssign.emplace_back(AssignPlayer{player, {0, 1}}); break;
114✔
467
            case Team::Random1To3: playersToAssign.emplace_back(AssignPlayer{player, {0, 1, 2}}); break;
267✔
468
            case Team::Random1To4: playersToAssign.emplace_back(AssignPlayer{player, {0, 1, 2, 3}}); break;
42✔
469
            case Team::Random: RTTR_Assert(false); break;
×
470
            case Team::None: break;
2✔
471
        }
472
    }
473

474
    // To make the teams as even as possible we start to assign the most constrained players first
475
    std::sort(playersToAssign.begin(), playersToAssign.end(), [](const AssignPlayer& lhs, const AssignPlayer& rhs) {
43✔
476
        return lhs.possibleTeams.size() < rhs.possibleTeams.size();
624✔
477
    });
478

479
    // Put each player into a random team with the currently least amount of players using the possible teams only
480
    for(AssignPlayer& player : playersToAssign)
411✔
481
    {
482
        // Determine the teams with the minima size for the currently possible teams and choose one randomly
483
        unsigned minNextTeamSize = std::numeric_limits<unsigned>::max();
141✔
484
        static_vector<TeamIndex, NUM_TEAMS> teamsForNextPlayer;
×
485
        for(const TeamIndex team : player.possibleTeams)
1,221✔
486
        {
487
            if(minNextTeamSize > numPlayersInTeam[team])
399✔
488
            {
489
                teamsForNextPlayer.clear();
490
                teamsForNextPlayer.push_back(team);
491
                minNextTeamSize = numPlayersInTeam[team];
215✔
492
            } else if(minNextTeamSize == numPlayersInTeam[team])
184✔
493
                teamsForNextPlayer.push_back(team);
494
        }
495
        player.chosenTeam = helpers::getRandomElement(rng, teamsForNextPlayer);
141✔
496

497
        ++numPlayersInTeam[player.chosenTeam];
141✔
498
        playerWasAssigned = true;
141✔
499
    }
500
    // Now the teams are as even as possible and the uneven team(s) is a random one within the constraints
501
    // To have some more randomness we swap players within their constraints
502
    std::shuffle(playersToAssign.begin(), playersToAssign.end(), rng);
43✔
503
    for(auto it = playersToAssign.begin(); it != playersToAssign.end(); ++it)
325✔
504
    {
505
        // Search for a random player with which we can swap, including ourselfes
506
        // Go only forward to avoid back-swapping
507
        static_vector<decltype(it), MAX_PLAYERS> possibleSwapTargets;
×
508
        for(auto it2 = it; it2 != playersToAssign.end(); ++it2)
825✔
509
        {
510
            if(helpers::contains(it->possibleTeams, it2->chosenTeam)
684✔
511
               && helpers::contains(it2->possibleTeams, it->chosenTeam))
988✔
512
                possibleSwapTargets.push_back(it2);
513
        }
514
        const auto itSwapTarget = helpers::getRandomElement(rng, possibleSwapTargets);
141✔
515
        std::swap(it->chosenTeam, itSwapTarget->chosenTeam);
282✔
516
        playerInfos[it->player].team = teamIdxToTeam(it->chosenTeam);
282✔
517
    }
518

519
    return playerWasAssigned;
86✔
520
}
521

UNCOV
522
bool GameServer::StartGame()
×
523
{
524
    lanAnnouncer.Stop();
×
525

526
    // Finalize the team selection for unassigned players.
527
    if(assignPlayersOfRandomTeams(playerInfos))
×
528
        SendToAll(GameMessage_Player_List(playerInfos));
×
529

530
    // Bei Savegames wird der Startwert von den Clients aus der Datei gelesen!
531
    unsigned random_init;
532
    if(mapinfo.type == MapType::Savegame)
×
533
        random_init = 0;
×
534
    else
535
        random_init = static_cast<unsigned>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
×
536

537
    nwfInfo.init(currentGF, 3);
×
538

539
    // Send start first, then load the rest
540
    SendToAll(GameMessage_Server_Start(random_init, nwfInfo.getNextNWF(), nwfInfo.getCmdDelay()));
×
541
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_SERVER_START(%d)\n") % random_init;
×
542

543
    // Höchsten Ping ermitteln
544
    unsigned highest_ping = 0;
×
545
    for(const JoinPlayerInfo& player : playerInfos)
×
546
    {
547
        if(player.ps == PlayerState::Occupied)
×
548
        {
549
            if(player.ping > highest_ping)
×
550
                highest_ping = player.ping;
×
551
        }
552
    }
553

554
    framesinfo.gfLengthReq = framesinfo.gf_length = SPEED_GF_LENGTHS[ggs_.speed];
×
555

556
    // NetworkFrame-Länge bestimmen, je schlechter (also höher) die Pings, desto länger auch die Framelänge
557
    framesinfo.nwf_length = CalcNWFLenght(FramesInfo::milliseconds32_t(highest_ping));
×
558

559
    LOG.write("SERVER: Using gameframe length of %1%\n") % helpers::withUnit(framesinfo.gf_length);
×
560
    LOG.write("SERVER: Using networkframe length of %1% GFs (%2%)\n") % framesinfo.nwf_length
×
561
      % helpers::withUnit(framesinfo.nwf_length * framesinfo.gf_length);
×
562

563
    for(unsigned id = 0; id < playerInfos.size(); id++)
×
564
    {
565
        if(playerInfos[id].isUsed())
×
566
            nwfInfo.addPlayer(id);
×
567
    }
568

569
    // Add server info so nwfInfo can be ready but do NOT send it yet, as we wait for the player commands before sending
570
    // the done msg
571
    nwfInfo.addServerInfo(NWFServerInfo(currentGF, framesinfo.gf_length / FramesInfo::milliseconds32_t(1),
×
572
                                        currentGF + framesinfo.nwf_length));
×
573

574
    state = ServerState::Loading;
×
575
    loadStartTime = SteadyClock::now();
×
576

577
    return true;
×
578
}
579

580
unsigned GameServer::CalcNWFLenght(FramesInfo::milliseconds32_t minDuration) const
×
581
{
582
    constexpr unsigned maxNumGF = 20;
×
583
    for(unsigned i = 1; i < maxNumGF; ++i)
×
584
    {
585
        if(i * framesinfo.gf_length >= minDuration)
×
586
            return i;
×
587
    }
588
    return maxNumGF;
×
589
}
590

591
void GameServer::SendNWFDone(const NWFServerInfo& info)
×
592
{
593
    nwfInfo.addServerInfo(info);
×
594
    SendToAll(GameMessage_Server_NWFDone(info.gf, info.newGFLen, info.nextNWF));
×
595
}
×
596

UNCOV
597
void GameServer::SendToAll(const GameMessage& msg)
×
598
{
599
    for(GameServerPlayer& player : networkPlayers)
×
600
    {
601
        // ist der Slot Belegt, dann Nachricht senden
602
        if(player.isActive())
×
603
            player.sendMsgAsync(msg.clone());
×
604
    }
605
}
×
606

607
void GameServer::KickPlayer(uint8_t playerId, KickReason cause, uint32_t param)
×
608
{
609
    if(playerId >= playerInfos.size())
×
610
        return;
×
611
    JoinPlayerInfo& playerInfo = playerInfos[playerId];
×
612
    GameServerPlayer* player = GetNetworkPlayer(playerId);
×
613
    if(player)
×
614
        player->closeConnection();
×
615
    // Non-existing or connecting player
616
    if(!playerInfo.isUsed())
×
617
        return;
×
618
    playerInfo.ps = PlayerState::Free;
×
619

620
    SendToAll(GameMessage_Player_Kicked(playerId, cause, param));
×
621

622
    // If we are ingame, replace by KI
623
    if(state == ServerState::Game || state == ServerState::Loading)
×
624
    {
625
        playerInfo.ps = PlayerState::AI;
×
626
        playerInfo.aiInfo = AI::Info(AI::Type::Dummy);
×
627
    } else
628
        CancelCountdown();
×
629

630
    AnnounceStatusChange();
×
631
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYERKICKED(%d,%d,%d)\n") % unsigned(playerId) % unsigned(cause)
×
632
      % unsigned(param);
×
633
}
634

635
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
UNCOV
636
void GameServer::ClientWatchDog()
×
637
{
638
    SocketSet set;
×
639
    set.Clear();
×
640

641
    // sockets zum set hinzufügen
642
    for(GameServerPlayer& player : networkPlayers)
×
643
        set.Add(player.socket);
×
644

645
    // auf fehler prüfen
646
    if(set.Select(0, 2) > 0)
×
647
    {
648
        for(const GameServerPlayer& player : networkPlayers)
×
649
        {
650
            if(set.InSet(player.socket))
×
651
            {
652
                LOG.write(_("SERVER: Error on socket of player %1%, bye bye!\n")) % player.playerId;
×
653
                KickPlayer(player.playerId, KickReason::ConnectionLost, __LINE__);
×
654
            }
655
        }
656
    }
657

658
    for(GameServerPlayer& player : networkPlayers)
×
659
    {
660
        if(player.hasTimedOut())
×
661
        {
662
            LOG.write(_("SERVER: Reserved slot %1% freed due to timeout\n")) % player.playerId;
×
663
            KickPlayer(player.playerId, KickReason::PingTimeout, __LINE__);
×
664
        } else
665
            player.doPing();
×
666
    }
667
}
×
668

669
void GameServer::ExecuteGameFrame()
×
670
{
671
    RTTR_Assert(state == ServerState::Game);
×
672

673
    FramesInfo::UsedClock::time_point currentTime = FramesInfo::UsedClock::now();
×
674
    FramesInfo::milliseconds32_t passedTime =
675
      std::chrono::duration_cast<FramesInfo::milliseconds32_t>(currentTime - framesinfo.lastTime);
×
676

677
    // prüfen ob GF vergangen
678
    if(passedTime >= framesinfo.gf_length || skiptogf > currentGF)
×
679
    {
680
        // NWF vergangen?
681
        if(currentGF == nwfInfo.getNextNWF())
×
682
        {
683
            if(CheckForLaggingPlayers())
×
684
            {
685
                // Check for kicking every second
686
                static FramesInfo::UsedClock::time_point lastLagKickTime;
687
                if(currentTime - lastLagKickTime >= std::chrono::seconds(1))
×
688
                {
689
                    lastLagKickTime = currentTime;
×
690
                    CheckAndKickLaggingPlayers();
×
691
                }
692
                // Skip the rest
693
                return;
×
694
            } else
695
                ExecuteNWF();
×
696
        }
697
        // Advance GF
698
        ++currentGF;
×
699
        // Normally we set lastTime = curTime (== lastTime + passedTime) where passedTime is ideally 1 GF
700
        // But we might got called late, so we advance the time by 1 GF anyway so in that case we execute the next GF a
701
        // bit earlier. Exception: We lag many GFs behind, then we advance by the full passedTime - 1 GF which means we
702
        // are now only 1 GF behind and execute that on the next call
703
        if(passedTime <= 4 * framesinfo.gf_length)
×
704
            passedTime = framesinfo.gf_length;
×
705
        else
706
            passedTime -= framesinfo.gf_length;
×
707
        framesinfo.lastTime += passedTime;
×
708
    }
709
}
710

711
void GameServer::ExecuteNWF()
×
712
{
713
    // Check for asyncs
714
    if(CheckForAsync())
×
715
    {
716
        // Pause game
717
        RTTR_Assert(!framesinfo.isPaused);
×
718
        SetPaused(true);
×
719

720
        // Notify players
721
        std::vector<unsigned> checksumHashes;
×
722
        checksumHashes.reserve(networkPlayers.size());
×
723
        for(const GameServerPlayer& player : networkPlayers)
×
724
            checksumHashes.push_back(nwfInfo.getPlayerCmds(player.playerId).checksum.getHash());
×
725
        SendToAll(GameMessage_Server_Async(checksumHashes));
×
726

727
        // Request async logs
728
        for(GameServerPlayer& player : networkPlayers)
×
729
        {
730
            asyncLogs.push_back(AsyncLog(player.playerId, nwfInfo.getPlayerCmds(player.playerId).checksum));
×
731
            player.sendMsgAsync(new GameMessage_GetAsyncLog());
×
732
        }
733
    }
734
    const NWFServerInfo serverInfo = nwfInfo.getServerInfo();
×
735
    RTTR_Assert(serverInfo.gf == currentGF);
×
736
    RTTR_Assert(serverInfo.nextNWF > currentGF);
×
737
    // First save old values
738
    unsigned lastNWF = nwfInfo.getLastNWF();
×
739
    FramesInfo::milliseconds32_t oldGFLen = framesinfo.gf_length;
×
740
    nwfInfo.execute(framesinfo);
×
741
    if(oldGFLen != framesinfo.gf_length)
×
742
    {
743
        LOG.write(_("SERVER: At GF %1%: Speed changed from %2% to %3%. NWF %4%\n")) % currentGF
×
744
          % helpers::withUnit(oldGFLen) % helpers::withUnit(framesinfo.gf_length) % framesinfo.nwf_length;
×
745
    }
746
    NWFServerInfo newInfo(lastNWF, framesinfo.gfLengthReq / FramesInfo::milliseconds32_t(1),
×
747
                          lastNWF + framesinfo.nwf_length);
×
748
    if(framesinfo.gfLengthReq != framesinfo.gf_length)
×
749
    {
750
        // Speed will change, adjust nwf length so the time will stay constant
751
        using namespace std::chrono;
752
        using MsDouble = duration<double, std::milli>;
753
        double newNWFLen =
754
          framesinfo.nwf_length * framesinfo.gf_length / duration_cast<MsDouble>(framesinfo.gfLengthReq);
×
755
        newInfo.nextNWF = lastNWF + std::max(1u, helpers::iround<unsigned>(newNWFLen));
×
756
    }
757
    SendNWFDone(newInfo);
×
758
}
×
759

760
bool GameServer::CheckForAsync()
×
761
{
762
    if(networkPlayers.empty())
×
763
        return false;
×
764
    bool isAsync = false;
×
765
    const AsyncChecksum& refChecksum = nwfInfo.getPlayerCmds(networkPlayers.front().playerId).checksum;
×
766
    for(const GameServerPlayer& player : networkPlayers)
×
767
    {
768
        const AsyncChecksum& curChecksum = nwfInfo.getPlayerCmds(player.playerId).checksum;
×
769

770
        // Checksummen nicht gleich?
771
        if(curChecksum != refChecksum)
×
772
        {
773
            LOG.write(_("Async at GF %1% of player %2% vs %3%. Checksums:\n%4%\n%5%\n\n")) % currentGF % player.playerId
×
774
              % networkPlayers.front().playerId % curChecksum % refChecksum;
×
775
            isAsync = true;
×
776
        }
777
    }
778
    return isAsync;
×
779
}
780

781
void GameServer::CheckAndKickLaggingPlayers()
×
782
{
783
    for(const GameServerPlayer& player : networkPlayers)
×
784
    {
785
        const unsigned timeOut = player.getLagTimeOut();
×
786
        if(timeOut == 0)
×
787
            KickPlayer(player.playerId, KickReason::PingTimeout, __LINE__);
×
788
        else if(timeOut <= 30
×
789
                && (timeOut % 5 == 0
×
790
                    || timeOut < 5)) // Notify every 5s if max 30s are remaining, if less than 5s notify every second
×
791
            LOG.write(_("SERVER: Kicking player %1% in %2% seconds\n")) % player.playerId % timeOut;
×
792
    }
793
}
×
794

795
bool GameServer::CheckForLaggingPlayers()
×
796
{
797
    if(nwfInfo.isReady())
×
798
        return false;
×
799
    for(GameServerPlayer& player : networkPlayers)
×
800
    {
801
        if(nwfInfo.getPlayerInfo(player.playerId).isLagging)
×
802
            player.setLagging();
×
803
    }
804
    return true;
×
805
}
806

807
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
UNCOV
808
void GameServer::WaitForClients()
×
809
{
810
    SocketSet set;
×
811

812
    set.Add(serversocket);
×
813
    if(set.Select(0, 0) > 0)
×
814
    {
815
        RTTR_Assert(set.InSet(serversocket));
×
816
        Socket socket = serversocket.Accept();
×
817

818
        // Verbindung annehmen
819
        if(!socket.isValid())
×
820
            return;
×
821

822
        unsigned newPlayerId = GameMessageWithPlayer::NO_PLAYER_ID;
×
823
        // Geeigneten Platz suchen
824
        for(unsigned playerId = 0; playerId < playerInfos.size(); ++playerId)
×
825
        {
826
            if(playerInfos[playerId].ps == PlayerState::Free && !GetNetworkPlayer(playerId))
×
827
            {
828
                networkPlayers.push_back(GameServerPlayer(playerId, socket));
×
829
                newPlayerId = playerId;
×
830
                break;
×
831
            }
832
        }
833

834
        GameMessage_Player_Id msg(newPlayerId);
×
835
        MessageHandler::send(socket, msg);
×
836

837
        // war kein platz mehr frei, wenn ja dann verbindung trennen?
838
        if(newPlayerId == 0xFFFFFFFF)
×
839
            socket.Close();
×
840
    }
841
}
842

843
// füllt die warteschlangen mit "paketen"
UNCOV
844
void GameServer::FillPlayerQueues()
×
845
{
846
    SocketSet set;
×
847
    bool msgReceived = false;
×
848

849
    // erstmal auf Daten überprüfen
850
    do
×
851
    {
852
        // sockets zum set hinzufügen
853
        for(const GameServerPlayer& player : networkPlayers)
×
854
            set.Add(player.socket);
×
855

856
        msgReceived = false;
×
857

858
        // ist eines der Sockets im Set lesbar?
859
        if(set.Select(0, 0) > 0)
×
860
        {
861
            for(GameServerPlayer& player : networkPlayers)
×
862
            {
863
                if(set.InSet(player.socket))
×
864
                {
865
                    // nachricht empfangen
866
                    if(!player.receiveMsgs())
×
867
                    {
868
                        LOG.write(_("SERVER: Receiving Message for player %1% failed, kicking...\n")) % player.playerId;
×
869
                        KickPlayer(player.playerId, KickReason::ConnectionLost, __LINE__);
×
870
                    } else
871
                        msgReceived = true;
×
872
                }
873
            }
874
        }
875
    } while(msgReceived);
876
}
×
877

UNCOV
878
bool GameServer::OnGameMessage(const GameMessage_Pong& msg)
×
879
{
880
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
881
    if(player)
×
882
    {
883
        unsigned ping = player->calcPingTime();
×
884
        if(ping == 0u)
×
885
            return true;
×
886
        playerInfos[msg.senderPlayerID].ping = ping;
×
887
        SendToAll(GameMessage_Player_Ping(msg.senderPlayerID, ping));
×
888
    }
889
    return true;
×
890
}
891

UNCOV
892
bool GameServer::OnGameMessage(const GameMessage_Server_Type& msg)
×
893
{
894
    if(state != ServerState::Config)
×
895
    {
896
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
897
        return true;
×
898
    }
899

900
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
901
    if(!player)
×
902
        return true;
×
903

904
    auto typeok = GameMessage_Server_TypeOK::StatusCode::Ok;
×
905
    if(msg.type != config.servertype)
×
906
        typeok = GameMessage_Server_TypeOK::StatusCode::InvalidServerType;
×
907
    else if(msg.revision != rttr::version::GetRevision())
×
908
        typeok = GameMessage_Server_TypeOK::StatusCode::WrongVersion;
×
909

910
    player->sendMsg(GameMessage_Server_TypeOK(typeok, rttr::version::GetRevision()));
×
911

912
    if(typeok != GameMessage_Server_TypeOK::StatusCode::Ok)
×
913
        KickPlayer(msg.senderPlayerID, KickReason::ConnectionLost, __LINE__);
×
914
    return true;
×
915
}
916

UNCOV
917
bool GameServer::OnGameMessage(const GameMessage_Server_Password& msg)
×
918
{
919
    if(state != ServerState::Config)
×
920
    {
921
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
922
        return true;
×
923
    }
924

925
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
926
    if(!player)
×
927
        return true;
×
928

929
    std::string passwordok = (config.password == msg.password ? "true" : "false");
×
930
    if(msg.password == config.hostPassword)
×
931
    {
932
        passwordok = "true";
×
933
        playerInfos[msg.senderPlayerID].isHost = true;
×
934
    } else
935
        playerInfos[msg.senderPlayerID].isHost = false;
×
936

937
    player->sendMsgAsync(new GameMessage_Server_Password(passwordok));
×
938

939
    if(passwordok == "false")
×
940
        KickPlayer(msg.senderPlayerID, KickReason::WrongPassword, __LINE__);
×
941
    return true;
×
942
}
943

UNCOV
944
bool GameServer::OnGameMessage(const GameMessage_Chat& msg)
×
945
{
946
    int playerID = GetTargetPlayer(msg);
×
947
    if(playerID >= 0)
×
948
        SendToAll(GameMessage_Chat(playerID, msg.destination, msg.text));
×
949
    return true;
×
950
}
951

952
bool GameServer::OnGameMessage(const GameMessage_Player_State& msg)
×
953
{
954
    if(state != ServerState::Config)
×
955
    {
956
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
957
        return true;
×
958
    }
959
    // Can't do this. Have to have a joined player
960
    if(msg.ps == PlayerState::Occupied)
×
961
        return true;
×
962

963
    int playerID = GetTargetPlayer(msg);
×
964
    if(playerID < 0)
×
965
        return true;
×
966
    JoinPlayerInfo& player = playerInfos[playerID];
×
967
    const PlayerState oldPs = player.ps;
×
968
    // Can't change self
969
    if(playerID != msg.senderPlayerID)
×
970
    {
971
        // oh ein spieler, weg mit ihm!
972
        if(GetNetworkPlayer(playerID))
×
973
            KickPlayer(playerID, KickReason::NoCause, __LINE__);
×
974

975
        if(mapinfo.type == MapType::Savegame)
×
976
        {
977
            // For savegames we cannot set anyone on a locked slot as the player does not exist on the map
978
            if(player.ps != PlayerState::Locked)
×
979
            {
980
                // And we don't lock!
981
                player.ps = msg.ps == PlayerState::Locked ? PlayerState::Free : msg.ps;
×
982
                player.aiInfo = msg.aiInfo;
×
983
            }
984
        } else
985
        {
986
            player.ps = msg.ps;
×
987
            player.aiInfo = msg.aiInfo;
×
988
        }
989
        if(player.ps == PlayerState::Free && config.servertype == ServerType::Local)
×
990
        {
991
            player.ps = PlayerState::AI;
×
992
            player.aiInfo = AI::Info(AI::Type::Default);
×
993
        }
994
    }
995
    // Even when nothing changed we send the data because the other players might have expected a change
996

997
    if(player.ps == PlayerState::AI)
×
998
    {
999
        player.SetAIName(playerID);
×
1000
        SendToAll(GameMessage_Player_Name(playerID, player.name));
×
1001
    }
1002
    // If slot is filled, check current color
1003
    if(player.isUsed())
×
1004
        CheckAndSetColor(playerID, player.color);
×
1005
    SendToAll(GameMessage_Player_State(playerID, player.ps, player.aiInfo));
×
1006

1007
    if(oldPs != player.ps)
×
1008
        player.isReady = (player.ps == PlayerState::AI);
×
1009
    SendToAll(GameMessage_Player_Ready(playerID, player.isReady));
×
1010
    PlayerDataChanged(playerID);
×
1011
    AnnounceStatusChange();
×
1012
    return true;
×
1013
}
1014

UNCOV
1015
bool GameServer::OnGameMessage(const GameMessage_Player_Name& msg)
×
1016
{
1017
    if(state != ServerState::Config)
×
1018
    {
1019
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1020
        return true;
×
1021
    }
1022
    int playerID = GetTargetPlayer(msg);
×
1023
    if(playerID < 0)
×
1024
        return true;
×
1025

1026
    LOG.writeToFile("CLIENT%d >>> SERVER: NMS_PLAYER_NAME(%s)\n") % playerID % msg.playername;
×
1027

1028
    playerInfos[playerID].name = msg.playername;
×
1029
    SendToAll(GameMessage_Player_Name(playerID, msg.playername));
×
1030
    PlayerDataChanged(playerID);
×
1031

1032
    return true;
×
1033
}
1034

NEW
1035
bool GameServer::OnGameMessage(const GameMessage_Player_Portrait& msg)
×
1036
{
NEW
1037
    if(state != ServerState::Config)
×
1038
    {
NEW
1039
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
NEW
1040
        return true;
×
1041
    }
NEW
1042
    int playerID = GetTargetPlayer(msg);
×
NEW
1043
    if(playerID < 0)
×
NEW
1044
        return true;
×
NEW
1045
    if(msg.playerPortraitIndex >= Portraits.size())
×
NEW
1046
        return true;
×
1047

NEW
1048
    LOG.writeToFile("CLIENT%d >>> SERVER: NMS_PLAYER_PORTRAIT(%u)\n") % playerID % msg.playerPortraitIndex;
×
NEW
1049
    playerInfos[playerID].portraitIndex = msg.playerPortraitIndex;
×
NEW
1050
    SendToAll(GameMessage_Player_Portrait(playerID, msg.playerPortraitIndex));
×
NEW
1051
    PlayerDataChanged(playerID);
×
1052

NEW
1053
    return true;
×
1054
}
1055

UNCOV
1056
bool GameServer::OnGameMessage(const GameMessage_Player_Nation& msg)
×
1057
{
1058
    if(state != ServerState::Config)
×
1059
    {
1060
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1061
        return true;
×
1062
    }
1063
    int playerID = GetTargetPlayer(msg);
×
1064
    if(playerID < 0)
×
1065
        return true;
×
1066

1067
    playerInfos[playerID].nation = msg.nation;
×
1068

1069
    SendToAll(GameMessage_Player_Nation(playerID, msg.nation));
×
1070
    PlayerDataChanged(playerID);
×
1071
    return true;
×
1072
}
1073

UNCOV
1074
bool GameServer::OnGameMessage(const GameMessage_Player_Team& msg)
×
1075
{
1076
    if(state != ServerState::Config)
×
1077
    {
1078
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1079
        return true;
×
1080
    }
1081
    int playerID = GetTargetPlayer(msg);
×
1082
    if(playerID < 0)
×
1083
        return true;
×
1084

1085
    playerInfos[playerID].team = msg.team;
×
1086

1087
    SendToAll(GameMessage_Player_Team(playerID, msg.team));
×
1088
    PlayerDataChanged(playerID);
×
1089
    return true;
×
1090
}
1091

UNCOV
1092
bool GameServer::OnGameMessage(const GameMessage_Player_Color& msg)
×
1093
{
1094
    if(state != ServerState::Config)
×
1095
    {
1096
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1097
        return true;
×
1098
    }
1099
    int playerID = GetTargetPlayer(msg);
×
1100
    if(playerID < 0)
×
1101
        return true;
×
1102

1103
    CheckAndSetColor(playerID, msg.color);
×
1104
    PlayerDataChanged(playerID);
×
1105
    return true;
×
1106
}
1107

UNCOV
1108
bool GameServer::OnGameMessage(const GameMessage_Player_Ready& msg)
×
1109
{
1110
    if(state != ServerState::Config)
×
1111
    {
1112
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1113
        return true;
×
1114
    }
1115
    int playerID = GetTargetPlayer(msg);
×
1116
    if(playerID < 0)
×
1117
        return true;
×
1118

1119
    JoinPlayerInfo& player = playerInfos[playerID];
×
1120

1121
    player.isReady = msg.ready;
×
1122

1123
    // countdown ggf abbrechen
1124
    if(!player.isReady && countdown.IsActive())
×
1125
        CancelCountdown();
×
1126

1127
    SendToAll(GameMessage_Player_Ready(playerID, msg.ready));
×
1128
    return true;
×
1129
}
1130

1131
bool GameServer::OnGameMessage(const GameMessage_MapRequest& msg)
×
1132
{
1133
    if(state != ServerState::Config)
×
1134
    {
1135
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1136
        return true;
×
1137
    }
1138
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1139
    if(!player)
×
1140
        return true;
×
1141

1142
    if(msg.requestInfo)
×
1143
    {
1144
        player->sendMsgAsync(new GameMessage_Map_Info(mapinfo.filepath.filename().string(), mapinfo.type,
×
1145
                                                      mapinfo.mapData.uncompressedLength, mapinfo.mapData.data.size(),
×
1146
                                                      mapinfo.luaData.uncompressedLength, mapinfo.luaData.data.size()));
×
1147
    } else if(player->isMapSending())
×
1148
    {
1149
        // Don't send again
1150
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1151
    } else
1152
    {
1153
        // Send map data
1154
        unsigned curPos = 0;
×
1155
        unsigned remainingSize = mapinfo.mapData.data.size();
×
1156
        while(remainingSize)
×
1157
        {
1158
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1159

1160
            player->sendMsgAsync(new GameMessage_Map_Data(true, curPos, &mapinfo.mapData.data[curPos], chunkSize));
×
1161
            curPos += chunkSize;
×
1162
            remainingSize -= chunkSize;
×
1163
        }
1164

1165
        // And lua data (if there is any)
1166
        RTTR_Assert(mapinfo.luaFilepath.empty() == mapinfo.luaData.data.empty());
×
1167
        RTTR_Assert(mapinfo.luaData.data.empty() == (mapinfo.luaData.uncompressedLength == 0));
×
1168
        curPos = 0;
×
1169
        remainingSize = mapinfo.luaData.data.size();
×
1170
        while(remainingSize)
×
1171
        {
1172
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1173

1174
            player->sendMsgAsync(new GameMessage_Map_Data(false, curPos, &mapinfo.luaData.data[curPos], chunkSize));
×
1175
            curPos += chunkSize;
×
1176
            remainingSize -= chunkSize;
×
1177
        }
1178
        // estimate time. max 60 chunks/s (currently limited by framerate), assume 50 (~25kb/s)
1179
        auto numChunks = (mapinfo.mapData.data.size() + mapinfo.luaData.data.size()) / MAP_PART_SIZE;
×
1180
        player->setMapSending(std::chrono::seconds(numChunks / 50 + 1));
×
1181
    }
1182
    return true;
×
1183
}
1184

1185
bool GameServer::OnGameMessage(const GameMessage_Map_Checksum& msg)
×
1186
{
1187
    if(state != ServerState::Config)
×
1188
    {
1189
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1190
        return true;
×
1191
    }
1192
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1193
    if(!player)
×
1194
        return true;
×
1195

1196
    bool checksumok = (msg.mapChecksum == mapinfo.mapChecksum && msg.luaChecksum == mapinfo.luaChecksum);
×
1197

1198
    LOG.writeToFile("CLIENT%d >>> SERVER: NMS_MAP_CHECKSUM(%u) expected: %u, ok: %s\n") % unsigned(msg.senderPlayerID)
×
1199
      % msg.mapChecksum % mapinfo.mapChecksum % (checksumok ? "yes" : "no");
×
1200

1201
    // Send response. If map data was not sent yet, the client may retry
1202
    player->sendMsgAsync(new GameMessage_Map_ChecksumOK(checksumok, !player->isMapSending()));
×
1203

1204
    LOG.writeToFile("SERVER >>> CLIENT%d: NMS_MAP_CHECKSUM(%d)\n") % unsigned(msg.senderPlayerID) % checksumok;
×
1205

1206
    if(!checksumok)
×
1207
    {
1208
        if(player->isMapSending())
×
1209
            KickPlayer(msg.senderPlayerID, KickReason::WrongChecksum, __LINE__);
×
1210
    } else
1211
    {
1212
        JoinPlayerInfo& playerInfo = playerInfos[msg.senderPlayerID];
×
1213
        // Used? Then we got this twice or some error happened. Remove him
1214
        if(playerInfo.isUsed())
×
1215
            KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1216
        else
1217
        {
1218
            // Inform others about a new player
1219
            SendToAll(GameMessage_Player_New(msg.senderPlayerID, playerInfo.name));
×
1220

1221
            LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYER_NEW(%d, %s)\n") % unsigned(msg.senderPlayerID)
×
1222
              % playerInfo.name;
×
1223

1224
            // Mark as used and assign a unique color
1225
            // Do this before sending the player list to avoid sending useless updates
1226
            playerInfo.ps = PlayerState::Occupied;
×
1227
            CheckAndSetColor(msg.senderPlayerID, playerInfo.color);
×
1228

1229
            // Send remaining data and mark as active
1230
            player->sendMsgAsync(new GameMessage_Server_Name(config.gamename));
×
1231
            player->sendMsgAsync(new GameMessage_Player_List(playerInfos));
×
1232
            player->sendMsgAsync(new GameMessage_GGSChange(ggs_));
×
1233
            player->setActive();
×
1234
        }
1235
        AnnounceStatusChange();
×
1236
    }
1237
    return true;
×
1238
}
1239

1240
// speed change message
1241
bool GameServer::OnGameMessage(const GameMessage_Speed& msg)
×
1242
{
1243
    if(state != ServerState::Game)
×
1244
    {
1245
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1246
        return true;
×
1247
    }
1248
    framesinfo.gfLengthReq = FramesInfo::milliseconds32_t(msg.gf_length);
×
1249
    return true;
×
1250
}
1251

1252
bool GameServer::OnGameMessage(const GameMessage_GameCommand& msg)
×
1253
{
1254
    int targetPlayerId = GetTargetPlayer(msg);
×
1255
    if((state != ServerState::Game && state != ServerState::Loading) || targetPlayerId < 0
×
1256
       || (state == ServerState::Loading && !msg.cmds.gcs.empty()))
×
1257
    {
1258
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1259
        return true;
×
1260
    }
1261

1262
    if(!nwfInfo.addPlayerCmds(targetPlayerId, msg.cmds))
×
1263
        return true; // Ignore
×
1264
    GameServerPlayer* player = GetNetworkPlayer(targetPlayerId);
×
1265
    if(player)
×
1266
        player->setNotLagging();
×
1267
    SendToAll(GameMessage_GameCommand(targetPlayerId, msg.cmds.checksum, msg.cmds.gcs));
×
1268

1269
    return true;
×
1270
}
1271

1272
bool GameServer::OnGameMessage(const GameMessage_AsyncLog& msg)
×
1273
{
1274
    if(state != ServerState::Game)
×
1275
    {
1276
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1277
        return true;
×
1278
    }
1279
    bool foundPlayer = false;
×
1280
    for(AsyncLog& log : asyncLogs)
×
1281
    {
1282
        if(log.playerId != msg.senderPlayerID)
×
1283
            continue;
×
1284
        RTTR_Assert(!log.done);
×
1285
        if(log.done)
×
1286
            return true;
×
1287
        foundPlayer = true;
×
1288
        log.addData += msg.addData;
×
1289
        log.randEntries.insert(log.randEntries.end(), msg.entries.begin(), msg.entries.end());
×
1290
        if(msg.last)
×
1291
        {
1292
            LOG.write(_("Received async logs from %1% (%2% entries).\n")) % unsigned(log.playerId)
×
1293
              % log.randEntries.size();
×
1294
            log.done = true;
×
1295
        }
1296
    }
1297
    if(!foundPlayer)
×
1298
    {
1299
        LOG.write(_("Received async log from %1%, but did not expect it!\n")) % unsigned(msg.senderPlayerID);
×
1300
        return true;
×
1301
    }
1302

1303
    // Check if we have all logs
1304
    for(const AsyncLog& log : asyncLogs)
×
1305
    {
1306
        if(!log.done)
×
1307
            return true;
×
1308
    }
1309

1310
    LOG.write(_("Async logs received completely.\n"));
×
1311

1312
    const bfs::path asyncFilePath = SaveAsyncLog();
×
1313
    if(!asyncFilePath.empty())
×
1314
        SendAsyncLog(asyncFilePath);
×
1315

1316
    // Kick all players that have a different checksum from the host
1317
    AsyncChecksum hostChecksum;
×
1318
    for(const AsyncLog& log : asyncLogs)
×
1319
    {
1320
        if(playerInfos.at(log.playerId).isHost)
×
1321
        {
1322
            hostChecksum = log.checksum;
×
1323
            break;
×
1324
        }
1325
    }
1326
    for(const AsyncLog& log : asyncLogs)
×
1327
    {
1328
        if(log.checksum != hostChecksum)
×
1329
            KickPlayer(log.playerId, KickReason::Async, __LINE__);
×
1330
    }
1331
    return true;
×
1332
}
1333

1334
bool GameServer::OnGameMessage(const GameMessage_RemoveLua& msg)
×
1335
{
1336
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1337
    {
1338
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1339
        return true;
×
1340
    }
1341
    mapinfo.luaFilepath.clear();
×
1342
    mapinfo.luaData.Clear();
×
1343
    mapinfo.luaChecksum = 0;
×
1344
    SendToAll(msg);
×
1345
    CancelCountdown();
×
1346
    return true;
×
1347
}
1348

1349
bool GameServer::OnGameMessage(const GameMessage_Countdown& msg)
×
1350
{
1351
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1352
    {
1353
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1354
        return true;
×
1355
    }
1356

1357
    NetworkPlayer* nwPlayer = GetNetworkPlayer(msg.senderPlayerID);
×
1358
    if(!nwPlayer || countdown.IsActive())
×
1359
        return true;
×
1360

1361
    if(!ArePlayersReady())
×
1362
        nwPlayer->sendMsgAsync(new GameMessage_CancelCountdown(true));
×
1363
    else
1364
    {
1365
        // Just to make sure update all player infos
1366
        SendToAll(GameMessage_Player_List(playerInfos));
×
1367
        // Start countdown (except its single player)
1368
        if(networkPlayers.size() > 1)
×
1369
        {
1370
            countdown.Start(msg.countdown);
×
1371
            SendToAll(GameMessage_Countdown(countdown.GetRemainingSecs()));
×
1372
            LOG.writeToFile("SERVER >>> Countdown started(%d)\n") % countdown.GetRemainingSecs();
×
1373
        } else if(!StartGame())
×
1374
            Stop();
×
1375
    }
1376

1377
    return true;
×
1378
}
1379

1380
bool GameServer::OnGameMessage(const GameMessage_CancelCountdown& msg)
×
1381
{
1382
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1383
    {
1384
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1385
        return true;
×
1386
    }
1387

1388
    CancelCountdown();
×
1389
    return true;
×
1390
}
1391

1392
bool GameServer::OnGameMessage(const GameMessage_Pause& msg)
×
1393
{
1394
    if(IsHost(msg.senderPlayerID))
×
1395
        SetPaused(msg.paused);
×
1396
    return true;
×
1397
}
1398

1399
bool GameServer::OnGameMessage(const GameMessage_SkipToGF& msg)
×
1400
{
1401
    if(IsHost(msg.senderPlayerID))
×
1402
    {
1403
        skiptogf = msg.targetGF;
×
1404
        SendToAll(msg);
×
1405
    }
1406
    return true;
×
1407
}
1408

1409
bool GameServer::OnGameMessage(const GameMessage_GGSChange& msg)
×
1410
{
1411
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1412
    {
1413
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1414
        return true;
×
1415
    }
1416
    ggs_ = msg.ggs;
×
1417
    SendToAll(msg);
×
1418
    CancelCountdown();
×
1419
    return true;
×
1420
}
1421

1422
void GameServer::CancelCountdown()
×
1423
{
1424
    if(!countdown.IsActive())
×
1425
        return;
×
1426
    // Countdown-Stop allen mitteilen
1427
    countdown.Stop();
×
1428
    SendToAll(GameMessage_CancelCountdown());
×
1429
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_CANCELCOUNTDOWN\n");
×
1430
}
1431

1432
bool GameServer::ArePlayersReady() const
×
1433
{
1434
    // Alle Spieler da?
1435
    for(const JoinPlayerInfo& player : playerInfos)
×
1436
    {
1437
        // noch nicht alle spieler da -> feierabend!
1438
        if(player.ps == PlayerState::Free || (player.isHuman() && !player.isReady))
×
1439
            return false;
×
1440
    }
1441

1442
    std::set<unsigned> takenColors;
×
1443

1444
    // Check all players have different colors
1445
    for(const JoinPlayerInfo& player : playerInfos)
×
1446
    {
1447
        if(player.isUsed())
×
1448
        {
1449
            if(helpers::contains(takenColors, player.color))
×
1450
                return false;
×
1451
            takenColors.insert(player.color);
×
1452
        }
1453
    }
1454
    return true;
×
1455
}
1456

1457
void GameServer::PlayerDataChanged(unsigned playerIdx)
×
1458
{
1459
    CancelCountdown();
×
1460
    JoinPlayerInfo& player = GetJoinPlayer(playerIdx);
×
1461
    if(player.ps != PlayerState::AI && player.isReady)
×
1462
    {
1463
        player.isReady = false;
×
1464
        SendToAll(GameMessage_Player_Ready(playerIdx, false));
×
1465
    }
1466
}
×
1467

1468
bfs::path GameServer::SaveAsyncLog()
×
1469
{
1470
    // Get the highest common counter number and start from there (remove all others)
1471
    unsigned maxCtr = 0;
×
1472
    for(const AsyncLog& log : asyncLogs)
×
1473
    {
1474
        if(!log.randEntries.empty() && log.randEntries[0].counter > maxCtr)
×
1475
            maxCtr = log.randEntries[0].counter;
×
1476
    }
1477
    // Number of entries = max(asyncLogs[0..n].randEntries.size())
1478
    unsigned numEntries = 0;
×
1479
    for(AsyncLog& log : asyncLogs)
×
1480
    {
1481
        auto it = helpers::find_if(log.randEntries, [maxCtr](const auto& e) { return e.counter == maxCtr; });
×
1482
        log.randEntries.erase(log.randEntries.begin(), it);
×
1483
        if(numEntries < log.randEntries.size())
×
1484
            numEntries = log.randEntries.size();
×
1485
    }
1486
    // No entries :(
1487
    if(numEntries == 0 || asyncLogs.size() < 2u)
×
1488
        return "";
×
1489

1490
    // count identical lines
1491
    unsigned numIdentical = 0;
×
1492
    for(unsigned i = 0; i < numEntries; i++)
×
1493
    {
1494
        bool isIdentical = true;
×
1495
        if(i >= asyncLogs[0].randEntries.size())
×
1496
            break;
×
1497
        const RandomEntry& refEntry = asyncLogs[0].randEntries[i];
×
1498
        for(const AsyncLog& log : asyncLogs)
×
1499
        {
1500
            if(i >= log.randEntries.size())
×
1501
            {
1502
                isIdentical = false;
×
1503
                break;
×
1504
            }
1505
            const RandomEntry& curEntry = log.randEntries[i];
×
1506
            if(curEntry.maxExcl != refEntry.maxExcl || curEntry.rngState != refEntry.rngState
×
1507
               || curEntry.objId != refEntry.objId)
×
1508
            {
1509
                isIdentical = false;
×
1510
                break;
×
1511
            }
1512
        }
1513
        if(isIdentical)
×
1514
            ++numIdentical;
×
1515
        else
1516
            break;
×
1517
    }
1518

1519
    LOG.write(_("There are %1% identical async log entries.\n")) % numIdentical;
×
1520

1521
    bfs::path filePath =
1522
      RTTRCONFIG.ExpandPath(s25::folders::logs) / (s25util::Time::FormatTime("async_%Y-%m-%d_%H-%i-%s") + "Server.log");
×
1523

1524
    // open async log
1525
    bnw::ofstream file(filePath);
×
1526

1527
    if(file)
×
1528
    {
1529
        file << "Map: " << mapinfo.title << std::endl;
×
1530
        file << std::setfill(' ');
×
1531
        for(const AsyncLog& log : asyncLogs)
×
1532
        {
1533
            const JoinPlayerInfo& plInfo = playerInfos.at(log.playerId);
×
1534
            file << "Player " << std::setw(2) << unsigned(log.playerId) << (plInfo.isHost ? '#' : ' ') << "\t\""
×
1535
                 << plInfo.name << '"' << std::endl;
×
1536
            file << "System info: " << log.addData << std::endl;
×
1537
            file << "\tChecksum: " << std::setw(0) << log.checksum << std::endl;
×
1538
        }
1539
        for(const AsyncLog& log : asyncLogs)
×
1540
            file << "Checksum " << std::setw(2) << unsigned(log.playerId) << std::setw(0) << ": " << log.checksum
×
1541
                 << std::endl;
×
1542

1543
        // print identical lines, they help in tracing the bug
1544
        for(unsigned i = 0; i < numIdentical; i++)
×
1545
            file << "[ I ]: " << asyncLogs[0].randEntries[i] << "\n";
×
1546
        for(unsigned i = numIdentical; i < numEntries; i++)
×
1547
        {
1548
            for(const AsyncLog& log : asyncLogs)
×
1549
            {
1550
                if(i < log.randEntries.size())
×
1551
                    file << "[C" << std::setw(2) << unsigned(log.playerId) << std::setw(0)
×
1552
                         << "]: " << log.randEntries[i] << '\n';
×
1553
            }
1554
        }
1555

1556
        LOG.write(_("Async log saved at %1%\n")) % filePath;
×
1557
        return filePath;
×
1558
    } else
1559
    {
1560
        LOG.write(_("Failed to save async log at %1%\n")) % filePath;
×
1561
        return "";
×
1562
    }
1563
}
1564

1565
void GameServer::SendAsyncLog(const bfs::path& asyncLogFilePath)
×
1566
{
1567
    if(SETTINGS.global.submit_debug_data == 1
×
1568
#ifdef _WIN32
1569
       || (MessageBoxW(nullptr,
1570
                       boost::nowide::widen(_("The game clients are out of sync. Would you like to send debug "
1571
                                              "information to RttR to help us avoiding this in "
1572
                                              "the future? Thank you very much!"))
1573
                         .c_str(),
1574
                       boost::nowide::widen(_("Error")).c_str(),
1575
                       MB_YESNO | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND)
1576
           == IDYES)
1577
#endif
1578
    )
1579
    {
1580
        DebugInfo di;
×
1581
        LOG.write(_("Sending async logs %1%.\n")) % (di.SendAsyncLog(asyncLogFilePath) ? "succeeded" : "failed");
×
1582

1583
        di.SendReplay();
×
1584
    }
1585
}
×
1586

1587
void GameServer::CheckAndSetColor(unsigned playerIdx, unsigned newColor)
×
1588
{
1589
    RTTR_Assert(playerIdx < playerInfos.size());
×
1590
    RTTR_Assert(playerInfos.size() <= PLAYER_COLORS.size()); // Else we may not find a valid color!
×
1591

1592
    JoinPlayerInfo& player = playerInfos[playerIdx];
×
1593
    RTTR_Assert(player.isUsed()); // Should only set colors for taken spots
×
1594

1595
    // Get colors used by other players
1596
    std::set<unsigned> takenColors;
×
1597
    for(unsigned p = 0; p < playerInfos.size(); ++p)
×
1598
    {
1599
        // Skip self
1600
        if(p == playerIdx)
×
1601
            continue;
×
1602

1603
        JoinPlayerInfo& otherPlayer = playerInfos[p];
×
1604
        if(otherPlayer.isUsed())
×
1605
            takenColors.insert(otherPlayer.color);
×
1606
    }
1607

1608
    // Look for a unique color
1609
    int newColorIdx = JoinPlayerInfo::GetColorIdx(newColor);
×
1610
    while(helpers::contains(takenColors, newColor))
×
1611
        newColor = PLAYER_COLORS[(++newColorIdx) % PLAYER_COLORS.size()];
×
1612

1613
    if(player.color == newColor)
×
1614
        return;
×
1615

1616
    player.color = newColor;
×
1617

1618
    SendToAll(GameMessage_Player_Color(playerIdx, player.color));
×
1619
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYER_TOGGLECOLOR(%d, %d)\n") % playerIdx % player.color;
×
1620
}
1621

1622
bool GameServer::OnGameMessage(const GameMessage_Player_Swap& msg)
×
1623
{
1624
    if(state != ServerState::Game && state != ServerState::Config)
×
1625
        return true;
×
1626
    int targetPlayer = GetTargetPlayer(msg);
×
1627
    if(targetPlayer < 0)
×
1628
        return true;
×
1629
    auto player1 = static_cast<uint8_t>(targetPlayer);
×
1630
    if(player1 == msg.player2 || msg.player2 >= playerInfos.size())
×
1631
        return true;
×
1632

1633
    SwapPlayer(player1, msg.player2);
×
1634
    return true;
×
1635
}
1636

1637
bool GameServer::OnGameMessage(const GameMessage_Player_SwapConfirm& msg)
×
1638
{
1639
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1640
    if(!player)
×
1641
        return true;
×
1642
    for(auto it = player->getPendingSwaps().begin(); it != player->getPendingSwaps().end(); ++it)
×
1643
    {
1644
        if(it->first == msg.player && it->second == msg.player2)
×
1645
        {
1646
            player->getPendingSwaps().erase(it);
×
1647
            break;
×
1648
        }
1649
    }
1650
    return true;
×
1651
}
1652

1653
void GameServer::SwapPlayer(const uint8_t player1, const uint8_t player2)
×
1654
{
1655
    // TODO: Swapping the player messes up the ids because our IDs are indizes. Usually this works because we use the
1656
    // sender player ID for messages received by the server and set the right ID for messages sent by the server.
1657
    // However (currently only) the host may send messages for another player. Those will not get the adjusted ID till
1658
    // he gets the swap message. So there is a short time, where the messages may be executed for the wrong player.
1659
    // Idea: Use actual IDs for players in messages (unique)
1660
    if(state == ServerState::Config)
×
1661
    {
1662
        // Swap player during match-making
1663
        // Swap everything
1664
        using std::swap;
1665
        swap(playerInfos[player1], playerInfos[player2]);
×
1666
        // In savegames some things cannot be changed
1667
        if(mapinfo.type == MapType::Savegame)
×
1668
            playerInfos[player1].FixSwappedSaveSlot(playerInfos[player2]);
×
1669
    } else if(state == ServerState::Game)
×
1670
    {
1671
        // Ingame we can only switch to a KI
1672
        if(playerInfos[player1].ps != PlayerState::Occupied || playerInfos[player2].ps != PlayerState::AI)
×
1673
            return;
×
1674

1675
        LOG.write("GameServer::ChangePlayer %i - %i \n") % unsigned(player1) % unsigned(player2);
×
1676
        using std::swap;
1677
        swap(playerInfos[player2].ps, playerInfos[player1].ps);
×
1678
        swap(playerInfos[player2].aiInfo, playerInfos[player1].aiInfo);
×
1679
        swap(playerInfos[player2].isHost, playerInfos[player1].isHost);
×
1680
    }
1681
    // Change ids of network players (if any). Get both first!
1682
    GameServerPlayer* newPlayer = GetNetworkPlayer(player2);
×
1683
    GameServerPlayer* oldPlayer = GetNetworkPlayer(player1);
×
1684
    if(newPlayer)
×
1685
        newPlayer->playerId = player1;
×
1686
    if(oldPlayer)
×
1687
        oldPlayer->playerId = player2;
×
1688
    SendToAll(GameMessage_Player_Swap(player1, player2));
×
1689
    const auto pSwap = std::make_pair(player1, player2);
×
1690
    for(GameServerPlayer& player : networkPlayers)
×
1691
    {
1692
        if(!player.isActive())
×
1693
            continue;
×
1694
        player.getPendingSwaps().push_back(pSwap);
×
1695
    }
1696
}
1697

1698
GameServerPlayer* GameServer::GetNetworkPlayer(unsigned playerId)
×
1699
{
1700
    for(GameServerPlayer& player : networkPlayers)
×
1701
    {
1702
        if(player.playerId == playerId)
×
1703
            return &player;
×
1704
    }
1705
    return nullptr;
×
1706
}
1707

1708
void GameServer::SetPaused(bool paused)
×
1709
{
1710
    if(framesinfo.isPaused == paused)
×
1711
        return;
×
1712
    framesinfo.isPaused = paused;
×
1713
    SendToAll(GameMessage_Pause(framesinfo.isPaused));
×
1714
    for(GameServerPlayer& player : networkPlayers)
×
1715
        player.setNotLagging();
×
1716
}
1717

1718
JoinPlayerInfo& GameServer::GetJoinPlayer(unsigned playerIdx)
×
1719
{
1720
    return playerInfos.at(playerIdx);
×
1721
}
1722

1723
bool GameServer::IsHost(unsigned playerIdx) const
×
1724
{
1725
    return playerIdx < playerInfos.size() && playerInfos[playerIdx].isHost;
×
1726
}
1727

1728
int GameServer::GetTargetPlayer(const GameMessageWithPlayer& msg)
×
1729
{
1730
    if(msg.player != 0xFF)
×
1731
    {
1732
        if(msg.player < playerInfos.size() && (msg.player == msg.senderPlayerID || IsHost(msg.senderPlayerID)))
×
1733
        {
1734
            GameServerPlayer* networkPlayer = GetNetworkPlayer(msg.senderPlayerID);
×
1735
            if(networkPlayer->isActive())
×
1736
                return msg.player;
×
1737
            unsigned result = msg.player;
×
1738
            // Apply pending swaps
1739
            for(auto& pSwap : networkPlayer->getPendingSwaps()) //-V522
×
1740
            {
1741
                if(pSwap.first == result)
×
1742
                    result = pSwap.second;
×
1743
                else if(pSwap.second == result)
×
1744
                    result = pSwap.first;
×
1745
            }
1746
            return result;
×
1747
        }
1748
    } else if(msg.senderPlayerID < playerInfos.size())
×
1749
        return msg.senderPlayerID;
×
1750
    return -1;
×
1751
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc