-
-
Notifications
You must be signed in to change notification settings - Fork 517
/
netplay.cpp
5555 lines (4880 loc) · 179 KB
/
netplay.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of Warzone 2100.
Copyright (C) 1999-2004 Eidos Interactive
Copyright (C) 2005-2020 Warzone 2100 Project
Warzone 2100 is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Warzone 2100 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file netplay.c
*
* Basic netcode.
*/
#include "lib/framework/frame.h"
#include "lib/framework/wzapp.h"
#include "lib/framework/string_ext.h"
#include "lib/framework/crc.h"
#include "lib/framework/file.h"
#include "lib/gamelib/gtime.h"
#include "lib/exceptionhandler/dumpinfo.h"
#include "src/console.h"
#include "src/component.h" // FIXME: we need to handle this better
#include "src/modding.h" // FIXME: we need to handle this better
#include <time.h> // for stats
#include <physfs.h>
#include "lib/framework/physfs_ext.h"
#include <string.h>
#include <memory>
#include <thread>
#include <atomic>
#include <limits>
#include <sodium.h>
#include "netplay.h"
#include "netlog.h"
#include "netreplay.h"
#include "netsocket.h"
#include "netpermissions.h"
#include <miniwget.h>
#if (defined(__GNUC__) || defined(__clang__)) && !defined(__INTEL_COMPILER)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wpedantic"
#endif
#include <miniupnpc.h>
#if (defined(__GNUC__) || defined(__clang__)) && !defined(__INTEL_COMPILER)
# pragma GCC diagnostic pop
#endif
#include <upnpcommands.h>
// Enforce minimum MINIUPNPC_API_VERSION
#if !defined(MINIUPNPC_API_VERSION) || (MINIUPNPC_API_VERSION < 9)
#error lib/netplay requires MINIUPNPC_API_VERSION >= 9
#endif
#include "src/multistat.h"
#include "src/multijoin.h"
#include "src/multiint.h"
#include "src/multiplay.h"
#include "src/hci/quickchat.h"
#include "src/warzoneconfig.h"
#include "src/version.h"
#include "src/loadsave.h"
#include "src/activity.h"
#include "src/stdinreader.h"
#include <LRUCache11/LRUCache11.hpp>
#if defined (WZ_OS_MAC)
# include "lib/framework/cocoa_wrapper.h"
#endif
#if defined(WZ_OS_LINUX) && defined(__GLIBC__)
#include <execinfo.h> // Nonfatal runtime backtraces.
#endif // defined(WZ_OS_LINUX) && defined(__GLIBC__)
// WARNING !!! This is initialised via configuration.c !!!
char masterserver_name[255] = {'\0'};
static unsigned int masterserver_port = 0, gameserver_port = 0;
static bool bJoinPrefTryIPv6First = true;
// This is for command line argument override
// Disables port saving and reading from/to config
bool netGameserverPortOverride = false;
#define NET_TIMEOUT_DELAY 2500 // we wait this amount of time for socket activity
#define NET_READ_TIMEOUT 0
/*
* === Using new socket code, this might not hold true any longer ===
* NOTE /rant: If the buffer size isn't big enough, it will invalidate the socket.
* Which means that we need to allocate a buffer big enough to handle worst case
* situations.
* reference: MaxMsgSize in netplay.h (currently set to 16K)
*
*/
#define NET_BUFFER_SIZE (MaxMsgSize) // Would be 16K
#define UPNP_SUCCESS 1
#define UPNP_ERROR_DEVICE_NOT_FOUND -1
#define UPNP_ERROR_CONTROL_NOT_AVAILABLE -2
// For NET_JOIN messages
enum NET_JOIN_PLAYERTYPE : uint8_t {
NET_JOIN_PLAYER = 0,
NET_JOIN_SPECTATOR = 1,
};
// ////////////////////////////////////////////////////////////////////////
// Function prototypes
static void NETplayerLeaving(UDWORD player); // Cleanup sockets on player leaving (nicely)
static void NETplayerDropped(UDWORD player); // Broadcast NET_PLAYER_DROPPED & cleanup
static void NETallowJoining();
static void recvDebugSync(NETQUEUE queue);
static void NETfixPlayerCount();
/*
* Network globals, these are part of the new network API
*/
SYNC_COUNTER sync_counter; // keeps track on how well we are in sync
// ////////////////////////////////////////////////////////////////////////
// Types
std::atomic_int upnp_status;
struct Statistic
{
size_t sent;
size_t received;
};
struct NETSTATS // data regarding the last one second or so.
{
Statistic rawBytes; // Number of actual bytes, in about 1 sec.
Statistic uncompressedBytes; // Number of bytes sent, before compression, in about 1 sec.
Statistic packets; // Number of calls to writeAll, in about 1 sec.
};
struct NET_PLAYER_DATA
{
uint16_t size;
void *data;
size_t buffer_size;
};
#define SERVER_UPDATE_MIN_INTERVAL 7 * GAME_TICKS_PER_SEC
#define SERVER_UPDATE_MAX_INTERVAL 25 * GAME_TICKS_PER_SEC
class LobbyServerConnectionHandler
{
public:
bool connect();
bool disconnect();
void sendUpdate();
void run();
private:
void sendUpdateNow();
void sendKeepAlive();
inline bool canSendServerUpdateNow()
{
return (currentState == LobbyConnectionState::Connected)
&& (realTime - lastServerUpdate >= SERVER_UPDATE_MIN_INTERVAL);
}
inline bool shouldSendServerKeepAliveNow()
{
return (currentState == LobbyConnectionState::Connected)
&& (realTime - lastServerUpdate >= SERVER_UPDATE_MAX_INTERVAL);
}
private:
enum class LobbyConnectionState
{
Disconnected,
Connecting_WaitingForResponse,
Connected
};
LobbyConnectionState currentState = LobbyConnectionState::Disconnected;
Socket *rs_socket = nullptr;
SocketSet* waitingForConnectionFinalize = nullptr;
uint32_t lastConnectionTime = 0;
uint32_t lastServerUpdate = 0;
bool queuedServerUpdate = false;
};
class PlayerManagementRecord
{
public:
void clear()
{
identitiesMovedToSpectatorsByHost.clear();
ipsMovedToSpectatorsByHost.clear();
}
void movedPlayerToSpectators(const PLAYER& player, const EcKey::Key& publicIdentity, bool byHost)
{
if (!byHost) { return; }
ipsMovedToSpectatorsByHost.insert(player.IPtextAddress);
identitiesMovedToSpectatorsByHost.insert(base64Encode(publicIdentity));
}
void movedSpectatorToPlayers(const PLAYER& player, const EcKey::Key& publicIdentity, bool byHost)
{
if (!byHost) { return; }
ipsMovedToSpectatorsByHost.erase(player.IPtextAddress);
identitiesMovedToSpectatorsByHost.erase(base64Encode(publicIdentity));
}
bool hostMovedPlayerToSpectators(const std::string& ipAddress)
{
return ipsMovedToSpectatorsByHost.count(ipAddress) > 0;
}
bool hostMovedPlayerToSpectators(const EcKey::Key& publicIdentity)
{
return identitiesMovedToSpectatorsByHost.count(base64Encode(publicIdentity)) > 0;
}
private:
std::unordered_set<std::string> identitiesMovedToSpectatorsByHost;
std::unordered_set<std::string> ipsMovedToSpectatorsByHost;
};
// ////////////////////////////////////////////////////////////////////////
// Variables
NETPLAY NetPlay;
static bool allow_joining = false;
static bool server_not_there = false;
static GAMESTRUCT gamestruct;
static std::vector<WZFile> DownloadingWzFiles;
// update flags
bool netPlayersUpdated;
/**
* Socket used for these purposes:
* * Host a game, be a server.
* * Connect to the lobby server.
* * Join a server for a game.
*/
static Socket *tcp_socket = nullptr; ///< Socket used to talk to a lobby server (hosts also seem to temporarily act as lobby servers while the client negotiates joining the game), or to listen for clients (if we're the host, in which case we use rs_socket (declaration hidden somewhere inside a function) to talk to the lobby server).
static Socket *bsocket = nullptr; ///< Socket used to talk to the host (clients only). If bsocket != NULL, then tcp_socket == NULL.
static Socket *connected_bsocket[MAX_CONNECTED_PLAYERS] = { nullptr }; ///< Sockets used to talk to clients (host only).
static SocketSet *socket_set = nullptr;
WZ_THREAD *upnpdiscover;
static struct UPNPUrls urls;
static struct IGDdatas data;
// local ip address
static char lanaddr[40];
static char externalIPAddress[40];
/**
* Used for connections with clients.
*/
#define NET_PING_TMP_PING_CHALLENGE_SIZE 128
struct TmpSocketInfo
{
std::string ip;
std::chrono::steady_clock::time_point connectTime;
char buffer[10] = {'\0'};
size_t usedBuffer = 0;
std::vector<uint8_t> connectChallenge;
enum class TmpConnectState
{
None,
PendingInitialConnect,
PendingJoinRequest
};
TmpConnectState connectState;
void reset()
{
ip.clear();
connectTime = std::chrono::steady_clock::time_point();
memset(buffer, 0, sizeof(buffer));
usedBuffer = 0;
connectChallenge.clear();
connectState = TmpConnectState::None;
}
};
static Socket *tmp_socket[MAX_TMP_SOCKETS] = { nullptr }; ///< Sockets used to talk to clients which have not yet been assigned a player number (host only).
static std::array<TmpSocketInfo, MAX_TMP_SOCKETS> tmp_connectState;
static std::unordered_map<std::string, size_t> tmp_pendingIPs;
static lru11::Cache<std::string, size_t> tmp_badIPs(512, 64);
static SocketSet *tmp_socket_set = nullptr;
static int32_t NetGameFlags[4] = { 0, 0, 0, 0 };
char iptoconnect[PATH_MAX] = "\0"; // holds IP/hostname from command line
bool cliConnectToIpAsSpectator = false; // for cli option
static NETSTATS nStats = {{0, 0}, {0, 0}, {0, 0}};
static NETSTATS nStatsLastSec = {{0, 0}, {0, 0}, {0, 0}};
static NETSTATS nStatsSecondLastSec = {{0, 0}, {0, 0}, {0, 0}};
static const NETSTATS nZeroStats = {{0, 0}, {0, 0}, {0, 0}};
static int nStatsLastUpdateTime = 0;
unsigned NET_PlayerConnectionStatus[CONNECTIONSTATUS_NORMAL][MAX_CONNECTED_PLAYERS];
std::vector<optional<uint32_t>> NET_waitingForIndexChangeAckSince = std::vector<optional<uint32_t>>(MAX_CONNECTED_PLAYERS, nullopt); ///< If waiting for the client to acknowledge a player index change, this is the realTime we started waiting
static LobbyServerConnectionHandler lobbyConnectionHandler;
static PlayerManagementRecord playerManagementRecord;
// ////////////////////////////////////////////////////////////////////////////
/************************************************************************************
** NOTE (!) Increment NETCODE_VERSION_MINOR on each release.
**
************************************************************************************
**/
static char const *versionString = version_getVersionString();
#include "lib/netplay/netplay_config.h"
static inline bool physfs_file_safe_close_impl(PHYSFS_file* f)
{
if (!f)
{
return false;
}
if (!PHYSFS_isInit())
{
debug(LOG_INFO, "PhysFS isn't init - ignoring attempt to close (likely at program shutdown?)");
return false;
}
PHYSFS_close(f);
f = nullptr;
return true;
}
void physfs_file_safe_close(PHYSFS_file* f)
{
physfs_file_safe_close_impl(f);
}
WZFile::~WZFile()
{ }
bool WZFile::closeFile()
{
if (!handle_)
{
return false;
}
PHYSFS_file *file = handle_.release();
return physfs_file_safe_close_impl(file);
}
const std::vector<WZFile>& NET_getDownloadingWzFiles()
{
return DownloadingWzFiles;
}
void NET_addDownloadingWZFile(WZFile&& newFile)
{
DownloadingWzFiles.push_back(std::move(newFile));
}
void NET_clearDownloadingWZFiles()
{
// if we were in a middle of transferring a file, then close the file handle
for (auto &file : DownloadingWzFiles)
{
debug(LOG_NET, "closing aborted file");
file.closeFile();
ASSERT(!file.filename.empty(), "filename must not be empty");
PHYSFS_delete(file.filename.c_str()); // delete incomplete (map) file
}
DownloadingWzFiles.clear();
}
NETPLAY::NETPLAY()
{
players.resize(MAX_CONNECTED_PLAYERS);
scriptSetPlayerDataStrings.resize(MAX_PLAYERS);
playerReferences.resize(MAX_CONNECTED_PLAYERS);
for (auto i = 0; i < MAX_CONNECTED_PLAYERS; i++)
{
playerReferences[i] = std::make_shared<PlayerReference>(i);
}
}
bool NETisCorrectVersion(uint32_t game_version_major, uint32_t game_version_minor)
{
return (uint32_t)NETCODE_VERSION_MAJOR == game_version_major && (uint32_t)NETCODE_VERSION_MINOR == game_version_minor;
}
bool NETisGreaterVersion(uint32_t game_version_major, uint32_t game_version_minor)
{
return (game_version_major > NETCODE_VERSION_MAJOR) || ((game_version_major == NETCODE_VERSION_MAJOR) && (game_version_minor > NETCODE_VERSION_MINOR));
}
uint32_t NETGetMajorVersion()
{
return NETCODE_VERSION_MAJOR;
}
uint32_t NETGetMinorVersion()
{
return NETCODE_VERSION_MINOR;
}
bool NETGameIsLocked()
{
return NetPlay.GamePassworded;
}
// Sets if the game is password protected or not
void NETGameLocked(bool flag)
{
NetPlay.GamePassworded = flag;
bool flagChanged = gamestruct.privateGame != (uint32_t)flag;
gamestruct.privateGame = flag;
if (allow_joining && NetPlay.isHost && flagChanged)
{
debug(LOG_NET, "Updating game locked status.");
NETregisterServer(WZ_SERVER_UPDATE);
}
if (flagChanged)
{
ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
}
NETlogEntry("Password is", SYNC_FLAG, NetPlay.GamePassworded);
debug(LOG_NET, "Passworded game is %s", NetPlay.GamePassworded ? "TRUE" : "FALSE");
}
SpectatorInfo SpectatorInfo::currentNetPlayState()
{
SpectatorInfo latestSpecInfo;
for (const auto& slot : NetPlay.players)
{
if (slot.isSpectator)
{
latestSpecInfo.totalSpectatorSlots++;
if (slot.allocated)
{
latestSpecInfo.spectatorsJoined++;
}
}
}
return latestSpecInfo;
}
SpectatorInfo NETGameGetSpectatorInfo()
{
if (NetPlay.isHost)
{
// we have this as part of the host current gamestruct
return SpectatorInfo::fromUint32(gamestruct.desc.dwUserFlags[1]);
}
else
{
return SpectatorInfo::currentNetPlayState();
}
}
void NETsetLobbyOptField(const char *Value, const NET_LOBBY_OPT_FIELD Field)
{
switch (Field)
{
case NET_LOBBY_OPT_FIELD::GNAME:
sstrcpy(gamestruct.name, Value);
break;
case NET_LOBBY_OPT_FIELD::MAPNAME:
sstrcpy(gamestruct.mapname, formatGameName(Value).toUtf8().c_str());
break;
case NET_LOBBY_OPT_FIELD::HOSTNAME:
sstrcpy(gamestruct.hostname, Value);
break;
default:
debug(LOG_WARNING, "Invalid field specified for NETsetGameOptField()");
break;
}
}
// Sets the game password
void NETsetGamePassword(const char *password)
{
sstrcpy(NetPlay.gamePassword, password);
debug(LOG_NET, "Password entered is: [%s]", NetPlay.gamePassword);
NETGameLocked(true);
}
// Resets the game password
void NETresetGamePassword()
{
NetPlay.gamePassword[0] = '\0';
debug(LOG_NET, "password was reset");
NETGameLocked(false);
}
// *********** Socket with buffer that read NETMSGs ******************
static size_t NET_fillBuffer(Socket **pSocket, SocketSet *pSocketSet, uint8_t *bufstart, int bufsize)
{
Socket *socket = *pSocket;
ssize_t size;
if (!socketReadReady(socket))
{
return 0;
}
size_t rawBytes;
size = readNoInt(socket, bufstart, bufsize, &rawBytes);
if ((size != 0 || !socketReadDisconnected(socket)) && size != SOCKET_ERROR)
{
nStats.rawBytes.received += rawBytes;
nStats.uncompressedBytes.received += size;
nStats.packets.received += 1;
return size;
}
else
{
if (size == 0)
{
debug(LOG_NET, "Connection closed from the other side");
NETlogEntry("Connection closed from the other side..", SYNC_FLAG, selectedPlayer);
}
else
{
debug(LOG_NET, "%s tcp_socket %p is now invalid", strSockError(getSockErr()), static_cast<void *>(socket));
}
// an error occurred, or the remote host has closed the connection.
if (pSocketSet != nullptr)
{
SocketSet_DelSocket(pSocketSet, socket);
}
ASSERT(size <= bufsize, "Socket buffer is too small!");
if (size > bufsize)
{
debug(LOG_ERROR, "Fatal connection error: buffer size of (%d) was too small, current byte count was %ld", bufsize, (long)size);
NETlogEntry("Fatal connection error: buffer size was too small!", SYNC_FLAG, selectedPlayer);
}
if (bsocket == socket)
{
debug(LOG_NET, "Host connection was lost!");
NETlogEntry("Host connection was lost!", SYNC_FLAG, selectedPlayer);
bsocket = nullptr;
//Game is pretty much over --should just end everything when HOST dies.
NetPlay.isHostAlive = false;
ingame.localJoiningInProgress = false;
setLobbyError(ERROR_NOERROR);
NETclose();
return 0;
}
socketClose(socket);
*pSocket = nullptr;
}
return 0;
}
static int playersPerTeam()
{
for (int v = game.maxPlayers - 1; v > 1; --v)
{
if (game.maxPlayers%v == 0)
{
return v;
}
}
return 1;
}
/**
* Resets network properties of a player to safe defaults. Player slots should always be in this state
* before attemtping to assign a connectign player to it.
*
* Used to reset the player slot in NET_InitPlayer and to reset players slot without modifying ai/team/
* position configuration for the players.
*/
static void initPlayerNetworkProps(int playerIndex)
{
NetPlay.players[playerIndex].allocated = false;
NetPlay.players[playerIndex].autoGame = false;
NetPlay.players[playerIndex].heartattacktime = 0;
NetPlay.players[playerIndex].heartbeat = true; // we always start with a heartbeat
NetPlay.players[playerIndex].kick = false;
NetPlay.players[playerIndex].ready = false;
if (NetPlay.players[playerIndex].wzFiles)
{
NetPlay.players[playerIndex].wzFiles->clear();
}
else
{
ASSERT(false, "PLAYERS.wzFiles is uninitialized??");
}
ingame.JoiningInProgress[playerIndex] = false;
ingame.PendingDisconnect[playerIndex] = false;
}
void NET_InitPlayer(uint32_t i, bool initPosition, bool initTeams, bool initSpectator)
{
ASSERT_OR_RETURN(, i < NetPlay.players.size(), "Invalid player_id: (%" PRIu32")", i);
initPlayerNetworkProps(i);
NetPlay.players[i].difficulty = AIDifficulty::DISABLED;
if (ingame.localJoiningInProgress)
{
// only clear name outside of games.
clearPlayerName(i);
}
if (initPosition)
{
setPlayerColour(i, i);
NetPlay.players[i].position = i;
NetPlay.players[i].team = initTeams && i < game.maxPlayers? i/playersPerTeam() : i;
}
if (NetPlay.bComms)
{
NetPlay.players[i].ai = AI_OPEN;
}
else
{
NetPlay.players[i].ai = 0;
}
NetPlay.players[i].faction = FACTION_NORMAL;
if (initSpectator)
{
NetPlay.players[i].isSpectator = false;
}
}
uint8_t NET_numHumanPlayers(void)
{
uint8_t RetVal = 0;
for (uint8_t Inc = 0; Inc < MAX_PLAYERS; ++Inc)
{
if (NetPlay.players[Inc].allocated && !NetPlay.players[Inc].isSpectator) ++RetVal;
}
return RetVal;
}
std::vector<uint8_t> NET_getHumanPlayers(void)
{
std::vector<uint8_t> RetVal;
RetVal.reserve(MAX_PLAYERS);
for (uint8_t Inc = 0; Inc < MAX_PLAYERS; ++Inc)
{
if (NetPlay.players[Inc].allocated && !NetPlay.players[Inc].isSpectator) RetVal.push_back(Inc);
}
return RetVal;
}
void NET_InitPlayers(bool initTeams, bool initSpectator)
{
for (unsigned i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
{
NET_InitPlayer(i, true, initTeams, initSpectator);
clearPlayerName(i);
NETinitQueue(NETnetQueue(i));
}
resetRecentScoreData();
NETinitQueue(NETbroadcastQueue());
NetPlay.hostPlayer = NET_HOST_ONLY; // right now, host starts always at index zero
NetPlay.playercount = 0;
DownloadingWzFiles.clear();
NET_waitingForIndexChangeAckSince = std::vector<optional<uint32_t>>(MAX_CONNECTED_PLAYERS, nullopt);
debug(LOG_NET, "Players initialized");
}
static void NETSendNPlayerInfoTo(uint32_t *index, uint32_t indexLen, unsigned to)
{
if (NetPlay.bComms && ingame.localJoiningInProgress)
{
ASSERT_HOST_ONLY(return);
}
NETbeginEncode(NETnetQueue(to), NET_PLAYER_INFO);
NETuint32_t(&indexLen);
for (unsigned n = 0; n < indexLen; ++n)
{
debug(LOG_NET, "sending player's (%u) info to all players", index[n]);
NETlogEntry("Sending player's info to all players", SYNC_FLAG, index[n]);
NETuint32_t(&index[n]);
NETbool(&NetPlay.players[index[n]].allocated);
NETbool(&NetPlay.players[index[n]].heartbeat);
NETbool(&NetPlay.players[index[n]].kick);
NETstring(NetPlay.players[index[n]].name, sizeof(NetPlay.players[index[n]].name));
NETuint32_t(&NetPlay.players[index[n]].heartattacktime);
NETint32_t(&NetPlay.players[index[n]].colour);
NETint32_t(&NetPlay.players[index[n]].position);
NETint32_t(&NetPlay.players[index[n]].team);
NETbool(&NetPlay.players[index[n]].ready);
NETint8_t(&NetPlay.players[index[n]].ai);
NETint8_t(reinterpret_cast<int8_t*>(&NetPlay.players[index[n]].difficulty));
NETuint8_t(reinterpret_cast<uint8_t *>(&NetPlay.players[index[n]].faction));
NETbool(&NetPlay.players[index[n]].isSpectator);
}
NETend();
ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
}
static void NETSendPlayerInfoTo(uint32_t index, unsigned to)
{
NETSendNPlayerInfoTo(&index, 1, to);
}
static void NETSendAllPlayerInfoTo(unsigned to)
{
static uint32_t indices[MAX_CONNECTED_PLAYERS];
for (int i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
{
indices[i] = i;
}
ASSERT_OR_RETURN(, NetPlay.isHost == true, "Invalid call for non-host");
NETSendNPlayerInfoTo(indices, ARRAY_SIZE(indices), to);
}
void NETBroadcastTwoPlayerInfo(uint32_t index1, uint32_t index2)
{
uint32_t indices[2] = {index1, index2};
NETSendNPlayerInfoTo(indices, 2, NET_ALL_PLAYERS);
}
void NETBroadcastPlayerInfo(uint32_t index)
{
NETSendPlayerInfoTo(index, NET_ALL_PLAYERS);
}
// Checks if there are *any* open slots (player *OR* spectator) for an incoming connection
static bool NET_HasAnyOpenSlots()
{
for (int i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
{
if (i == scavengerSlot())
{
// do not offer up the scavenger slot (this really needs to be refactored later - why is this a variable slot index?!?)
continue;
}
if (i == PLAYER_FEATURE)
{
// do not offer up this "player feature" slot - TODO: maybe remove the need for this slot?
continue;
}
PLAYER const &p = NetPlay.players[i];
if (!p.allocated && p.ai == AI_OPEN)
{
return true;
}
}
return false;
}
static optional<uint32_t> NET_FindOpenSlotForPlayer(bool forceTakeLowestAvailablePlayerNumber = false, optional<bool> asSpectator = false)
{
int index = -1;
int position = INT_MAX;
for (int i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
{
if (!forceTakeLowestAvailablePlayerNumber && !asSpectator.value_or(false) && (i >= game.maxPlayers || i >= MAX_PLAYERS || NetPlay.players[i].position >= game.maxPlayers))
{
// Player slots are only supported where the player index and the player position is <= game.maxPlayers
// Skip otherwise
continue;
}
if (i == scavengerSlot())
{
// do not offer up the scavenger slot (this really needs to be refactored later - why is this a variable slot index?!?)
continue;
}
if (i == PLAYER_FEATURE)
{
// do not offer up this "player feature" slot - TODO: maybe remove the need for this slot?
continue;
}
// find the lowest "position" slot that is available (unless forceTakeLowestAvailablePlayerNumber is set, in which case just take the first available)
PLAYER const &p = NetPlay.players[i];
if (!p.allocated && p.ai == AI_OPEN && p.position < position && (!asSpectator.has_value() || asSpectator.value() == p.isSpectator))
{
index = i;
position = p.position;
if (forceTakeLowestAvailablePlayerNumber)
{
break;
}
}
}
if (index == -1)
{
return nullopt;
}
return static_cast<uint32_t>(index);
}
static optional<uint32_t> NET_CreatePlayer(char const *name, bool forceTakeLowestAvailablePlayerNumber = false, optional<bool> asSpectator = false)
{
optional<uint32_t> index = NET_FindOpenSlotForPlayer(forceTakeLowestAvailablePlayerNumber, asSpectator);
if (!index.has_value())
{
debug(LOG_ERROR, "Could not find place for player %s", name);
NETlogEntry("Could not find a place for player!", SYNC_FLAG, -1);
return nullopt;
}
char buf[250] = {'\0'};
ssprintf(buf, "A new player has been created. Player, %s, is set to slot %u", name, index.value());
debug(LOG_NET, "%s", buf);
NETlogEntry(buf, SYNC_FLAG, index.value());
NET_InitPlayer(index.value(), false); // re-init everything
NetPlay.players[index.value()].allocated = true;
NetPlay.players[index.value()].difficulty = AIDifficulty::HUMAN;
setPlayerName(index.value(), name);
if (!NetPlay.players[index.value()].isSpectator)
{
++NetPlay.playercount;
}
++sync_counter.joins;
return index;
}
static void NET_DestroyPlayer(unsigned int index, bool suppressActivityUpdates = false)
{
ASSERT_OR_RETURN(, index < NetPlay.players.size(), "Invalid player_id: (%" PRIu32")", index);
debug(LOG_NET, "Freeing slot %u for a new player", index);
NETlogEntry("Freeing slot for a new player.", SYNC_FLAG, index);
bool wasAllocated = NetPlay.players[index].allocated;
if (NetPlay.players[index].allocated)
{
NetPlay.players[index].allocated = false;
if (!NetPlay.players[index].isSpectator)
{
NetPlay.playercount--;
}
gamestruct.desc.dwCurrentPlayers = NetPlay.playercount;
if (allow_joining && NetPlay.isHost)
{
// Update player count in the lobby by disconnecting
// and reconnecting
NETregisterServer(WZ_SERVER_UPDATE);
}
}
NET_InitPlayer(index, false); // reinitialize
if (wasAllocated && !suppressActivityUpdates)
{
ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
}
}
bool NETplayerHasConnection(uint32_t index)
{
ASSERT_HOST_ONLY(return false);
ASSERT_OR_RETURN(false, index < MAX_CONNECTED_PLAYERS, "Invalid index: %" PRIu32, index);
return connected_bsocket[index] != nullptr;
}
/**
* @note Connection dropped. Handle it gracefully.
* \param index
*/
static void NETplayerClientDisconnect(uint32_t index)
{
if (!NetPlay.isHost)
{
ASSERT(false, "Host only routine detected for client!");
return;
}
if (connected_bsocket[index])
{
debug(LOG_NET, "Player (%u) has left unexpectedly, closing socket %p", index, static_cast<void *>(connected_bsocket[index]));
NETplayerLeaving(index);
NETlogEntry("Player has left unexpectedly.", SYNC_FLAG, index);
// Announce to the world. This was really icky, because we may have been calling the send
// function recursively. We really ought to have had a send queue, and now we finally do...
if (ingame.localJoiningInProgress) // Only if game hasn't actually started yet.
{
NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_DROPPED);
NETuint32_t(&index);
NETend();
}
}
else
{
debug(LOG_ERROR, "Player (%u) has left unexpectedly - but socket already closed?", index);
}
}
/**
* @note When a player leaves nicely (ie, we got a NET_PLAYER_LEAVING
* message), we clean up the socket that we used.
* \param index
*/
static void NETplayerLeaving(UDWORD index)
{
ASSERT(index < MAX_CONNECTED_PLAYERS, "Invalid index: %" PRIu32, index);
if (connected_bsocket[index])
{
debug(LOG_NET, "Player (%u) has left, closing socket %p", index, static_cast<void *>(connected_bsocket[index]));
NETlogEntry("Player has left nicely.", SYNC_FLAG, index);
// Although we can get a error result from DelSocket, it don't really matter here.
SocketSet_DelSocket(socket_set, connected_bsocket[index]);
socketClose(connected_bsocket[index]);
connected_bsocket[index] = nullptr;
}
else
{
debug(LOG_NET, "Player (%u) has left nicely, socket already closed?", index);
}
sync_counter.left++;
bool wasSpectator = NetPlay.players[index].isSpectator;
MultiPlayerLeave(index); // more cleanup
if (ingame.localJoiningInProgress) // Only if game hasn't actually started yet.
{
NET_DestroyPlayer(index); // sets index player's array to false
if (!wasSpectator)
{
resetReadyStatus(false); // reset ready status for all players
}
}
}
/**
* @note When a player's connection is broken we broadcast the NET_PLAYER_DROPPED
* message.
* \param index
*/
static void NETplayerDropped(UDWORD index)
{
ASSERT_OR_RETURN(, index < NetPlay.players.size(), "Invalid index: %" PRIu32, index);
uint32_t id = index;
if (!NetPlay.isHost)
{
ASSERT(false, "Host only routine detected for client!");
return;
}
sync_counter.drops++;
bool wasSpectator = NetPlay.players[index].isSpectator;
MultiPlayerLeave(id); // more cleanup
if (ingame.localJoiningInProgress) // Only if game hasn't actually started yet.
{
// Send message type specifically for dropped / disconnects
NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_DROPPED);
NETuint32_t(&id);
NETend();
debug(LOG_INFO, "sending NET_PLAYER_DROPPED for player %d", id);
NET_DestroyPlayer(id); // just clears array
if (!wasSpectator)
{
resetReadyStatus(false); // reset ready status for all players
}
}
NETsetPlayerConnectionStatus(CONNECTIONSTATUS_PLAYER_DROPPED, id);
}
/**
* @note Cleanup for when a player is kicked.
* \param index
*/
void NETplayerKicked(UDWORD index)
{
ASSERT_OR_RETURN(, index < MAX_CONNECTED_PLAYERS, "NETplayerKicked invalid player_id: (%" PRIu32")", index);
// kicking a player counts as "leaving nicely", since "nicely" in this case
// simply means "there wasn't a connection error."
debug(LOG_INFO, "Player %u was kicked.", index);
sync_counter.kicks++;
NETlogEntry("Player was kicked.", SYNC_FLAG, index);
NETplayerLeaving(index); // need to close socket for the player that left.
NETsetPlayerConnectionStatus(CONNECTIONSTATUS_PLAYER_LEAVING, index);
}
// ////////////////////////////////////////////////////////////////////////
// rename the local player
bool NETchangePlayerName(UDWORD index, char *newName)
{
if (!NetPlay.bComms)