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

Return-To-The-Roots / s25client / 15644688224

13 Jun 2025 09:56PM UTC coverage: 50.481% (-0.007%) from 50.488%
15644688224

Pull #1771

github

web-flow
Merge c17631444 into 5cc1ddb3d
Pull Request #1771: Fix clang tidy on ci

42 of 53 new or added lines in 22 files covered. (79.25%)

4 existing lines in 1 file now uncovered.

22466 of 44504 relevant lines covered (50.48%)

35173.47 hits per line

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

4.65
/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 "liblobby/LobbyClient.h"
30
#include "libsiedler2/ArchivItem_Map.h"
31
#include "libsiedler2/ArchivItem_Map_Header.h"
32
#include "libsiedler2/prototypen.h"
33
#include "s25util/SocketSet.h"
34
#include "s25util/colors.h"
35
#include "s25util/utf8.h"
36
#include <boost/container/static_vector.hpp>
37
#include <boost/filesystem.hpp>
38
#include <boost/nowide/convert.hpp>
39
#include <boost/nowide/fstream.hpp>
40
#include <helpers/chronoIO.h>
41
#include <iomanip>
42
#include <iterator>
43
#include <mygettext/mygettext.h>
44

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

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

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

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

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

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

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

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

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

106
///////////////////////////////////////////////////////////////////////////////
107
//
108
GameServer::~GameServer()
×
109
{
110
    Stop();
×
111
}
×
112

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

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

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

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

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

157
            if(!save.Load(mapinfo.filepath, SaveGameDataToLoad::HeaderAndSettings))
×
158
                return false;
×
159

160
            // Spieleranzahl
161
            playerInfos.resize(save.GetNumPlayers());
×
162
            mapinfo.title = save.GetMapName();
×
163

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

172
            ggs_ = save.ggs;
×
173
            currentGF = save.start_gf;
×
174
        }
175
        break;
×
176
    }
177

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

184
    if(!mapinfo.mapData.CompressFromFile(mapinfo.filepath, &mapinfo.mapChecksum))
×
185
        return false;
×
186

187
    if(map.lua_path.has_value() && !bfs::is_regular_file(*map.lua_path))
×
188
        return false;
×
189

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

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

205
    // ab in die Konfiguration
206
    state = ServerState::Config;
×
207

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

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

225
    return true;
×
226
}
227

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

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

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

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

276
///////////////////////////////////////////////////////////////////////////////
277
// Hauptschleife
278
void GameServer::Run()
×
279
{
280
    if(state == ServerState::Stopped)
×
281
        return;
×
282

283
    // auf tote Clients prüfen
284
    ClientWatchDog();
×
285

286
    // auf neue Clients warten
287
    if(state == ServerState::Config)
×
288
        RunStateConfig();
×
289
    else if(state == ServerState::Loading)
×
290
        RunStateLoading();
×
291
    else if(state == ServerState::Game)
×
292
        RunStateGame();
×
293

294
    // post zustellen
295
    FillPlayerQueues();
×
296

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

315
    lanAnnouncer.Run();
×
316
}
317

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

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

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

381
    // And go!
382
    framesinfo.lastTime = FramesInfo::UsedClock::now();
×
383
    state = ServerState::Game;
×
384
}
385

386
void GameServer::RunStateGame()
×
387
{
388
    if(!framesinfo.isPaused)
×
389
        ExecuteGameFrame();
×
390
}
×
391

392
///////////////////////////////////////////////////////////////////////////////
393
// stoppt den server
394
void GameServer::Stop()
×
395
{
396
    if(state == ServerState::Stopped)
×
397
        return;
×
398

399
    // player verabschieden
400
    playerInfos.clear();
×
401
    networkPlayers.clear();
×
402

403
    // aufräumen
404
    framesinfo.Clear();
×
405
    config.Clear();
×
406
    mapinfo.Clear();
×
407
    countdown.Stop();
×
408

409
    // laden dicht machen
410
    serversocket.Close();
×
411
    // clear jump target
412
    skiptogf = 0;
×
413

414
    // clear async logs
415
    asyncLogs.clear();
×
416

417
    lanAnnouncer.Stop();
×
418

419
    if(LOBBYCLIENT.IsLoggedIn()) // steht die Lobbyverbindung noch?
×
420
        LOBBYCLIENT.DeleteServer();
×
421
    LOBBYCLIENT.RemoveListener(this);
×
422

423
    // status
424
    state = ServerState::Stopped;
×
425
    LOG.write("server state changed to stop\n");
×
426
}
427

428
// Check if there are players that have not been assigned a team but only a random team.
429
// Those players are assigned a team now optionally trying to balance the number of players per team.
430
// Returns true iff players have been assigned.
431
bool GameServer::assignPlayersOfRandomTeams(std::vector<JoinPlayerInfo>& playerInfos)
26✔
432
{
433
    static_assert(NUM_TEAMS == 4, "Expected exactly 4 playable teams!");
434
    RTTR_Assert(playerInfos.size() <= MAX_PLAYERS);
26✔
435

436
    using boost::container::static_vector;
437
    using PlayerIndex = unsigned;
438
    using TeamIndex = unsigned;
439
    const auto teamIdxToTeam = [](const TeamIndex teamNum) {
85✔
440
        RTTR_Assert(teamNum < NUM_TEAMS);
85✔
441
        return Team(static_cast<TeamIndex>(Team::Team1) + teamNum);
85✔
442
    };
443

444
    std::array<unsigned, NUM_TEAMS> numPlayersInTeam{};
26✔
445
    struct AssignPlayer
446
    {
447
        PlayerIndex player;
448
        static_vector<TeamIndex, NUM_TEAMS> possibleTeams;
449
        TeamIndex chosenTeam = 0;
450
    };
451

452
    static_vector<AssignPlayer, MAX_PLAYERS> playersToAssign;
×
453
    auto rng = helpers::getRandomGenerator();
26✔
454

455
    bool playerWasAssigned = false;
26✔
456

457
    // Assign (fully) random teams, count players in team and sort into playersToAssign
458
    for(PlayerIndex player = 0; player < playerInfos.size(); ++player)
170✔
459
    {
460
        auto& playerInfo = playerInfos[player];
144✔
461
        if(playerInfo.team == Team::Random)
144✔
462
        {
463
            const TeamIndex randTeam = std::uniform_int_distribution<TeamIndex>{0, NUM_TEAMS - 1u}(rng);
2✔
464
            playerInfo.team = teamIdxToTeam(randTeam);
2✔
465
            playerWasAssigned = true;
2✔
466
        }
467
        switch(playerInfo.team)
144✔
468
        {
469
            case Team::Team1: ++numPlayersInTeam[0]; break;
27✔
470
            case Team::Team2: ++numPlayersInTeam[1]; break;
8✔
471
            case Team::Team3: ++numPlayersInTeam[2]; break;
21✔
472
            case Team::Team4: ++numPlayersInTeam[3]; break;
3✔
473
            case Team::Random1To2: playersToAssign.emplace_back(AssignPlayer{player, {0, 1}}); break;
63✔
474
            case Team::Random1To3: playersToAssign.emplace_back(AssignPlayer{player, {0, 1, 2}}); break;
144✔
475
            case Team::Random1To4: playersToAssign.emplace_back(AssignPlayer{player, {0, 1, 2, 3}}); break;
42✔
476
            case Team::Random: RTTR_Assert(false); break;
×
477
            case Team::None: break;
2✔
478
        }
479
    }
480

481
    // To make the teams as even as possible we start to assign the most constrained players first
482
    std::sort(playersToAssign.begin(), playersToAssign.end(), [](const AssignPlayer& lhs, const AssignPlayer& rhs) {
26✔
483
        return lhs.possibleTeams.size() < rhs.possibleTeams.size();
378✔
484
    });
485

486
    // Put each player into a random team with the currently least amount of players using the possible teams only
487
    for(AssignPlayer& player : playersToAssign)
244✔
488
    {
489
        // Determine the teams with the minima size for the currently possible teams and choose one randomly
490
        unsigned minNextTeamSize = std::numeric_limits<unsigned>::max();
83✔
491
        static_vector<TeamIndex, NUM_TEAMS> teamsForNextPlayer;
×
492
        for(const TeamIndex team : player.possibleTeams)
733✔
493
        {
494
            if(minNextTeamSize > numPlayersInTeam[team])
242✔
495
            {
496
                teamsForNextPlayer.clear();
497
                teamsForNextPlayer.push_back(team);
498
                minNextTeamSize = numPlayersInTeam[team];
120✔
499
            } else if(minNextTeamSize == numPlayersInTeam[team])
122✔
500
                teamsForNextPlayer.push_back(team);
501
        }
502
        player.chosenTeam = helpers::getRandomElement(rng, teamsForNextPlayer);
83✔
503

504
        ++numPlayersInTeam[player.chosenTeam];
83✔
505
        playerWasAssigned = true;
83✔
506
    }
507
    // Now the teams are as even as possible and the uneven team(s) is a random one within the constraints
508
    // To have some more randomness we swap players within their constraints
509
    std::shuffle(playersToAssign.begin(), playersToAssign.end(), rng);
26✔
510
    for(auto it = playersToAssign.begin(); it != playersToAssign.end(); ++it)
192✔
511
    {
512
        // Search for a random player with which we can swap, including ourselfes
513
        // Go only forward to avoid back-swapping
514
        static_vector<decltype(it), MAX_PLAYERS> possibleSwapTargets;
×
515
        for(auto it2 = it; it2 != playersToAssign.end(); ++it2)
507✔
516
        {
517
            if(helpers::contains(it->possibleTeams, it2->chosenTeam)
424✔
518
               && helpers::contains(it2->possibleTeams, it->chosenTeam))
608✔
519
                possibleSwapTargets.push_back(it2);
520
        }
521
        const auto itSwapTarget = helpers::getRandomElement(rng, possibleSwapTargets);
83✔
522
        std::swap(it->chosenTeam, itSwapTarget->chosenTeam);
166✔
523
        playerInfos[it->player].team = teamIdxToTeam(it->chosenTeam);
166✔
524
    }
525

526
    return playerWasAssigned;
52✔
527
}
528

529
/**
530
 *  startet das Spiel.
531
 */
532
bool GameServer::StartGame()
×
533
{
534
    lanAnnouncer.Stop();
×
535

536
    // Finalize the team selection for unassigned players.
537
    if(assignPlayersOfRandomTeams(playerInfos))
×
538
        SendToAll(GameMessage_Player_List(playerInfos));
×
539

540
    // Bei Savegames wird der Startwert von den Clients aus der Datei gelesen!
541
    unsigned random_init;
542
    if(mapinfo.type == MapType::Savegame)
×
543
        random_init = 0;
×
544
    else
545
        random_init = static_cast<unsigned>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
×
546

547
    nwfInfo.init(currentGF, 3);
×
548

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

553
    // Höchsten Ping ermitteln
554
    unsigned highest_ping = 0;
×
555
    for(const JoinPlayerInfo& player : playerInfos)
×
556
    {
557
        if(player.ps == PlayerState::Occupied)
×
558
        {
559
            if(player.ping > highest_ping)
×
560
                highest_ping = player.ping;
×
561
        }
562
    }
563

564
    framesinfo.gfLengthReq = framesinfo.gf_length = SPEED_GF_LENGTHS[ggs_.speed];
×
565

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

569
    LOG.write("SERVER: Using gameframe length of %1%\n") % helpers::withUnit(framesinfo.gf_length);
×
570
    LOG.write("SERVER: Using networkframe length of %1% GFs (%2%)\n") % framesinfo.nwf_length
×
571
      % helpers::withUnit(framesinfo.nwf_length * framesinfo.gf_length);
×
572

573
    for(unsigned id = 0; id < playerInfos.size(); id++)
×
574
    {
575
        if(playerInfos[id].isUsed())
×
576
            nwfInfo.addPlayer(id);
×
577
    }
578

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

584
    state = ServerState::Loading;
×
585
    loadStartTime = SteadyClock::now();
×
586

587
    return true;
×
588
}
589

590
unsigned GameServer::CalcNWFLenght(FramesInfo::milliseconds32_t minDuration) const
×
591
{
592
    constexpr unsigned maxNumGF = 20;
×
593
    for(unsigned i = 1; i < maxNumGF; ++i)
×
594
    {
595
        if(i * framesinfo.gf_length >= minDuration)
×
596
            return i;
×
597
    }
598
    return maxNumGF;
×
599
}
600

601
void GameServer::SendNWFDone(const NWFServerInfo& info)
×
602
{
603
    nwfInfo.addServerInfo(info);
×
604
    SendToAll(GameMessage_Server_NWFDone(info.gf, info.newGFLen, info.nextNWF));
×
605
}
×
606

607
/**
608
 *  Nachricht an Alle
609
 */
610
void GameServer::SendToAll(const GameMessage& msg)
×
611
{
612
    for(GameServerPlayer& player : networkPlayers)
×
613
    {
614
        // ist der Slot Belegt, dann Nachricht senden
615
        if(player.isActive())
×
616
            player.sendMsgAsync(msg.clone());
×
617
    }
618
}
×
619

620
void GameServer::KickPlayer(uint8_t playerId, KickReason cause, uint32_t param)
×
621
{
622
    if(playerId >= playerInfos.size())
×
623
        return;
×
624
    JoinPlayerInfo& playerInfo = playerInfos[playerId];
×
625
    GameServerPlayer* player = GetNetworkPlayer(playerId);
×
626
    if(player)
×
627
        player->closeConnection();
×
628
    // Non-existing or connecting player
629
    if(!playerInfo.isUsed())
×
630
        return;
×
631
    playerInfo.ps = PlayerState::Free;
×
632

633
    SendToAll(GameMessage_Player_Kicked(playerId, cause, param));
×
634

635
    // If we are ingame, replace by KI
636
    if(state == ServerState::Game || state == ServerState::Loading)
×
637
    {
638
        playerInfo.ps = PlayerState::AI;
×
639
        playerInfo.aiInfo = AI::Info(AI::Type::Dummy);
×
640
    } else
641
        CancelCountdown();
×
642

643
    AnnounceStatusChange();
×
644
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYERKICKED(%d,%d,%d)\n") % unsigned(playerId) % unsigned(cause)
×
645
      % unsigned(param);
×
646
}
647

648
///////////////////////////////////////////////////////////////////////////////
649
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
650
void GameServer::ClientWatchDog()
×
651
{
652
    SocketSet set;
×
653
    set.Clear();
×
654

655
    // sockets zum set hinzufügen
656
    for(GameServerPlayer& player : networkPlayers)
×
657
        set.Add(player.socket);
×
658

659
    // auf fehler prüfen
660
    if(set.Select(0, 2) > 0)
×
661
    {
662
        for(const GameServerPlayer& player : networkPlayers)
×
663
        {
664
            if(set.InSet(player.socket))
×
665
            {
666
                LOG.write(_("SERVER: Error on socket of player %1%, bye bye!\n")) % player.playerId;
×
667
                KickPlayer(player.playerId, KickReason::ConnectionLost, __LINE__);
×
668
            }
669
        }
670
    }
671

672
    for(GameServerPlayer& player : networkPlayers)
×
673
    {
674
        if(player.hasTimedOut())
×
675
        {
676
            LOG.write(_("SERVER: Reserved slot %1% freed due to timeout\n")) % player.playerId;
×
677
            KickPlayer(player.playerId, KickReason::PingTimeout, __LINE__);
×
678
        } else
679
            player.doPing();
×
680
    }
681
}
×
682

683
void GameServer::ExecuteGameFrame()
×
684
{
685
    RTTR_Assert(state == ServerState::Game);
×
686

687
    FramesInfo::UsedClock::time_point currentTime = FramesInfo::UsedClock::now();
×
688
    FramesInfo::milliseconds32_t passedTime =
689
      std::chrono::duration_cast<FramesInfo::milliseconds32_t>(currentTime - framesinfo.lastTime);
×
690

691
    // prüfen ob GF vergangen
692
    if(passedTime >= framesinfo.gf_length || skiptogf > currentGF)
×
693
    {
694
        // NWF vergangen?
695
        if(currentGF == nwfInfo.getNextNWF())
×
696
        {
697
            if(CheckForLaggingPlayers())
×
698
            {
699
                // Check for kicking every second
700
                static FramesInfo::UsedClock::time_point lastLagKickTime;
701
                if(currentTime - lastLagKickTime >= std::chrono::seconds(1))
×
702
                {
703
                    lastLagKickTime = currentTime;
×
704
                    CheckAndKickLaggingPlayers();
×
705
                }
706
                // Skip the rest
707
                return;
×
708
            } else
709
                ExecuteNWF();
×
710
        }
711
        // Advance GF
712
        ++currentGF;
×
713
        // Normally we set lastTime = curTime (== lastTime + passedTime) where passedTime is ideally 1 GF
714
        // 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
715
        // bit earlier. Exception: We lag many GFs behind, then we advance by the full passedTime - 1 GF which means we
716
        // are now only 1 GF behind and execute that on the next call
717
        if(passedTime <= 4 * framesinfo.gf_length)
×
718
            passedTime = framesinfo.gf_length;
×
719
        else
720
            passedTime -= framesinfo.gf_length;
×
721
        framesinfo.lastTime += passedTime;
×
722
    }
723
}
724

725
void GameServer::ExecuteNWF()
×
726
{
727
    // Check for asyncs
728
    if(CheckForAsync())
×
729
    {
730
        // Pause game
731
        RTTR_Assert(!framesinfo.isPaused);
×
732
        SetPaused(true);
×
733

734
        // Notify players
735
        std::vector<unsigned> checksumHashes;
×
NEW
736
        checksumHashes.reserve(networkPlayers.size());
×
737
        for(const GameServerPlayer& player : networkPlayers)
×
738
            checksumHashes.push_back(nwfInfo.getPlayerCmds(player.playerId).checksum.getHash());
×
739
        SendToAll(GameMessage_Server_Async(checksumHashes));
×
740

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

774
bool GameServer::CheckForAsync()
×
775
{
776
    if(networkPlayers.empty())
×
777
        return false;
×
778
    bool isAsync = false;
×
779
    const AsyncChecksum& refChecksum = nwfInfo.getPlayerCmds(networkPlayers.front().playerId).checksum;
×
780
    for(const GameServerPlayer& player : networkPlayers)
×
781
    {
782
        const AsyncChecksum& curChecksum = nwfInfo.getPlayerCmds(player.playerId).checksum;
×
783

784
        // Checksummen nicht gleich?
785
        if(curChecksum != refChecksum)
×
786
        {
787
            LOG.write(_("Async at GF %1% of player %2% vs %3%. Checksums:\n%4%\n%5%\n\n")) % currentGF % player.playerId
×
788
              % networkPlayers.front().playerId % curChecksum % refChecksum;
×
789
            isAsync = true;
×
790
        }
791
    }
792
    return isAsync;
×
793
}
794

795
void GameServer::CheckAndKickLaggingPlayers()
×
796
{
797
    for(const GameServerPlayer& player : networkPlayers)
×
798
    {
799
        const unsigned timeOut = player.getLagTimeOut();
×
800
        if(timeOut == 0)
×
801
            KickPlayer(player.playerId, KickReason::PingTimeout, __LINE__);
×
802
        else if(timeOut <= 30
×
803
                && (timeOut % 5 == 0
×
804
                    || timeOut < 5)) // Notify every 5s if max 30s are remaining, if less than 5s notify every second
×
805
            LOG.write(_("SERVER: Kicking player %1% in %2% seconds\n")) % player.playerId % timeOut;
×
806
    }
807
}
×
808

809
bool GameServer::CheckForLaggingPlayers()
×
810
{
811
    if(nwfInfo.isReady())
×
812
        return false;
×
813
    for(GameServerPlayer& player : networkPlayers)
×
814
    {
815
        if(nwfInfo.getPlayerInfo(player.playerId).isLagging)
×
816
            player.setLagging();
×
817
    }
818
    return true;
×
819
}
820

821
///////////////////////////////////////////////////////////////////////////////
822
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
823
void GameServer::WaitForClients()
×
824
{
825
    SocketSet set;
×
826

827
    set.Add(serversocket);
×
828
    if(set.Select(0, 0) > 0)
×
829
    {
830
        RTTR_Assert(set.InSet(serversocket));
×
831
        Socket socket = serversocket.Accept();
×
832

833
        // Verbindung annehmen
834
        if(!socket.isValid())
×
835
            return;
×
836

837
        unsigned newPlayerId = GameMessageWithPlayer::NO_PLAYER_ID;
×
838
        // Geeigneten Platz suchen
839
        for(unsigned playerId = 0; playerId < playerInfos.size(); ++playerId)
×
840
        {
841
            if(playerInfos[playerId].ps == PlayerState::Free && !GetNetworkPlayer(playerId))
×
842
            {
843
                networkPlayers.push_back(GameServerPlayer(playerId, socket));
×
844
                newPlayerId = playerId;
×
845
                break;
×
846
            }
847
        }
848

849
        GameMessage_Player_Id msg(newPlayerId);
×
850
        MessageHandler::send(socket, msg);
×
851

852
        // war kein platz mehr frei, wenn ja dann verbindung trennen?
853
        if(newPlayerId == 0xFFFFFFFF)
×
854
            socket.Close();
×
855
    }
856
}
857

858
///////////////////////////////////////////////////////////////////////////////
859
// füllt die warteschlangen mit "paketen"
860
void GameServer::FillPlayerQueues()
×
861
{
862
    SocketSet set;
×
863
    bool msgReceived = false;
×
864

865
    // erstmal auf Daten überprüfen
866
    do
×
867
    {
868
        // sockets zum set hinzufügen
869
        for(const GameServerPlayer& player : networkPlayers)
×
870
            set.Add(player.socket);
×
871

872
        msgReceived = false;
×
873

874
        // ist eines der Sockets im Set lesbar?
875
        if(set.Select(0, 0) > 0)
×
876
        {
877
            for(GameServerPlayer& player : networkPlayers)
×
878
            {
879
                if(set.InSet(player.socket))
×
880
                {
881
                    // nachricht empfangen
882
                    if(!player.receiveMsgs())
×
883
                    {
884
                        LOG.write(_("SERVER: Receiving Message for player %1% failed, kicking...\n")) % player.playerId;
×
885
                        KickPlayer(player.playerId, KickReason::ConnectionLost, __LINE__);
×
886
                    } else
887
                        msgReceived = true;
×
888
                }
889
            }
890
        }
891
    } while(msgReceived);
892
}
×
893

894
///////////////////////////////////////////////////////////////////////////////
895
// pongnachricht
896
bool GameServer::OnGameMessage(const GameMessage_Pong& msg)
×
897
{
898
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
899
    if(player)
×
900
    {
901
        unsigned ping = player->calcPingTime();
×
902
        if(ping == 0u)
×
903
            return true;
×
904
        playerInfos[msg.senderPlayerID].ping = ping;
×
905
        SendToAll(GameMessage_Player_Ping(msg.senderPlayerID, ping));
×
906
    }
907
    return true;
×
908
}
909

910
///////////////////////////////////////////////////////////////////////////////
911
// servertype
912
bool GameServer::OnGameMessage(const GameMessage_Server_Type& msg)
×
913
{
914
    if(state != ServerState::Config)
×
915
    {
916
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
917
        return true;
×
918
    }
919

920
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
921
    if(!player)
×
922
        return true;
×
923

924
    auto typeok = GameMessage_Server_TypeOK::StatusCode::Ok;
×
925
    if(msg.type != config.servertype)
×
926
        typeok = GameMessage_Server_TypeOK::StatusCode::InvalidServerType;
×
927
    else if(msg.revision != rttr::version::GetRevision())
×
928
        typeok = GameMessage_Server_TypeOK::StatusCode::WrongVersion;
×
929

930
    player->sendMsg(GameMessage_Server_TypeOK(typeok, rttr::version::GetRevision()));
×
931

932
    if(typeok != GameMessage_Server_TypeOK::StatusCode::Ok)
×
933
        KickPlayer(msg.senderPlayerID, KickReason::ConnectionLost, __LINE__);
×
934
    return true;
×
935
}
936

937
/**
938
 *  Server-Passwort-Nachricht
939
 */
940
bool GameServer::OnGameMessage(const GameMessage_Server_Password& msg)
×
941
{
942
    if(state != ServerState::Config)
×
943
    {
944
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
945
        return true;
×
946
    }
947

948
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
949
    if(!player)
×
950
        return true;
×
951

952
    std::string passwordok = (config.password == msg.password ? "true" : "false");
×
953
    if(msg.password == config.hostPassword)
×
954
    {
955
        passwordok = "true";
×
956
        playerInfos[msg.senderPlayerID].isHost = true;
×
957
    } else
958
        playerInfos[msg.senderPlayerID].isHost = false;
×
959

960
    player->sendMsgAsync(new GameMessage_Server_Password(passwordok));
×
961

962
    if(passwordok == "false")
×
963
        KickPlayer(msg.senderPlayerID, KickReason::WrongPassword, __LINE__);
×
964
    return true;
×
965
}
966

967
/**
968
 *  Chat-Nachricht.
969
 */
970
bool GameServer::OnGameMessage(const GameMessage_Chat& msg)
×
971
{
972
    int playerID = GetTargetPlayer(msg);
×
973
    if(playerID >= 0)
×
974
        SendToAll(GameMessage_Chat(playerID, msg.destination, msg.text));
×
975
    return true;
×
976
}
977

978
bool GameServer::OnGameMessage(const GameMessage_Player_State& msg)
×
979
{
980
    if(state != ServerState::Config)
×
981
    {
982
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
983
        return true;
×
984
    }
985
    // Can't do this. Have to have a joined player
986
    if(msg.ps == PlayerState::Occupied)
×
987
        return true;
×
988

989
    int playerID = GetTargetPlayer(msg);
×
990
    if(playerID < 0)
×
991
        return true;
×
992
    JoinPlayerInfo& player = playerInfos[playerID];
×
993
    const PlayerState oldPs = player.ps;
×
994
    // Can't change self
995
    if(playerID != msg.senderPlayerID)
×
996
    {
997
        // oh ein spieler, weg mit ihm!
998
        if(GetNetworkPlayer(playerID))
×
999
            KickPlayer(playerID, KickReason::NoCause, __LINE__);
×
1000

1001
        if(mapinfo.type == MapType::Savegame)
×
1002
        {
1003
            // For savegames we cannot set anyone on a locked slot as the player does not exist on the map
1004
            if(player.ps != PlayerState::Locked)
×
1005
            {
1006
                // And we don't lock!
1007
                player.ps = msg.ps == PlayerState::Locked ? PlayerState::Free : msg.ps;
×
1008
                player.aiInfo = msg.aiInfo;
×
1009
            }
1010
        } else
1011
        {
1012
            player.ps = msg.ps;
×
1013
            player.aiInfo = msg.aiInfo;
×
1014
        }
1015
        if(player.ps == PlayerState::Free && config.servertype == ServerType::Local)
×
1016
        {
1017
            player.ps = PlayerState::AI;
×
1018
            player.aiInfo = AI::Info(AI::Type::Default);
×
1019
        }
1020
    }
1021
    // Even when nothing changed we send the data because the other players might have expected a change
1022

1023
    if(player.ps == PlayerState::AI)
×
1024
    {
1025
        player.SetAIName(playerID);
×
1026
        SendToAll(GameMessage_Player_Name(playerID, player.name));
×
1027
    }
1028
    // If slot is filled, check current color
1029
    if(player.isUsed())
×
1030
        CheckAndSetColor(playerID, player.color);
×
1031
    SendToAll(GameMessage_Player_State(playerID, player.ps, player.aiInfo));
×
1032

1033
    if(oldPs != player.ps)
×
1034
        player.isReady = (player.ps == PlayerState::AI);
×
1035
    SendToAll(GameMessage_Player_Ready(playerID, player.isReady));
×
1036
    PlayerDataChanged(playerID);
×
1037
    AnnounceStatusChange();
×
1038
    return true;
×
1039
}
1040

1041
///////////////////////////////////////////////////////////////////////////////
1042
// Spielername
1043
bool GameServer::OnGameMessage(const GameMessage_Player_Name& msg)
×
1044
{
1045
    if(state != ServerState::Config)
×
1046
    {
1047
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1048
        return true;
×
1049
    }
1050
    int playerID = GetTargetPlayer(msg);
×
1051
    if(playerID < 0)
×
1052
        return true;
×
1053

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

1056
    playerInfos[playerID].name = msg.playername;
×
1057
    SendToAll(GameMessage_Player_Name(playerID, msg.playername));
×
1058
    PlayerDataChanged(playerID);
×
1059

1060
    return true;
×
1061
}
1062

1063
///////////////////////////////////////////////////////////////////////////////
1064
// Nation weiterwechseln
1065
bool GameServer::OnGameMessage(const GameMessage_Player_Nation& msg)
×
1066
{
1067
    if(state != ServerState::Config)
×
1068
    {
1069
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1070
        return true;
×
1071
    }
1072
    int playerID = GetTargetPlayer(msg);
×
1073
    if(playerID < 0)
×
1074
        return true;
×
1075

1076
    playerInfos[playerID].nation = msg.nation;
×
1077

1078
    SendToAll(GameMessage_Player_Nation(playerID, msg.nation));
×
1079
    PlayerDataChanged(playerID);
×
1080
    return true;
×
1081
}
1082

1083
///////////////////////////////////////////////////////////////////////////////
1084
// Team weiterwechseln
1085
bool GameServer::OnGameMessage(const GameMessage_Player_Team& msg)
×
1086
{
1087
    if(state != ServerState::Config)
×
1088
    {
1089
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1090
        return true;
×
1091
    }
1092
    int playerID = GetTargetPlayer(msg);
×
1093
    if(playerID < 0)
×
1094
        return true;
×
1095

1096
    playerInfos[playerID].team = msg.team;
×
1097

1098
    SendToAll(GameMessage_Player_Team(playerID, msg.team));
×
1099
    PlayerDataChanged(playerID);
×
1100
    return true;
×
1101
}
1102

1103
///////////////////////////////////////////////////////////////////////////////
1104
// Farbe weiterwechseln
1105
bool GameServer::OnGameMessage(const GameMessage_Player_Color& msg)
×
1106
{
1107
    if(state != ServerState::Config)
×
1108
    {
1109
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1110
        return true;
×
1111
    }
1112
    int playerID = GetTargetPlayer(msg);
×
1113
    if(playerID < 0)
×
1114
        return true;
×
1115

1116
    CheckAndSetColor(playerID, msg.color);
×
1117
    PlayerDataChanged(playerID);
×
1118
    return true;
×
1119
}
1120

1121
/**
1122
 *  Spielerstatus wechseln
1123
 */
1124
bool GameServer::OnGameMessage(const GameMessage_Player_Ready& msg)
×
1125
{
1126
    if(state != ServerState::Config)
×
1127
    {
1128
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1129
        return true;
×
1130
    }
1131
    int playerID = GetTargetPlayer(msg);
×
1132
    if(playerID < 0)
×
1133
        return true;
×
1134

1135
    JoinPlayerInfo& player = playerInfos[playerID];
×
1136

1137
    player.isReady = msg.ready;
×
1138

1139
    // countdown ggf abbrechen
1140
    if(!player.isReady && countdown.IsActive())
×
1141
        CancelCountdown();
×
1142

1143
    SendToAll(GameMessage_Player_Ready(playerID, msg.ready));
×
1144
    return true;
×
1145
}
1146

1147
bool GameServer::OnGameMessage(const GameMessage_MapRequest& msg)
×
1148
{
1149
    if(state != ServerState::Config)
×
1150
    {
1151
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1152
        return true;
×
1153
    }
1154
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1155
    if(!player)
×
1156
        return true;
×
1157

1158
    if(msg.requestInfo)
×
1159
    {
1160
        player->sendMsgAsync(new GameMessage_Map_Info(mapinfo.filepath.filename().string(), mapinfo.type,
×
1161
                                                      mapinfo.mapData.uncompressedLength, mapinfo.mapData.data.size(),
×
1162
                                                      mapinfo.luaData.uncompressedLength, mapinfo.luaData.data.size()));
×
1163
    } else if(player->isMapSending())
×
1164
    {
1165
        // Don't send again
1166
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1167
    } else
1168
    {
1169
        // Send map data
1170
        unsigned curPos = 0;
×
1171
        unsigned remainingSize = mapinfo.mapData.data.size();
×
1172
        while(remainingSize)
×
1173
        {
1174
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1175

1176
            player->sendMsgAsync(new GameMessage_Map_Data(true, curPos, &mapinfo.mapData.data[curPos], chunkSize));
×
1177
            curPos += chunkSize;
×
1178
            remainingSize -= chunkSize;
×
1179
        }
1180

1181
        // And lua data (if there is any)
1182
        RTTR_Assert(mapinfo.luaFilepath.empty() == mapinfo.luaData.data.empty());
×
1183
        RTTR_Assert(mapinfo.luaData.data.empty() == (mapinfo.luaData.uncompressedLength == 0));
×
1184
        curPos = 0;
×
1185
        remainingSize = mapinfo.luaData.data.size();
×
1186
        while(remainingSize)
×
1187
        {
1188
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1189

1190
            player->sendMsgAsync(new GameMessage_Map_Data(false, curPos, &mapinfo.luaData.data[curPos], chunkSize));
×
1191
            curPos += chunkSize;
×
1192
            remainingSize -= chunkSize;
×
1193
        }
1194
        // estimate time. max 60 chunks/s (currently limited by framerate), assume 50 (~25kb/s)
1195
        auto numChunks = (mapinfo.mapData.data.size() + mapinfo.luaData.data.size()) / MAP_PART_SIZE;
×
1196
        player->setMapSending(std::chrono::seconds(numChunks / 50 + 1));
×
1197
    }
1198
    return true;
×
1199
}
1200

1201
bool GameServer::OnGameMessage(const GameMessage_Map_Checksum& msg)
×
1202
{
1203
    if(state != ServerState::Config)
×
1204
    {
1205
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1206
        return true;
×
1207
    }
1208
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1209
    if(!player)
×
1210
        return true;
×
1211

1212
    bool checksumok = (msg.mapChecksum == mapinfo.mapChecksum && msg.luaChecksum == mapinfo.luaChecksum);
×
1213

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

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

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

1222
    if(!checksumok)
×
1223
    {
1224
        if(player->isMapSending())
×
1225
            KickPlayer(msg.senderPlayerID, KickReason::WrongChecksum, __LINE__);
×
1226
    } else
1227
    {
1228
        JoinPlayerInfo& playerInfo = playerInfos[msg.senderPlayerID];
×
1229
        // Used? Then we got this twice or some error happened. Remove him
1230
        if(playerInfo.isUsed())
×
1231
            KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1232
        else
1233
        {
1234
            // Inform others about a new player
1235
            SendToAll(GameMessage_Player_New(msg.senderPlayerID, playerInfo.name));
×
1236

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

1240
            // Mark as used and assign a unique color
1241
            // Do this before sending the player list to avoid sending useless updates
1242
            playerInfo.ps = PlayerState::Occupied;
×
1243
            CheckAndSetColor(msg.senderPlayerID, playerInfo.color);
×
1244

1245
            // Send remaining data and mark as active
1246
            player->sendMsgAsync(new GameMessage_Server_Name(config.gamename));
×
1247
            player->sendMsgAsync(new GameMessage_Player_List(playerInfos));
×
1248
            player->sendMsgAsync(new GameMessage_GGSChange(ggs_));
×
1249
            player->setActive();
×
1250
        }
1251
        AnnounceStatusChange();
×
1252
    }
1253
    return true;
×
1254
}
1255

1256
// speed change message
1257
bool GameServer::OnGameMessage(const GameMessage_Speed& msg)
×
1258
{
1259
    if(state != ServerState::Game)
×
1260
    {
1261
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1262
        return true;
×
1263
    }
1264
    framesinfo.gfLengthReq = FramesInfo::milliseconds32_t(msg.gf_length);
×
1265
    return true;
×
1266
}
1267

1268
bool GameServer::OnGameMessage(const GameMessage_GameCommand& msg)
×
1269
{
1270
    int targetPlayerId = GetTargetPlayer(msg);
×
1271
    if((state != ServerState::Game && state != ServerState::Loading) || targetPlayerId < 0
×
1272
       || (state == ServerState::Loading && !msg.cmds.gcs.empty()))
×
1273
    {
1274
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1275
        return true;
×
1276
    }
1277

1278
    if(!nwfInfo.addPlayerCmds(targetPlayerId, msg.cmds))
×
1279
        return true; // Ignore
×
1280
    GameServerPlayer* player = GetNetworkPlayer(targetPlayerId);
×
1281
    if(player)
×
1282
        player->setNotLagging();
×
1283
    SendToAll(GameMessage_GameCommand(targetPlayerId, msg.cmds.checksum, msg.cmds.gcs));
×
1284

1285
    return true;
×
1286
}
1287

1288
bool GameServer::OnGameMessage(const GameMessage_AsyncLog& msg)
×
1289
{
1290
    if(state != ServerState::Game)
×
1291
    {
1292
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1293
        return true;
×
1294
    }
1295
    bool foundPlayer = false;
×
1296
    for(AsyncLog& log : asyncLogs)
×
1297
    {
1298
        if(log.playerId != msg.senderPlayerID)
×
1299
            continue;
×
1300
        RTTR_Assert(!log.done);
×
1301
        if(log.done)
×
1302
            return true;
×
1303
        foundPlayer = true;
×
1304
        log.addData += msg.addData;
×
1305
        log.randEntries.insert(log.randEntries.end(), msg.entries.begin(), msg.entries.end());
×
1306
        if(msg.last)
×
1307
        {
1308
            LOG.write(_("Received async logs from %1% (%2% entries).\n")) % unsigned(log.playerId)
×
1309
              % log.randEntries.size();
×
1310
            log.done = true;
×
1311
        }
1312
    }
1313
    if(!foundPlayer)
×
1314
    {
1315
        LOG.write(_("Received async log from %1%, but did not expect it!\n")) % unsigned(msg.senderPlayerID);
×
1316
        return true;
×
1317
    }
1318

1319
    // Check if we have all logs
1320
    for(const AsyncLog& log : asyncLogs)
×
1321
    {
1322
        if(!log.done)
×
1323
            return true;
×
1324
    }
1325

1326
    LOG.write(_("Async logs received completely.\n"));
×
1327

1328
    const bfs::path asyncFilePath = SaveAsyncLog();
×
1329
    if(!asyncFilePath.empty())
×
1330
        SendAsyncLog(asyncFilePath);
×
1331

1332
    // Kick all players that have a different checksum from the host
1333
    AsyncChecksum hostChecksum;
×
1334
    for(const AsyncLog& log : asyncLogs)
×
1335
    {
1336
        if(playerInfos.at(log.playerId).isHost)
×
1337
        {
1338
            hostChecksum = log.checksum;
×
1339
            break;
×
1340
        }
1341
    }
1342
    for(const AsyncLog& log : asyncLogs)
×
1343
    {
1344
        if(log.checksum != hostChecksum)
×
1345
            KickPlayer(log.playerId, KickReason::Async, __LINE__);
×
1346
    }
1347
    return true;
×
1348
}
1349

1350
bool GameServer::OnGameMessage(const GameMessage_RemoveLua& msg)
×
1351
{
1352
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1353
    {
1354
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1355
        return true;
×
1356
    }
1357
    mapinfo.luaFilepath.clear();
×
1358
    mapinfo.luaData.Clear();
×
1359
    mapinfo.luaChecksum = 0;
×
1360
    SendToAll(msg);
×
1361
    CancelCountdown();
×
1362
    return true;
×
1363
}
1364

1365
bool GameServer::OnGameMessage(const GameMessage_Countdown& msg)
×
1366
{
1367
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1368
    {
1369
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1370
        return true;
×
1371
    }
1372

1373
    NetworkPlayer* nwPlayer = GetNetworkPlayer(msg.senderPlayerID);
×
1374
    if(!nwPlayer || countdown.IsActive())
×
1375
        return true;
×
1376

1377
    if(!ArePlayersReady())
×
1378
        nwPlayer->sendMsgAsync(new GameMessage_CancelCountdown(true));
×
1379
    else
1380
    {
1381
        // Just to make sure update all player infos
1382
        SendToAll(GameMessage_Player_List(playerInfos));
×
1383
        // Start countdown (except its single player)
1384
        if(networkPlayers.size() > 1)
×
1385
        {
1386
            countdown.Start(msg.countdown);
×
1387
            SendToAll(GameMessage_Countdown(countdown.GetRemainingSecs()));
×
1388
            LOG.writeToFile("SERVER >>> Countdown started(%d)\n") % countdown.GetRemainingSecs();
×
1389
        } else if(!StartGame())
×
1390
            Stop();
×
1391
    }
1392

1393
    return true;
×
1394
}
1395

1396
bool GameServer::OnGameMessage(const GameMessage_CancelCountdown& msg)
×
1397
{
1398
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1399
    {
1400
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1401
        return true;
×
1402
    }
1403

1404
    CancelCountdown();
×
1405
    return true;
×
1406
}
1407

1408
bool GameServer::OnGameMessage(const GameMessage_Pause& msg)
×
1409
{
1410
    if(IsHost(msg.senderPlayerID))
×
1411
        SetPaused(msg.paused);
×
1412
    return true;
×
1413
}
1414

1415
bool GameServer::OnGameMessage(const GameMessage_SkipToGF& msg)
×
1416
{
1417
    if(IsHost(msg.senderPlayerID))
×
1418
    {
1419
        skiptogf = msg.targetGF;
×
1420
        SendToAll(msg);
×
1421
    }
1422
    return true;
×
1423
}
1424

1425
bool GameServer::OnGameMessage(const GameMessage_GGSChange& msg)
×
1426
{
1427
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1428
    {
1429
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1430
        return true;
×
1431
    }
1432
    ggs_ = msg.ggs;
×
1433
    SendToAll(msg);
×
1434
    CancelCountdown();
×
1435
    return true;
×
1436
}
1437

1438
void GameServer::CancelCountdown()
×
1439
{
1440
    if(!countdown.IsActive())
×
1441
        return;
×
1442
    // Countdown-Stop allen mitteilen
1443
    countdown.Stop();
×
1444
    SendToAll(GameMessage_CancelCountdown());
×
1445
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_CANCELCOUNTDOWN\n");
×
1446
}
1447

1448
bool GameServer::ArePlayersReady() const
×
1449
{
1450
    // Alle Spieler da?
1451
    for(const JoinPlayerInfo& player : playerInfos)
×
1452
    {
1453
        // noch nicht alle spieler da -> feierabend!
1454
        if(player.ps == PlayerState::Free || (player.isHuman() && !player.isReady))
×
1455
            return false;
×
1456
    }
1457

1458
    std::set<unsigned> takenColors;
×
1459

1460
    // Check all players have different colors
1461
    for(const JoinPlayerInfo& player : playerInfos)
×
1462
    {
1463
        if(player.isUsed())
×
1464
        {
1465
            if(helpers::contains(takenColors, player.color))
×
1466
                return false;
×
1467
            takenColors.insert(player.color);
×
1468
        }
1469
    }
1470
    return true;
×
1471
}
1472

1473
void GameServer::PlayerDataChanged(unsigned playerIdx)
×
1474
{
1475
    CancelCountdown();
×
1476
    JoinPlayerInfo& player = GetJoinPlayer(playerIdx);
×
1477
    if(player.ps != PlayerState::AI && player.isReady)
×
1478
    {
1479
        player.isReady = false;
×
1480
        SendToAll(GameMessage_Player_Ready(playerIdx, false));
×
1481
    }
1482
}
×
1483

1484
bfs::path GameServer::SaveAsyncLog()
×
1485
{
1486
    // Get the highest common counter number and start from there (remove all others)
1487
    unsigned maxCtr = 0;
×
1488
    for(const AsyncLog& log : asyncLogs)
×
1489
    {
1490
        if(!log.randEntries.empty() && log.randEntries[0].counter > maxCtr)
×
1491
            maxCtr = log.randEntries[0].counter;
×
1492
    }
1493
    // Number of entries = max(asyncLogs[0..n].randEntries.size())
1494
    unsigned numEntries = 0;
×
1495
    for(AsyncLog& log : asyncLogs)
×
1496
    {
1497
        auto it = helpers::find_if(log.randEntries, [maxCtr](const auto& e) { return e.counter == maxCtr; });
×
1498
        log.randEntries.erase(log.randEntries.begin(), it);
×
1499
        if(numEntries < log.randEntries.size())
×
1500
            numEntries = log.randEntries.size();
×
1501
    }
1502
    // No entries :(
1503
    if(numEntries == 0 || asyncLogs.size() < 2u)
×
1504
        return "";
×
1505

1506
    // count identical lines
1507
    unsigned numIdentical = 0;
×
1508
    for(unsigned i = 0; i < numEntries; i++)
×
1509
    {
1510
        bool isIdentical = true;
×
1511
        if(i >= asyncLogs[0].randEntries.size())
×
1512
            break;
×
1513
        const RandomEntry& refEntry = asyncLogs[0].randEntries[i];
×
1514
        for(const AsyncLog& log : asyncLogs)
×
1515
        {
1516
            if(i >= log.randEntries.size())
×
1517
            {
1518
                isIdentical = false;
×
1519
                break;
×
1520
            }
1521
            const RandomEntry& curEntry = log.randEntries[i];
×
1522
            if(curEntry.maxExcl != refEntry.maxExcl || curEntry.rngState != refEntry.rngState
×
1523
               || curEntry.objId != refEntry.objId)
×
1524
            {
1525
                isIdentical = false;
×
1526
                break;
×
1527
            }
1528
        }
1529
        if(isIdentical)
×
1530
            ++numIdentical;
×
1531
        else
1532
            break;
×
1533
    }
1534

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

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

1540
    // open async log
1541
    bnw::ofstream file(filePath);
×
1542

1543
    if(file)
×
1544
    {
1545
        file << "Map: " << mapinfo.title << std::endl;
×
1546
        file << std::setfill(' ');
×
1547
        for(const AsyncLog& log : asyncLogs)
×
1548
        {
1549
            const JoinPlayerInfo& plInfo = playerInfos.at(log.playerId);
×
1550
            file << "Player " << std::setw(2) << unsigned(log.playerId) << (plInfo.isHost ? '#' : ' ') << "\t\""
×
1551
                 << plInfo.name << '"' << std::endl;
×
1552
            file << "System info: " << log.addData << std::endl;
×
1553
            file << "\tChecksum: " << std::setw(0) << log.checksum << std::endl;
×
1554
        }
1555
        for(const AsyncLog& log : asyncLogs)
×
1556
            file << "Checksum " << std::setw(2) << unsigned(log.playerId) << std::setw(0) << ": " << log.checksum
×
1557
                 << std::endl;
×
1558

1559
        // print identical lines, they help in tracing the bug
1560
        for(unsigned i = 0; i < numIdentical; i++)
×
1561
            file << "[ I ]: " << asyncLogs[0].randEntries[i] << "\n";
×
1562
        for(unsigned i = numIdentical; i < numEntries; i++)
×
1563
        {
1564
            for(const AsyncLog& log : asyncLogs)
×
1565
            {
1566
                if(i < log.randEntries.size())
×
1567
                    file << "[C" << std::setw(2) << unsigned(log.playerId) << std::setw(0)
×
1568
                         << "]: " << log.randEntries[i] << '\n';
×
1569
            }
1570
        }
1571

1572
        LOG.write(_("Async log saved at %1%\n")) % filePath;
×
1573
        return filePath;
×
1574
    } else
1575
    {
1576
        LOG.write(_("Failed to save async log at %1%\n")) % filePath;
×
1577
        return "";
×
1578
    }
1579
}
1580

1581
void GameServer::SendAsyncLog(const bfs::path& asyncLogFilePath)
×
1582
{
1583
    if(SETTINGS.global.submit_debug_data == 1
×
1584
#ifdef _WIN32
1585
       || (MessageBoxW(nullptr,
1586
                       boost::nowide::widen(_("The game clients are out of sync. Would you like to send debug "
1587
                                              "information to RttR to help us avoiding this in "
1588
                                              "the future? Thank you very much!"))
1589
                         .c_str(),
1590
                       boost::nowide::widen(_("Error")).c_str(),
1591
                       MB_YESNO | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND)
1592
           == IDYES)
1593
#endif
1594
    )
1595
    {
1596
        DebugInfo di;
×
1597
        LOG.write(_("Sending async logs %1%.\n")) % (di.SendAsyncLog(asyncLogFilePath) ? "succeeded" : "failed");
×
1598

1599
        di.SendReplay();
×
1600
    }
1601
}
×
1602

1603
void GameServer::CheckAndSetColor(unsigned playerIdx, unsigned newColor)
×
1604
{
1605
    RTTR_Assert(playerIdx < playerInfos.size());
×
1606
    RTTR_Assert(playerInfos.size() <= PLAYER_COLORS.size()); // Else we may not find a valid color!
×
1607

1608
    JoinPlayerInfo& player = playerInfos[playerIdx];
×
1609
    RTTR_Assert(player.isUsed()); // Should only set colors for taken spots
×
1610

1611
    // Get colors used by other players
1612
    std::set<unsigned> takenColors;
×
1613
    for(unsigned p = 0; p < playerInfos.size(); ++p)
×
1614
    {
1615
        // Skip self
1616
        if(p == playerIdx)
×
1617
            continue;
×
1618

1619
        JoinPlayerInfo& otherPlayer = playerInfos[p];
×
1620
        if(otherPlayer.isUsed())
×
1621
            takenColors.insert(otherPlayer.color);
×
1622
    }
1623

1624
    // Look for a unique color
1625
    int newColorIdx = JoinPlayerInfo::GetColorIdx(newColor);
×
1626
    while(helpers::contains(takenColors, newColor))
×
1627
        newColor = PLAYER_COLORS[(++newColorIdx) % PLAYER_COLORS.size()];
×
1628

1629
    if(player.color == newColor)
×
1630
        return;
×
1631

1632
    player.color = newColor;
×
1633

1634
    SendToAll(GameMessage_Player_Color(playerIdx, player.color));
×
1635
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYER_TOGGLECOLOR(%d, %d)\n") % playerIdx % player.color;
×
1636
}
1637

1638
bool GameServer::OnGameMessage(const GameMessage_Player_Swap& msg)
×
1639
{
1640
    if(state != ServerState::Game && state != ServerState::Config)
×
1641
        return true;
×
1642
    int targetPlayer = GetTargetPlayer(msg);
×
1643
    if(targetPlayer < 0)
×
1644
        return true;
×
1645
    auto player1 = static_cast<uint8_t>(targetPlayer);
×
1646
    if(player1 == msg.player2 || msg.player2 >= playerInfos.size())
×
1647
        return true;
×
1648

1649
    SwapPlayer(player1, msg.player2);
×
1650
    return true;
×
1651
}
1652

1653
bool GameServer::OnGameMessage(const GameMessage_Player_SwapConfirm& msg)
×
1654
{
1655
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1656
    if(!player)
×
1657
        return true;
×
1658
    for(auto it = player->getPendingSwaps().begin(); it != player->getPendingSwaps().end(); ++it)
×
1659
    {
1660
        if(it->first == msg.player && it->second == msg.player2)
×
1661
        {
1662
            player->getPendingSwaps().erase(it);
×
1663
            break;
×
1664
        }
1665
    }
1666
    return true;
×
1667
}
1668

1669
void GameServer::SwapPlayer(const uint8_t player1, const uint8_t player2)
×
1670
{
1671
    // TODO: Swapping the player messes up the ids because our IDs are indizes. Usually this works because we use the
1672
    // sender player ID for messages received by the server and set the right ID for messages sent by the server.
1673
    // However (currently only) the host may send messages for another player. Those will not get the adjusted ID till
1674
    // he gets the swap message. So there is a short time, where the messages may be executed for the wrong player.
1675
    // Idea: Use actual IDs for players in messages (unique)
1676
    if(state == ServerState::Config)
×
1677
    {
1678
        // Swap player during match-making
1679
        // Swap everything
1680
        using std::swap;
1681
        swap(playerInfos[player1], playerInfos[player2]);
×
1682
        // In savegames some things cannot be changed
1683
        if(mapinfo.type == MapType::Savegame)
×
1684
            playerInfos[player1].FixSwappedSaveSlot(playerInfos[player2]);
×
1685
    } else if(state == ServerState::Game)
×
1686
    {
1687
        // Ingame we can only switch to a KI
1688
        if(playerInfos[player1].ps != PlayerState::Occupied || playerInfos[player2].ps != PlayerState::AI)
×
1689
            return;
×
1690

1691
        LOG.write("GameServer::ChangePlayer %i - %i \n") % unsigned(player1) % unsigned(player2);
×
1692
        using std::swap;
1693
        swap(playerInfos[player2].ps, playerInfos[player1].ps);
×
1694
        swap(playerInfos[player2].aiInfo, playerInfos[player1].aiInfo);
×
1695
        swap(playerInfos[player2].isHost, playerInfos[player1].isHost);
×
1696
    }
1697
    // Change ids of network players (if any). Get both first!
1698
    GameServerPlayer* newPlayer = GetNetworkPlayer(player2);
×
1699
    GameServerPlayer* oldPlayer = GetNetworkPlayer(player1);
×
1700
    if(newPlayer)
×
1701
        newPlayer->playerId = player1;
×
1702
    if(oldPlayer)
×
1703
        oldPlayer->playerId = player2;
×
1704
    SendToAll(GameMessage_Player_Swap(player1, player2));
×
1705
    const auto pSwap = std::make_pair(player1, player2);
×
1706
    for(GameServerPlayer& player : networkPlayers)
×
1707
    {
1708
        if(!player.isActive())
×
1709
            continue;
×
1710
        player.getPendingSwaps().push_back(pSwap);
×
1711
    }
1712
}
1713

1714
GameServerPlayer* GameServer::GetNetworkPlayer(unsigned playerId)
×
1715
{
1716
    for(GameServerPlayer& player : networkPlayers)
×
1717
    {
1718
        if(player.playerId == playerId)
×
1719
            return &player;
×
1720
    }
1721
    return nullptr;
×
1722
}
1723

1724
void GameServer::SetPaused(bool paused)
×
1725
{
1726
    if(framesinfo.isPaused == paused)
×
1727
        return;
×
1728
    framesinfo.isPaused = paused;
×
1729
    SendToAll(GameMessage_Pause(framesinfo.isPaused));
×
1730
    for(GameServerPlayer& player : networkPlayers)
×
1731
        player.setNotLagging();
×
1732
}
1733

1734
JoinPlayerInfo& GameServer::GetJoinPlayer(unsigned playerIdx)
×
1735
{
1736
    return playerInfos.at(playerIdx);
×
1737
}
1738

1739
bool GameServer::IsHost(unsigned playerIdx) const
×
1740
{
1741
    return playerIdx < playerInfos.size() && playerInfos[playerIdx].isHost;
×
1742
}
1743

1744
int GameServer::GetTargetPlayer(const GameMessageWithPlayer& msg)
×
1745
{
1746
    if(msg.player != 0xFF)
×
1747
    {
1748
        if(msg.player < playerInfos.size() && (msg.player == msg.senderPlayerID || IsHost(msg.senderPlayerID)))
×
1749
        {
1750
            GameServerPlayer* networkPlayer = GetNetworkPlayer(msg.senderPlayerID);
×
1751
            if(networkPlayer->isActive())
×
1752
                return msg.player;
×
1753
            unsigned result = msg.player;
×
1754
            // Apply pending swaps
1755
            for(auto& pSwap : networkPlayer->getPendingSwaps()) //-V522
×
1756
            {
1757
                if(pSwap.first == result)
×
1758
                    result = pSwap.second;
×
1759
                else if(pSwap.second == result)
×
1760
                    result = pSwap.first;
×
1761
            }
1762
            return result;
×
1763
        }
1764
    } else if(msg.senderPlayerID < playerInfos.size())
×
1765
        return msg.senderPlayerID;
×
1766
    return -1;
×
1767
}
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