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

Return-To-The-Roots / s25client / 21600910629

02 Feb 2026 05:42PM UTC coverage: 50.721% (-0.03%) from 50.754%
21600910629

Pull #1683

github

web-flow
Merge b0763ef2d into dc0ce04f6
Pull Request #1683: Lua: Allow setting number of players, and placing HQs. Then fix the mission on map "The snake"

1 of 29 new or added lines in 7 files covered. (3.45%)

5 existing lines in 2 files now uncovered.

22796 of 44944 relevant lines covered (50.72%)

41333.25 hits per line

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

4.57
/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

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

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

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

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)
28✔
425
{
426
    static_assert(NUM_TEAMS == 4, "Expected exactly 4 playable teams!");
427
    RTTR_Assert(playerInfos.size() <= MAX_PLAYERS);
28✔
428

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

437
    std::array<unsigned, NUM_TEAMS> numPlayersInTeam{};
28✔
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();
28✔
447

448
    bool playerWasAssigned = false;
28✔
449

450
    // Assign (fully) random teams, count players in team and sort into playersToAssign
451
    for(PlayerIndex player = 0; player < playerInfos.size(); ++player)
184✔
452
    {
453
        auto& playerInfo = playerInfos[player];
156✔
454
        if(playerInfo.team == Team::Random)
156✔
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)
156✔
461
        {
462
            case Team::Team1: ++numPlayersInTeam[0]; break;
28✔
463
            case Team::Team2: ++numPlayersInTeam[1]; break;
8✔
464
            case Team::Team3: ++numPlayersInTeam[2]; break;
23✔
465
            case Team::Team4: ++numPlayersInTeam[3]; break;
4✔
466
            case Team::Random1To2: playersToAssign.emplace_back(AssignPlayer{player, {0, 1}}); break;
69✔
467
            case Team::Random1To3: playersToAssign.emplace_back(AssignPlayer{player, {0, 1, 2}}); break;
162✔
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) {
28✔
476
        return lhs.possibleTeams.size() < rhs.possibleTeams.size();
414✔
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)
266✔
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();
91✔
484
        static_vector<TeamIndex, NUM_TEAMS> teamsForNextPlayer;
×
485
        for(const TeamIndex team : player.possibleTeams)
801✔
486
        {
487
            if(minNextTeamSize > numPlayersInTeam[team])
264✔
488
            {
489
                teamsForNextPlayer.clear();
490
                teamsForNextPlayer.push_back(team);
491
                minNextTeamSize = numPlayersInTeam[team];
140✔
492
            } else if(minNextTeamSize == numPlayersInTeam[team])
124✔
493
                teamsForNextPlayer.push_back(team);
494
        }
495
        player.chosenTeam = helpers::getRandomElement(rng, teamsForNextPlayer);
91✔
496

497
        ++numPlayersInTeam[player.chosenTeam];
91✔
498
        playerWasAssigned = true;
91✔
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);
28✔
503
    for(auto it = playersToAssign.begin(); it != playersToAssign.end(); ++it)
210✔
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)
555✔
509
        {
510
            if(helpers::contains(it->possibleTeams, it2->chosenTeam)
464✔
511
               && helpers::contains(it2->possibleTeams, it->chosenTeam))
656✔
512
                possibleSwapTargets.push_back(it2);
513
        }
514
        const auto itSwapTarget = helpers::getRandomElement(rng, possibleSwapTargets);
91✔
515
        std::swap(it->chosenTeam, itSwapTarget->chosenTeam);
182✔
516
        playerInfos[it->player].team = teamIdxToTeam(it->chosenTeam);
182✔
517
    }
518

519
    return playerWasAssigned;
56✔
520
}
521

NEW
522
void GameServer::SetNumPlayers(unsigned num)
×
523
{
NEW
524
    playerInfos.resize(num);
×
NEW
525
}
×
526

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

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

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

545
    nwfInfo.init(currentGF, 3);
×
546

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

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

562
    framesinfo.gfLengthReq = framesinfo.gf_length = SPEED_GF_LENGTHS[ggs_.speed];
×
563

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

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

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

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

582
    state = ServerState::Loading;
×
583
    loadStartTime = SteadyClock::now();
×
584

585
    return true;
×
586
}
587

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

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

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

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

628
    SendToAll(GameMessage_Player_Kicked(playerId, cause, param));
×
629

630
    // If we are ingame, replace by KI
631
    if(state == ServerState::Game || state == ServerState::Loading)
×
632
    {
633
        playerInfo.ps = PlayerState::AI;
×
634
        playerInfo.aiInfo = AI::Info(AI::Type::Dummy);
×
635
    } else
636
        CancelCountdown();
×
637

638
    AnnounceStatusChange();
×
639
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYERKICKED(%d,%d,%d)\n") % unsigned(playerId) % unsigned(cause)
×
640
      % unsigned(param);
×
641
}
642

643
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
644
void GameServer::ClientWatchDog()
×
645
{
646
    SocketSet set;
×
647
    set.Clear();
×
648

649
    // sockets zum set hinzufügen
650
    for(GameServerPlayer& player : networkPlayers)
×
651
        set.Add(player.socket);
×
652

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

666
    for(GameServerPlayer& player : networkPlayers)
×
667
    {
668
        if(player.hasTimedOut())
×
669
        {
670
            LOG.write(_("SERVER: Reserved slot %1% freed due to timeout\n")) % player.playerId;
×
671
            KickPlayer(player.playerId, KickReason::PingTimeout, __LINE__);
×
672
        } else
673
            player.doPing();
×
674
    }
675
}
×
676

677
void GameServer::ExecuteGameFrame()
×
678
{
679
    RTTR_Assert(state == ServerState::Game);
×
680

681
    FramesInfo::UsedClock::time_point currentTime = FramesInfo::UsedClock::now();
×
682
    FramesInfo::milliseconds32_t passedTime =
683
      std::chrono::duration_cast<FramesInfo::milliseconds32_t>(currentTime - framesinfo.lastTime);
×
684

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

719
void GameServer::ExecuteNWF()
×
720
{
721
    // Check for asyncs
722
    if(CheckForAsync())
×
723
    {
724
        // Pause game
725
        RTTR_Assert(!framesinfo.isPaused);
×
726
        SetPaused(true);
×
727

728
        // Notify players
729
        std::vector<unsigned> checksumHashes;
×
730
        checksumHashes.reserve(networkPlayers.size());
×
731
        for(const GameServerPlayer& player : networkPlayers)
×
732
            checksumHashes.push_back(nwfInfo.getPlayerCmds(player.playerId).checksum.getHash());
×
733
        SendToAll(GameMessage_Server_Async(checksumHashes));
×
734

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

768
bool GameServer::CheckForAsync()
×
769
{
770
    if(networkPlayers.empty())
×
771
        return false;
×
772
    bool isAsync = false;
×
773
    const AsyncChecksum& refChecksum = nwfInfo.getPlayerCmds(networkPlayers.front().playerId).checksum;
×
774
    for(const GameServerPlayer& player : networkPlayers)
×
775
    {
776
        const AsyncChecksum& curChecksum = nwfInfo.getPlayerCmds(player.playerId).checksum;
×
777

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

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

803
bool GameServer::CheckForLaggingPlayers()
×
804
{
805
    if(nwfInfo.isReady())
×
806
        return false;
×
807
    for(GameServerPlayer& player : networkPlayers)
×
808
    {
809
        if(nwfInfo.getPlayerInfo(player.playerId).isLagging)
×
810
            player.setLagging();
×
811
    }
812
    return true;
×
813
}
814

815
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
816
void GameServer::WaitForClients()
×
817
{
818
    SocketSet set;
×
819

820
    set.Add(serversocket);
×
821
    if(set.Select(0, 0) > 0)
×
822
    {
823
        RTTR_Assert(set.InSet(serversocket));
×
824
        Socket socket = serversocket.Accept();
×
825

826
        // Verbindung annehmen
827
        if(!socket.isValid())
×
828
            return;
×
829

830
        unsigned newPlayerId = GameMessageWithPlayer::NO_PLAYER_ID;
×
831
        // Geeigneten Platz suchen
832
        for(unsigned playerId = 0; playerId < playerInfos.size(); ++playerId)
×
833
        {
834
            if(playerInfos[playerId].ps == PlayerState::Free && !GetNetworkPlayer(playerId))
×
835
            {
836
                networkPlayers.push_back(GameServerPlayer(playerId, socket));
×
837
                newPlayerId = playerId;
×
838
                break;
×
839
            }
840
        }
841

842
        GameMessage_Player_Id msg(newPlayerId);
×
843
        MessageHandler::send(socket, msg);
×
844

845
        // war kein platz mehr frei, wenn ja dann verbindung trennen?
846
        if(newPlayerId == 0xFFFFFFFF)
×
847
            socket.Close();
×
848
    }
849
}
850

851
// füllt die warteschlangen mit "paketen"
852
void GameServer::FillPlayerQueues()
×
853
{
854
    SocketSet set;
×
855
    bool msgReceived = false;
×
856

857
    // erstmal auf Daten überprüfen
858
    do
×
859
    {
860
        // sockets zum set hinzufügen
861
        for(const GameServerPlayer& player : networkPlayers)
×
862
            set.Add(player.socket);
×
863

864
        msgReceived = false;
×
865

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

886
bool GameServer::OnGameMessage(const GameMessage_Pong& msg)
×
887
{
888
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
889
    if(player)
×
890
    {
891
        unsigned ping = player->calcPingTime();
×
892
        if(ping == 0u)
×
893
            return true;
×
894
        playerInfos[msg.senderPlayerID].ping = ping;
×
895
        SendToAll(GameMessage_Player_Ping(msg.senderPlayerID, ping));
×
896
    }
897
    return true;
×
898
}
899

900
bool GameServer::OnGameMessage(const GameMessage_Server_Type& msg)
×
901
{
902
    if(state != ServerState::Config)
×
903
    {
904
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
905
        return true;
×
906
    }
907

908
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
909
    if(!player)
×
910
        return true;
×
911

912
    auto typeok = GameMessage_Server_TypeOK::StatusCode::Ok;
×
913
    if(msg.type != config.servertype)
×
914
        typeok = GameMessage_Server_TypeOK::StatusCode::InvalidServerType;
×
915
    else if(msg.revision != rttr::version::GetRevision())
×
916
        typeok = GameMessage_Server_TypeOK::StatusCode::WrongVersion;
×
917

918
    player->sendMsg(GameMessage_Server_TypeOK(typeok, rttr::version::GetRevision()));
×
919

920
    if(typeok != GameMessage_Server_TypeOK::StatusCode::Ok)
×
921
        KickPlayer(msg.senderPlayerID, KickReason::ConnectionLost, __LINE__);
×
922
    return true;
×
923
}
924

925
bool GameServer::OnGameMessage(const GameMessage_Server_Password& msg)
×
926
{
927
    if(state != ServerState::Config)
×
928
    {
929
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
930
        return true;
×
931
    }
932

933
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
934
    if(!player)
×
935
        return true;
×
936

937
    std::string passwordok = (config.password == msg.password ? "true" : "false");
×
938
    if(msg.password == config.hostPassword)
×
939
    {
940
        passwordok = "true";
×
941
        playerInfos[msg.senderPlayerID].isHost = true;
×
942
    } else
943
        playerInfos[msg.senderPlayerID].isHost = false;
×
944

945
    player->sendMsgAsync(new GameMessage_Server_Password(passwordok));
×
946

947
    if(passwordok == "false")
×
948
        KickPlayer(msg.senderPlayerID, KickReason::WrongPassword, __LINE__);
×
949
    return true;
×
950
}
951

952
bool GameServer::OnGameMessage(const GameMessage_Chat& msg)
×
953
{
954
    int playerID = GetTargetPlayer(msg);
×
955
    if(playerID >= 0)
×
956
        SendToAll(GameMessage_Chat(playerID, msg.destination, msg.text));
×
957
    return true;
×
958
}
959

960
bool GameServer::OnGameMessage(const GameMessage_Player_State& msg)
×
961
{
962
    if(state != ServerState::Config)
×
963
    {
964
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
965
        return true;
×
966
    }
967
    // Can't do this. Have to have a joined player
968
    if(msg.ps == PlayerState::Occupied)
×
969
        return true;
×
970

971
    int playerID = GetTargetPlayer(msg);
×
972
    if(playerID < 0)
×
973
        return true;
×
974
    JoinPlayerInfo& player = playerInfos[playerID];
×
975
    const PlayerState oldPs = player.ps;
×
976
    // Can't change self
977
    if(playerID != msg.senderPlayerID)
×
978
    {
979
        // oh ein spieler, weg mit ihm!
980
        if(GetNetworkPlayer(playerID))
×
981
            KickPlayer(playerID, KickReason::NoCause, __LINE__);
×
982

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

1005
    if(player.ps == PlayerState::AI)
×
1006
    {
1007
        player.SetAIName(playerID);
×
1008
        SendToAll(GameMessage_Player_Name(playerID, player.name));
×
1009
    }
1010
    // If slot is filled, check current color
1011
    if(player.isUsed())
×
1012
        CheckAndSetColor(playerID, player.color);
×
1013
    SendToAll(GameMessage_Player_State(playerID, player.ps, player.aiInfo));
×
1014

1015
    if(oldPs != player.ps)
×
1016
        player.isReady = (player.ps == PlayerState::AI);
×
1017
    SendToAll(GameMessage_Player_Ready(playerID, player.isReady));
×
1018
    PlayerDataChanged(playerID);
×
1019
    AnnounceStatusChange();
×
1020
    return true;
×
1021
}
1022

1023
bool GameServer::OnGameMessage(const GameMessage_Player_Name& msg)
×
1024
{
1025
    if(state != ServerState::Config)
×
1026
    {
1027
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1028
        return true;
×
1029
    }
1030
    int playerID = GetTargetPlayer(msg);
×
1031
    if(playerID < 0)
×
1032
        return true;
×
1033

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

1036
    playerInfos[playerID].name = msg.playername;
×
1037
    SendToAll(GameMessage_Player_Name(playerID, msg.playername));
×
1038
    PlayerDataChanged(playerID);
×
1039

1040
    return true;
×
1041
}
1042

1043
bool GameServer::OnGameMessage(const GameMessage_Player_Portrait& 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
    if(msg.playerPortraitIndex >= Portraits.size())
×
1054
        return true;
×
1055

1056
    LOG.writeToFile("CLIENT%d >>> SERVER: NMS_PLAYER_PORTRAIT(%u)\n") % playerID % msg.playerPortraitIndex;
×
1057
    playerInfos[playerID].portraitIndex = msg.playerPortraitIndex;
×
1058
    SendToAll(GameMessage_Player_Portrait(playerID, msg.playerPortraitIndex));
×
1059
    PlayerDataChanged(playerID);
×
1060

1061
    return true;
×
1062
}
1063

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

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

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

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

1093
    playerInfos[playerID].team = msg.team;
×
1094

1095
    SendToAll(GameMessage_Player_Team(playerID, msg.team));
×
1096
    PlayerDataChanged(playerID);
×
1097
    return true;
×
1098
}
1099

1100
bool GameServer::OnGameMessage(const GameMessage_Player_Color& msg)
×
1101
{
1102
    if(state != ServerState::Config)
×
1103
    {
1104
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1105
        return true;
×
1106
    }
1107
    int playerID = GetTargetPlayer(msg);
×
1108
    if(playerID < 0)
×
1109
        return true;
×
1110

1111
    CheckAndSetColor(playerID, msg.color);
×
1112
    PlayerDataChanged(playerID);
×
1113
    return true;
×
1114
}
1115

1116
bool GameServer::OnGameMessage(const GameMessage_Player_Ready& msg)
×
1117
{
1118
    if(state != ServerState::Config)
×
1119
    {
1120
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1121
        return true;
×
1122
    }
1123
    int playerID = GetTargetPlayer(msg);
×
1124
    if(playerID < 0)
×
1125
        return true;
×
1126

1127
    JoinPlayerInfo& player = playerInfos[playerID];
×
1128

1129
    player.isReady = msg.ready;
×
1130

1131
    // countdown ggf abbrechen
1132
    if(!player.isReady && countdown.IsActive())
×
1133
        CancelCountdown();
×
1134

1135
    SendToAll(GameMessage_Player_Ready(playerID, msg.ready));
×
1136
    return true;
×
1137
}
1138

1139
bool GameServer::OnGameMessage(const GameMessage_MapRequest& msg)
×
1140
{
1141
    if(state != ServerState::Config)
×
1142
    {
1143
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1144
        return true;
×
1145
    }
1146
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1147
    if(!player)
×
1148
        return true;
×
1149

1150
    if(msg.requestInfo)
×
1151
    {
1152
        player->sendMsgAsync(new GameMessage_Map_Info(mapinfo.filepath.filename().string(), mapinfo.type,
×
1153
                                                      mapinfo.mapData.uncompressedLength, mapinfo.mapData.data.size(),
×
1154
                                                      mapinfo.luaData.uncompressedLength, mapinfo.luaData.data.size()));
×
1155
    } else if(player->isMapSending())
×
1156
    {
1157
        // Don't send again
1158
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1159
    } else
1160
    {
1161
        // Send map data
1162
        unsigned curPos = 0;
×
1163
        unsigned remainingSize = mapinfo.mapData.data.size();
×
1164
        while(remainingSize)
×
1165
        {
1166
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1167

1168
            player->sendMsgAsync(new GameMessage_Map_Data(true, curPos, &mapinfo.mapData.data[curPos], chunkSize));
×
1169
            curPos += chunkSize;
×
1170
            remainingSize -= chunkSize;
×
1171
        }
1172

1173
        // And lua data (if there is any)
1174
        RTTR_Assert(mapinfo.luaFilepath.empty() == mapinfo.luaData.data.empty());
×
1175
        RTTR_Assert(mapinfo.luaData.data.empty() == (mapinfo.luaData.uncompressedLength == 0));
×
1176
        curPos = 0;
×
1177
        remainingSize = mapinfo.luaData.data.size();
×
1178
        while(remainingSize)
×
1179
        {
1180
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1181

1182
            player->sendMsgAsync(new GameMessage_Map_Data(false, curPos, &mapinfo.luaData.data[curPos], chunkSize));
×
1183
            curPos += chunkSize;
×
1184
            remainingSize -= chunkSize;
×
1185
        }
1186
        // estimate time. max 60 chunks/s (currently limited by framerate), assume 50 (~25kb/s)
1187
        auto numChunks = (mapinfo.mapData.data.size() + mapinfo.luaData.data.size()) / MAP_PART_SIZE;
×
1188
        player->setMapSending(std::chrono::seconds(numChunks / 50 + 1));
×
1189
    }
1190
    return true;
×
1191
}
1192

1193
bool GameServer::OnGameMessage(const GameMessage_Map_Checksum& msg)
×
1194
{
1195
    if(state != ServerState::Config)
×
1196
    {
1197
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1198
        return true;
×
1199
    }
1200
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1201
    if(!player)
×
1202
        return true;
×
1203

1204
    bool checksumok = (msg.mapChecksum == mapinfo.mapChecksum && msg.luaChecksum == mapinfo.luaChecksum);
×
1205

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

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

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

1214
    if(!checksumok)
×
1215
    {
1216
        if(player->isMapSending())
×
1217
            KickPlayer(msg.senderPlayerID, KickReason::WrongChecksum, __LINE__);
×
1218
    } else
1219
    {
1220
        JoinPlayerInfo& playerInfo = playerInfos[msg.senderPlayerID];
×
1221
        // Used? Then we got this twice or some error happened. Remove him
1222
        if(playerInfo.isUsed())
×
1223
            KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1224
        else
1225
        {
1226
            // Inform others about a new player
1227
            SendToAll(GameMessage_Player_New(msg.senderPlayerID, playerInfo.name));
×
1228

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

1232
            // Mark as used and assign a unique color
1233
            // Do this before sending the player list to avoid sending useless updates
1234
            playerInfo.ps = PlayerState::Occupied;
×
1235
            CheckAndSetColor(msg.senderPlayerID, playerInfo.color);
×
1236

1237
            // Send remaining data and mark as active
1238
            player->sendMsgAsync(new GameMessage_Server_Name(config.gamename));
×
1239
            player->sendMsgAsync(new GameMessage_Player_List(playerInfos));
×
1240
            player->sendMsgAsync(new GameMessage_GGSChange(ggs_));
×
1241
            player->setActive();
×
1242
        }
1243
        AnnounceStatusChange();
×
1244
    }
1245
    return true;
×
1246
}
1247

1248
// speed change message
1249
bool GameServer::OnGameMessage(const GameMessage_Speed& msg)
×
1250
{
1251
    if(state != ServerState::Game)
×
1252
    {
1253
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1254
        return true;
×
1255
    }
1256
    framesinfo.gfLengthReq = FramesInfo::milliseconds32_t(msg.gf_length);
×
1257
    return true;
×
1258
}
1259

1260
bool GameServer::OnGameMessage(const GameMessage_GameCommand& msg)
×
1261
{
1262
    int targetPlayerId = GetTargetPlayer(msg);
×
1263
    if((state != ServerState::Game && state != ServerState::Loading) || targetPlayerId < 0
×
1264
       || (state == ServerState::Loading && !msg.cmds.gcs.empty()))
×
1265
    {
1266
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1267
        return true;
×
1268
    }
1269

1270
    if(!nwfInfo.addPlayerCmds(targetPlayerId, msg.cmds))
×
1271
        return true; // Ignore
×
1272
    GameServerPlayer* player = GetNetworkPlayer(targetPlayerId);
×
1273
    if(player)
×
1274
        player->setNotLagging();
×
1275
    SendToAll(GameMessage_GameCommand(targetPlayerId, msg.cmds.checksum, msg.cmds.gcs));
×
1276

1277
    return true;
×
1278
}
1279

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

1311
    // Check if we have all logs
1312
    for(const AsyncLog& log : asyncLogs)
×
1313
    {
1314
        if(!log.done)
×
1315
            return true;
×
1316
    }
1317

1318
    LOG.write(_("Async logs received completely.\n"));
×
1319

1320
    const bfs::path asyncFilePath = SaveAsyncLog();
×
1321
    if(!asyncFilePath.empty())
×
1322
        SendAsyncLog(asyncFilePath);
×
1323

1324
    // Kick all players that have a different checksum from the host
1325
    AsyncChecksum hostChecksum;
×
1326
    for(const AsyncLog& log : asyncLogs)
×
1327
    {
1328
        if(playerInfos.at(log.playerId).isHost)
×
1329
        {
1330
            hostChecksum = log.checksum;
×
1331
            break;
×
1332
        }
1333
    }
1334
    for(const AsyncLog& log : asyncLogs)
×
1335
    {
1336
        if(log.checksum != hostChecksum)
×
1337
            KickPlayer(log.playerId, KickReason::Async, __LINE__);
×
1338
    }
1339
    return true;
×
1340
}
1341

1342
bool GameServer::OnGameMessage(const GameMessage_RemoveLua& msg)
×
1343
{
1344
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1345
    {
1346
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1347
        return true;
×
1348
    }
1349
    mapinfo.luaFilepath.clear();
×
1350
    mapinfo.luaData.Clear();
×
1351
    mapinfo.luaChecksum = 0;
×
1352
    SendToAll(msg);
×
1353
    CancelCountdown();
×
1354
    return true;
×
1355
}
1356

1357
bool GameServer::OnGameMessage(const GameMessage_Countdown& msg)
×
1358
{
1359
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1360
    {
1361
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1362
        return true;
×
1363
    }
1364

1365
    NetworkPlayer* nwPlayer = GetNetworkPlayer(msg.senderPlayerID);
×
1366
    if(!nwPlayer || countdown.IsActive())
×
1367
        return true;
×
1368

1369
    if(!ArePlayersReady())
×
1370
        nwPlayer->sendMsgAsync(new GameMessage_CancelCountdown(true));
×
1371
    else
1372
    {
1373
        // Just to make sure update all player infos
1374
        SendToAll(GameMessage_Player_List(playerInfos));
×
1375
        // Start countdown (except its single player)
1376
        if(networkPlayers.size() > 1)
×
1377
        {
1378
            countdown.Start(msg.countdown);
×
1379
            SendToAll(GameMessage_Countdown(countdown.GetRemainingSecs()));
×
1380
            LOG.writeToFile("SERVER >>> Countdown started(%d)\n") % countdown.GetRemainingSecs();
×
1381
        } else if(!StartGame())
×
1382
            Stop();
×
1383
    }
1384

1385
    return true;
×
1386
}
1387

1388
bool GameServer::OnGameMessage(const GameMessage_CancelCountdown& msg)
×
1389
{
1390
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1391
    {
1392
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1393
        return true;
×
1394
    }
1395

1396
    CancelCountdown();
×
1397
    return true;
×
1398
}
1399

1400
bool GameServer::OnGameMessage(const GameMessage_Pause& msg)
×
1401
{
1402
    if(IsHost(msg.senderPlayerID))
×
1403
        SetPaused(msg.paused);
×
1404
    return true;
×
1405
}
1406

1407
bool GameServer::OnGameMessage(const GameMessage_SkipToGF& msg)
×
1408
{
1409
    if(IsHost(msg.senderPlayerID))
×
1410
    {
1411
        skiptogf = msg.targetGF;
×
1412
        SendToAll(msg);
×
1413
    }
1414
    return true;
×
1415
}
1416

1417
bool GameServer::OnGameMessage(const GameMessage_GGSChange& msg)
×
1418
{
1419
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1420
    {
1421
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1422
        return true;
×
1423
    }
1424
    ggs_ = msg.ggs;
×
1425
    SendToAll(msg);
×
1426
    CancelCountdown();
×
1427
    return true;
×
1428
}
1429

1430
void GameServer::CancelCountdown()
×
1431
{
1432
    if(!countdown.IsActive())
×
1433
        return;
×
1434
    // Countdown-Stop allen mitteilen
1435
    countdown.Stop();
×
1436
    SendToAll(GameMessage_CancelCountdown());
×
1437
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_CANCELCOUNTDOWN\n");
×
1438
}
1439

1440
bool GameServer::ArePlayersReady() const
×
1441
{
1442
    // Alle Spieler da?
1443
    for(const JoinPlayerInfo& player : playerInfos)
×
1444
    {
1445
        // noch nicht alle spieler da -> feierabend!
1446
        if(player.ps == PlayerState::Free || (player.isHuman() && !player.isReady))
×
1447
            return false;
×
1448
    }
1449

1450
    std::set<unsigned> takenColors;
×
1451

1452
    // Check all players have different colors
1453
    for(const JoinPlayerInfo& player : playerInfos)
×
1454
    {
1455
        if(player.isUsed())
×
1456
        {
1457
            if(helpers::contains(takenColors, player.color))
×
1458
                return false;
×
1459
            takenColors.insert(player.color);
×
1460
        }
1461
    }
1462
    return true;
×
1463
}
1464

1465
void GameServer::PlayerDataChanged(unsigned playerIdx)
×
1466
{
1467
    CancelCountdown();
×
1468
    JoinPlayerInfo& player = GetJoinPlayer(playerIdx);
×
1469
    if(player.ps != PlayerState::AI && player.isReady)
×
1470
    {
1471
        player.isReady = false;
×
1472
        SendToAll(GameMessage_Player_Ready(playerIdx, false));
×
1473
    }
1474
}
×
1475

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

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

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

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

1532
    // open async log
1533
    bnw::ofstream file(filePath);
×
1534

1535
    if(file)
×
1536
    {
1537
        file << "Map: " << mapinfo.title << std::endl;
×
1538
        file << std::setfill(' ');
×
1539
        for(const AsyncLog& log : asyncLogs)
×
1540
        {
1541
            const JoinPlayerInfo& plInfo = playerInfos.at(log.playerId);
×
1542
            file << "Player " << std::setw(2) << unsigned(log.playerId) << (plInfo.isHost ? '#' : ' ') << "\t\""
×
1543
                 << plInfo.name << '"' << std::endl;
×
1544
            file << "System info: " << log.addData << std::endl;
×
1545
            file << "\tChecksum: " << std::setw(0) << log.checksum << std::endl;
×
1546
        }
1547
        for(const AsyncLog& log : asyncLogs)
×
1548
            file << "Checksum " << std::setw(2) << unsigned(log.playerId) << std::setw(0) << ": " << log.checksum
×
1549
                 << std::endl;
×
1550

1551
        // print identical lines, they help in tracing the bug
1552
        for(unsigned i = 0; i < numIdentical; i++)
×
1553
            file << "[ I ]: " << asyncLogs[0].randEntries[i] << "\n";
×
1554
        for(unsigned i = numIdentical; i < numEntries; i++)
×
1555
        {
1556
            for(const AsyncLog& log : asyncLogs)
×
1557
            {
1558
                if(i < log.randEntries.size())
×
1559
                    file << "[C" << std::setw(2) << unsigned(log.playerId) << std::setw(0)
×
1560
                         << "]: " << log.randEntries[i] << '\n';
×
1561
            }
1562
        }
1563

1564
        LOG.write(_("Async log saved at %1%\n")) % filePath;
×
1565
        return filePath;
×
1566
    } else
1567
    {
1568
        LOG.write(_("Failed to save async log at %1%\n")) % filePath;
×
1569
        return "";
×
1570
    }
1571
}
1572

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

1591
        di.SendReplay();
×
1592
    }
1593
}
×
1594

1595
void GameServer::CheckAndSetColor(unsigned playerIdx, unsigned newColor)
×
1596
{
1597
    RTTR_Assert(playerIdx < playerInfos.size());
×
1598
    RTTR_Assert(playerInfos.size() <= PLAYER_COLORS.size()); // Else we may not find a valid color!
×
1599

1600
    JoinPlayerInfo& player = playerInfos[playerIdx];
×
1601
    RTTR_Assert(player.isUsed()); // Should only set colors for taken spots
×
1602

1603
    // Get colors used by other players
1604
    std::set<unsigned> takenColors;
×
1605
    for(unsigned p = 0; p < playerInfos.size(); ++p)
×
1606
    {
1607
        // Skip self
1608
        if(p == playerIdx)
×
1609
            continue;
×
1610

1611
        JoinPlayerInfo& otherPlayer = playerInfos[p];
×
1612
        if(otherPlayer.isUsed())
×
1613
            takenColors.insert(otherPlayer.color);
×
1614
    }
1615

1616
    // Look for a unique color
1617
    int newColorIdx = JoinPlayerInfo::GetColorIdx(newColor);
×
1618
    while(helpers::contains(takenColors, newColor))
×
1619
        newColor = PLAYER_COLORS[(++newColorIdx) % PLAYER_COLORS.size()];
×
1620

1621
    if(player.color == newColor)
×
1622
        return;
×
1623

1624
    player.color = newColor;
×
1625

1626
    SendToAll(GameMessage_Player_Color(playerIdx, player.color));
×
1627
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYER_TOGGLECOLOR(%d, %d)\n") % playerIdx % player.color;
×
1628
}
1629

1630
bool GameServer::OnGameMessage(const GameMessage_Player_Swap& msg)
×
1631
{
1632
    if(state != ServerState::Game && state != ServerState::Config)
×
1633
        return true;
×
1634
    int targetPlayer = GetTargetPlayer(msg);
×
1635
    if(targetPlayer < 0)
×
1636
        return true;
×
1637
    auto player1 = static_cast<uint8_t>(targetPlayer);
×
1638
    if(player1 == msg.player2 || msg.player2 >= playerInfos.size())
×
1639
        return true;
×
1640

1641
    SwapPlayer(player1, msg.player2);
×
1642
    return true;
×
1643
}
1644

1645
bool GameServer::OnGameMessage(const GameMessage_Player_SwapConfirm& msg)
×
1646
{
1647
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1648
    if(!player)
×
1649
        return true;
×
1650
    for(auto it = player->getPendingSwaps().begin(); it != player->getPendingSwaps().end(); ++it)
×
1651
    {
1652
        if(it->first == msg.player && it->second == msg.player2)
×
1653
        {
1654
            player->getPendingSwaps().erase(it);
×
1655
            break;
×
1656
        }
1657
    }
1658
    return true;
×
1659
}
1660

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

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

1706
GameServerPlayer* GameServer::GetNetworkPlayer(unsigned playerId)
×
1707
{
1708
    for(GameServerPlayer& player : networkPlayers)
×
1709
    {
1710
        if(player.playerId == playerId)
×
1711
            return &player;
×
1712
    }
1713
    return nullptr;
×
1714
}
1715

1716
void GameServer::SetPaused(bool paused)
×
1717
{
1718
    if(framesinfo.isPaused == paused)
×
1719
        return;
×
1720
    framesinfo.isPaused = paused;
×
1721
    SendToAll(GameMessage_Pause(framesinfo.isPaused));
×
1722
    for(GameServerPlayer& player : networkPlayers)
×
1723
        player.setNotLagging();
×
1724
}
1725

1726
JoinPlayerInfo& GameServer::GetJoinPlayer(unsigned playerIdx)
×
1727
{
1728
    return playerInfos.at(playerIdx);
×
1729
}
1730

1731
bool GameServer::IsHost(unsigned playerIdx) const
×
1732
{
1733
    return playerIdx < playerInfos.size() && playerInfos[playerIdx].isHost;
×
1734
}
1735

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