1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3
4#include "client.h"
5
6#include "demoedit.h"
7#include "friends.h"
8#include "serverbrowser.h"
9
10#include <base/bytes.h>
11#include <base/crashdump.h>
12#include <base/dbg.h>
13#include <base/fs.h>
14#include <base/hash.h>
15#include <base/hash_ctxt.h>
16#include <base/io.h>
17#include <base/log.h>
18#include <base/logger.h>
19#include <base/math.h>
20#include <base/mem.h>
21#include <base/os.h>
22#include <base/process.h>
23#include <base/secure.h>
24#include <base/str.h>
25#include <base/thread.h>
26#include <base/time.h>
27#include <base/windows.h>
28
29#include <engine/config.h>
30#include <engine/console.h>
31#include <engine/discord.h>
32#include <engine/editor.h>
33#include <engine/engine.h>
34#include <engine/external/json-parser/json.h>
35#include <engine/favorites.h>
36#include <engine/graphics.h>
37#include <engine/http.h>
38#include <engine/input.h>
39#include <engine/keys.h>
40#include <engine/map.h>
41#include <engine/notifications.h>
42#include <engine/serverbrowser.h>
43#include <engine/shared/assertion_logger.h>
44#include <engine/shared/compression.h>
45#include <engine/shared/config.h>
46#include <engine/shared/demo.h>
47#include <engine/shared/fifo.h>
48#include <engine/shared/filecollection.h>
49#include <engine/shared/masterserver.h>
50#include <engine/shared/network.h>
51#include <engine/shared/packer.h>
52#include <engine/shared/protocol.h>
53#include <engine/shared/protocol7.h>
54#include <engine/shared/protocol_ex.h>
55#include <engine/shared/protocolglue.h>
56#include <engine/shared/rust_version.h>
57#include <engine/shared/snapshot.h>
58#include <engine/shared/uuid_manager.h>
59#include <engine/sound.h>
60#include <engine/steam.h>
61#include <engine/storage.h>
62#include <engine/textrender.h>
63
64#include <generated/protocol.h>
65#include <generated/protocol7.h>
66#include <generated/protocolglue.h>
67
68#include <game/localization.h>
69#include <game/version.h>
70
71#if defined(CONF_VIDEORECORDER)
72#include "video.h"
73#endif
74
75#if defined(CONF_PLATFORM_ANDROID)
76#include <android/android_main.h>
77#elif defined(CONF_PLATFORM_IOS)
78#include <ios/ios_main.h>
79#endif
80
81#if defined(CONF_PLATFORM_EMSCRIPTEN)
82#include <emscripten/emscripten.h>
83#endif
84
85#include "SDL.h"
86#ifdef main
87#undef main
88#endif
89
90#include <algorithm>
91#include <chrono>
92#include <iterator>
93#include <limits>
94#include <stack>
95#include <thread>
96#include <tuple>
97
98using namespace std::chrono_literals;
99
100static constexpr ColorRGBA CLIENT_NETWORK_PRINT_COLOR = ColorRGBA(0.7f, 1, 0.7f, 1.0f);
101static constexpr ColorRGBA CLIENT_NETWORK_PRINT_ERROR_COLOR = ColorRGBA(1.0f, 0.25f, 0.25f, 1.0f);
102
103CSnapshotDelta *CClient::SnapshotDelta()
104{
105 if(IsSixup())
106 {
107 return &m_SnapshotDeltaSixup;
108 }
109 return &m_SnapshotDelta;
110}
111
112CClient::CClient() :
113 m_DemoPlayer(&m_SnapshotDelta, &m_SnapshotDeltaSixup, true, [&]() { UpdateDemoIntraTimers(); }),
114 m_aInputtimeMarginGraphs{{128, 2, true}, {128, 2, true}},
115 m_aGametimeMarginGraphs{{128, 2, true}, {128, 2, true}},
116 m_FpsGraph(4096, 0, true)
117{
118 m_StateStartTime = time_get();
119 for(auto &DemoRecorder : m_aDemoRecorders)
120 DemoRecorder = CDemoRecorder(&m_SnapshotDelta);
121 for(auto &DemoRecorder : m_aDemoRecordersSixup)
122 DemoRecorder = CDemoRecorder(&m_SnapshotDeltaSixup);
123 m_LastRenderTime = time_get();
124 mem_zero(block: m_aInputs, size: sizeof(m_aInputs));
125 mem_zero(block: m_aapSnapshots, size: sizeof(m_aapSnapshots));
126 for(auto &SnapshotStorage : m_aSnapshotStorage)
127 SnapshotStorage.Init();
128 mem_zero(block: m_aDemorecSnapshotHolders, size: sizeof(m_aDemorecSnapshotHolders));
129 m_CurrentServerInfo = {};
130 mem_zero(block: &m_Checksum, size: sizeof(m_Checksum));
131 for(auto &GameTime : m_aGameTime)
132 GameTime.Init(Target: 0);
133 m_PredictedTime.Init(Target: 0);
134
135 m_Sixup = false;
136}
137
138// ----- send functions -----
139static inline bool RepackMsg(const CMsgPacker *pMsg, CPacker &Packer, bool Sixup)
140{
141 int MsgId = pMsg->m_MsgId;
142 Packer.Reset();
143
144 if(Sixup && !pMsg->m_NoTranslate)
145 {
146 if(pMsg->m_System)
147 {
148 if(MsgId >= OFFSET_UUID)
149 ;
150 else if(MsgId == NETMSG_INFO || MsgId == NETMSG_REQUEST_MAP_DATA)
151 ;
152 else if(MsgId == NETMSG_READY)
153 MsgId = protocol7::NETMSG_READY;
154 else if(MsgId == NETMSG_RCON_CMD)
155 MsgId = protocol7::NETMSG_RCON_CMD;
156 else if(MsgId == NETMSG_ENTERGAME)
157 MsgId = protocol7::NETMSG_ENTERGAME;
158 else if(MsgId == NETMSG_INPUT)
159 MsgId = protocol7::NETMSG_INPUT;
160 else if(MsgId == NETMSG_RCON_AUTH)
161 MsgId = protocol7::NETMSG_RCON_AUTH;
162 else if(MsgId == NETMSG_PING)
163 MsgId = protocol7::NETMSG_PING;
164 else
165 {
166 log_error("net", "0.7 DROP send sys %d", MsgId);
167 return false;
168 }
169 }
170 else
171 {
172 if(MsgId >= 0 && MsgId < OFFSET_UUID)
173 MsgId = Msg_SixToSeven(a: MsgId);
174
175 if(MsgId < 0)
176 return false;
177 }
178 }
179
180 if(pMsg->m_MsgId < OFFSET_UUID)
181 {
182 Packer.AddInt(i: (MsgId << 1) | (pMsg->m_System ? 1 : 0));
183 }
184 else
185 {
186 Packer.AddInt(i: pMsg->m_System ? 1 : 0); // NETMSG_EX, NETMSGTYPE_EX
187 g_UuidManager.PackUuid(Id: pMsg->m_MsgId, pPacker: &Packer);
188 }
189 Packer.AddRaw(pData: pMsg->Data(), Size: pMsg->Size());
190
191 return true;
192}
193
194int CClient::SendMsg(int Conn, CMsgPacker *pMsg, int Flags)
195{
196 CNetChunk Packet;
197
198 if(State() == IClient::STATE_OFFLINE)
199 return 0;
200
201 // repack message (inefficient)
202 CPacker Pack;
203 if(!RepackMsg(pMsg, Packer&: Pack, Sixup: IsSixup()))
204 return 0;
205
206 mem_zero(block: &Packet, size: sizeof(CNetChunk));
207 Packet.m_ClientId = 0;
208 Packet.m_pData = Pack.Data();
209 Packet.m_DataSize = Pack.Size();
210
211 if(Flags & MSGFLAG_VITAL)
212 Packet.m_Flags |= NETSENDFLAG_VITAL;
213 if(Flags & MSGFLAG_FLUSH)
214 Packet.m_Flags |= NETSENDFLAG_FLUSH;
215
216 if((Flags & MSGFLAG_RECORD) && Conn == g_Config.m_ClDummy)
217 {
218 for(auto &DemoRecorder : DemoRecorders())
219 {
220 if(DemoRecorder.IsRecording())
221 {
222 DemoRecorder.RecordMessage(pData: Packet.m_pData, Size: Packet.m_DataSize);
223 }
224 }
225 }
226
227 if(!(Flags & MSGFLAG_NOSEND))
228 {
229 m_aNetClient[Conn].Send(pChunk: &Packet);
230 }
231
232 return 0;
233}
234
235int CClient::SendMsgActive(CMsgPacker *pMsg, int Flags)
236{
237 return SendMsg(Conn: g_Config.m_ClDummy, pMsg, Flags);
238}
239
240void CClient::SendInfo(int Conn)
241{
242 CMsgPacker MsgVer(NETMSG_CLIENTVER, true);
243 MsgVer.AddRaw(pData: &m_ConnectionId, Size: sizeof(m_ConnectionId));
244 MsgVer.AddInt(i: GameClient()->DDNetVersion());
245 MsgVer.AddString(pStr: GameClient()->DDNetVersionStr());
246 SendMsg(Conn, pMsg: &MsgVer, Flags: MSGFLAG_VITAL);
247
248 if(IsSixup())
249 {
250 CMsgPacker Msg(NETMSG_INFO, true);
251 Msg.AddString(GAME_NETVERSION7, Limit: 128);
252 Msg.AddString(pStr: Config()->m_Password);
253 Msg.AddInt(i: GameClient()->ClientVersion7());
254 SendMsg(Conn, pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
255 return;
256 }
257
258 CMsgPacker Msg(NETMSG_INFO, true);
259 Msg.AddString(pStr: GameClient()->NetVersion());
260 Msg.AddString(pStr: m_aPassword);
261 SendMsg(Conn, pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
262}
263
264void CClient::SendEnterGame(int Conn)
265{
266 CMsgPacker Msg(NETMSG_ENTERGAME, true);
267 SendMsg(Conn, pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
268}
269
270void CClient::SendReady(int Conn)
271{
272 CMsgPacker Msg(NETMSG_READY, true);
273 SendMsg(Conn, pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
274}
275
276void CClient::SendMapRequest()
277{
278 dbg_assert(!m_MapdownloadFileTemp, "Map download already in progress");
279 m_MapdownloadFileTemp = Storage()->OpenFile(pFilename: m_aMapdownloadFilenameTemp, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
280 if(IsSixup())
281 {
282 CMsgPacker MsgP(protocol7::NETMSG_REQUEST_MAP_DATA, true, true);
283 SendMsg(Conn: CONN_MAIN, pMsg: &MsgP, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
284 }
285 else
286 {
287 CMsgPacker Msg(NETMSG_REQUEST_MAP_DATA, true);
288 Msg.AddInt(i: m_MapdownloadChunk);
289 SendMsg(Conn: CONN_MAIN, pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
290 }
291}
292
293void CClient::RconAuth(const char *pName, const char *pPassword, bool Dummy)
294{
295 if(m_aRconAuthed[Dummy] != 0)
296 return;
297
298 if(pName != m_aRconUsername)
299 str_copy(dst&: m_aRconUsername, src: pName);
300 if(pPassword != m_aRconPassword)
301 str_copy(dst&: m_aRconPassword, src: pPassword);
302
303 if(IsSixup())
304 {
305 CMsgPacker Msg7(protocol7::NETMSG_RCON_AUTH, true, true);
306 Msg7.AddString(pStr: pPassword);
307 SendMsg(Conn: Dummy, pMsg: &Msg7, Flags: MSGFLAG_VITAL);
308 return;
309 }
310
311 CMsgPacker Msg(NETMSG_RCON_AUTH, true);
312 Msg.AddString(pStr: pName);
313 Msg.AddString(pStr: pPassword);
314 Msg.AddInt(i: 1);
315 SendMsg(Conn: Dummy, pMsg: &Msg, Flags: MSGFLAG_VITAL);
316}
317
318void CClient::Rcon(const char *pCmd)
319{
320 CMsgPacker Msg(NETMSG_RCON_CMD, true);
321 Msg.AddString(pStr: pCmd);
322 SendMsgActive(pMsg: &Msg, Flags: MSGFLAG_VITAL);
323}
324
325float CClient::GotRconCommandsPercentage() const
326{
327 if(m_ExpectedRconCommands <= 0)
328 return -1.0f;
329 if(m_GotRconCommands > m_ExpectedRconCommands)
330 return -1.0f;
331
332 return (float)m_GotRconCommands / (float)m_ExpectedRconCommands;
333}
334
335float CClient::GotMaplistPercentage() const
336{
337 if(m_ExpectedMaplistEntries <= 0)
338 return -1.0f;
339 if(m_vMaplistEntries.size() > (size_t)m_ExpectedMaplistEntries)
340 return -1.0f;
341
342 return (float)m_vMaplistEntries.size() / (float)m_ExpectedMaplistEntries;
343}
344
345bool CClient::ConnectionProblems() const
346{
347 return m_aNetClient[g_Config.m_ClDummy].GotProblems(MaxLatency: MaxLatencyTicks() * time_freq() / GameTickSpeed());
348}
349
350void CClient::SendInput()
351{
352 int64_t Now = time_get();
353
354 if(m_aPredTick[g_Config.m_ClDummy] <= 0)
355 return;
356
357 bool Force = false;
358 // fetch input
359 for(int Dummy = 0; Dummy < NUM_DUMMIES; Dummy++)
360 {
361 if(!DummyConnected() && Dummy != 0)
362 {
363 break;
364 }
365 int i = g_Config.m_ClDummy ^ Dummy;
366 int Size = GameClient()->OnSnapInput(pData: m_aInputs[i][m_aCurrentInput[i]].m_aData, Dummy, Force);
367
368 if(Size)
369 {
370 // pack input
371 CMsgPacker Msg(NETMSG_INPUT, true);
372 Msg.AddInt(i: m_aAckGameTick[i]);
373 Msg.AddInt(i: m_aPredTick[g_Config.m_ClDummy]);
374 Msg.AddInt(i: Size);
375
376 m_aInputs[i][m_aCurrentInput[i]].m_Tick = m_aPredTick[g_Config.m_ClDummy];
377 m_aInputs[i][m_aCurrentInput[i]].m_PredictedTime = m_PredictedTime.Get(Now);
378 m_aInputs[i][m_aCurrentInput[i]].m_PredictionMargin = PredictionMargin() * time_freq() / 1000;
379 m_aInputs[i][m_aCurrentInput[i]].m_Time = Now;
380
381 // pack it
382 for(int k = 0; k < Size / 4; k++)
383 {
384 static const int FlagsOffset = offsetof(CNetObj_PlayerInput, m_PlayerFlags) / sizeof(int);
385 if(k == FlagsOffset && IsSixup())
386 {
387 int PlayerFlags = m_aInputs[i][m_aCurrentInput[i]].m_aData[k];
388 Msg.AddInt(i: PlayerFlags_SixToSeven(Flags: PlayerFlags));
389 }
390 else
391 {
392 Msg.AddInt(i: m_aInputs[i][m_aCurrentInput[i]].m_aData[k]);
393 }
394 }
395
396 m_aCurrentInput[i]++;
397 m_aCurrentInput[i] %= 200;
398
399 SendMsg(Conn: i, pMsg: &Msg, Flags: MSGFLAG_FLUSH);
400 // ugly workaround for dummy. we need to send input with dummy to prevent
401 // prediction time resets. but if we do it too often, then it's
402 // impossible to use grenade with frozen dummy that gets hammered...
403 if(g_Config.m_ClDummyCopyMoves || m_aCurrentInput[i] % 2)
404 Force = true;
405 }
406 }
407}
408
409const char *CClient::LatestVersion() const
410{
411 return m_aVersionStr;
412}
413
414// TODO: OPT: do this a lot smarter!
415int *CClient::GetInput(int Tick, int IsDummy) const
416{
417 int Best = -1;
418 const int d = IsDummy ^ g_Config.m_ClDummy;
419 for(int i = 0; i < 200; i++)
420 {
421 if(m_aInputs[d][i].m_Tick != -1 && m_aInputs[d][i].m_Tick <= Tick && (Best == -1 || m_aInputs[d][Best].m_Tick < m_aInputs[d][i].m_Tick))
422 Best = i;
423 }
424
425 if(Best != -1)
426 return (int *)m_aInputs[d][Best].m_aData;
427 return nullptr;
428}
429
430// ------ state handling -----
431void CClient::SetState(EClientState State)
432{
433 if(m_State == IClient::STATE_QUITTING || m_State == IClient::STATE_RESTARTING)
434 return;
435 if(m_State == State)
436 return;
437
438 if(g_Config.m_Debug)
439 {
440 char aBuf[64];
441 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "state change. last=%d current=%d", m_State, State);
442 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "client", pStr: aBuf);
443 }
444
445 const EClientState OldState = m_State;
446 m_State = State;
447
448 m_StateStartTime = time_get();
449 GameClient()->OnStateChange(NewState: m_State, OldState);
450
451 if(State == IClient::STATE_OFFLINE && m_ReconnectTime == 0)
452 {
453 if(g_Config.m_ClReconnectFull > 0 && (str_find_nocase(haystack: ErrorString(), needle: "full") || str_find_nocase(haystack: ErrorString(), needle: "reserved")))
454 m_ReconnectTime = time_get() + time_freq() * g_Config.m_ClReconnectFull;
455 else if(g_Config.m_ClReconnectTimeout > 0 && (str_find_nocase(haystack: ErrorString(), needle: "Timeout") || str_find_nocase(haystack: ErrorString(), needle: "Too weak connection")))
456 m_ReconnectTime = time_get() + time_freq() * g_Config.m_ClReconnectTimeout;
457 }
458
459 if(State == IClient::STATE_ONLINE)
460 {
461 const bool Registered = m_ServerBrowser.IsRegistered(Addr: ServerAddress());
462 Discord()->SetGameInfo(ServerInfo: m_CurrentServerInfo, Registered);
463 Steam()->SetGameInfo(ServerAddr: ServerAddress(), pMapName: GameClient()->Map()->BaseName(), AnnounceAddr: Registered);
464 }
465 else if(OldState == IClient::STATE_ONLINE)
466 {
467 Discord()->ClearGameInfo();
468 Steam()->ClearGameInfo();
469 }
470}
471
472// called when the map is loaded and we should init for a new round
473void CClient::OnEnterGame(bool Dummy)
474{
475 // reset input
476 for(int i = 0; i < 200; i++)
477 {
478 m_aInputs[Dummy][i].m_Tick = -1;
479 }
480 m_aCurrentInput[Dummy] = 0;
481
482 // reset snapshots
483 m_aapSnapshots[Dummy][SNAP_CURRENT] = nullptr;
484 m_aapSnapshots[Dummy][SNAP_PREV] = nullptr;
485 m_aSnapshotStorage[Dummy].PurgeAll();
486 m_aReceivedSnapshots[Dummy] = 0;
487 m_aSnapshotParts[Dummy] = 0;
488 m_aSnapshotIncomingDataSize[Dummy] = 0;
489 m_SnapCrcErrors = 0;
490 // Also make gameclient aware that snapshots have been purged
491 GameClient()->InvalidateSnapshot();
492
493 // reset times
494 m_aAckGameTick[Dummy] = -1;
495 m_aCurrentRecvTick[Dummy] = 0;
496 m_aPrevGameTick[Dummy] = 0;
497 m_aCurGameTick[Dummy] = 0;
498 m_aGameIntraTick[Dummy] = 0.0f;
499 m_aGameTickTime[Dummy] = 0.0f;
500 m_aGameIntraTickSincePrev[Dummy] = 0.0f;
501 m_aPredTick[Dummy] = 0;
502 m_aPredIntraTick[Dummy] = 0.0f;
503 m_aGameTime[Dummy].Init(Target: 0);
504 m_PredictedTime.Init(Target: 0);
505
506 if(!Dummy)
507 {
508 m_LastDummyConnectTime = 0.0f;
509 }
510
511 GameClient()->OnEnterGame();
512}
513
514void CClient::EnterGame(int Conn)
515{
516 if(State() == IClient::STATE_DEMOPLAYBACK)
517 return;
518
519 m_aDidPostConnect[Conn] = false;
520
521 // now we will wait for two snapshots
522 // to finish the connection
523 SendEnterGame(Conn);
524 OnEnterGame(Dummy: Conn);
525
526 ServerInfoRequest(); // fresh one for timeout protection
527 m_CurrentServerNextPingTime = time_get() + time_freq() / 2;
528}
529
530void CClient::OnPostConnect(int Conn)
531{
532 if(!m_ServerCapabilities.m_ChatTimeoutCode)
533 return;
534
535 char aBufMsg[256];
536 if(!g_Config.m_ClRunOnJoin[0] && !g_Config.m_ClDummyDefaultEyes && !g_Config.m_ClPlayerDefaultEyes)
537 str_format(buffer: aBufMsg, buffer_size: sizeof(aBufMsg), format: "/timeout %s", m_aTimeoutCodes[Conn]);
538 else
539 str_format(buffer: aBufMsg, buffer_size: sizeof(aBufMsg), format: "/mc;timeout %s", m_aTimeoutCodes[Conn]);
540
541 if(g_Config.m_ClDummyDefaultEyes || g_Config.m_ClPlayerDefaultEyes)
542 {
543 int Emote = Conn == CONN_DUMMY ? g_Config.m_ClDummyDefaultEyes : g_Config.m_ClPlayerDefaultEyes;
544
545 if(Emote != EMOTE_NORMAL)
546 {
547 char aBuf[32];
548 static const char *s_EMOTE_NAMES[] = {
549 "pain",
550 "happy",
551 "surprise",
552 "angry",
553 "blink",
554 };
555 static_assert(std::size(s_EMOTE_NAMES) == NUM_EMOTES - 1, "The size of EMOTE_NAMES must match NUM_EMOTES - 1");
556
557 str_append(dst&: aBufMsg, src: ";");
558 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "emote %s %d", s_EMOTE_NAMES[Emote - 1], g_Config.m_ClEyeDuration);
559 str_append(dst&: aBufMsg, src: aBuf);
560 }
561 }
562 if(g_Config.m_ClRunOnJoin[0])
563 {
564 str_append(dst&: aBufMsg, src: ";");
565 str_append(dst&: aBufMsg, src: g_Config.m_ClRunOnJoin);
566 }
567 if(IsSixup())
568 {
569 protocol7::CNetMsg_Cl_Say Msg7;
570 Msg7.m_Mode = protocol7::CHAT_ALL;
571 Msg7.m_Target = -1;
572 Msg7.m_pMessage = aBufMsg;
573 SendPackMsg(Conn, pMsg: &Msg7, Flags: MSGFLAG_VITAL, NoTranslate: true);
574 }
575 else
576 {
577 CNetMsg_Cl_Say MsgP;
578 MsgP.m_Team = 0;
579 MsgP.m_pMessage = aBufMsg;
580 CMsgPacker PackerTimeout(&MsgP);
581 MsgP.Pack(pPacker: &PackerTimeout);
582 SendMsg(Conn, pMsg: &PackerTimeout, Flags: MSGFLAG_VITAL);
583 }
584}
585
586static void GenerateTimeoutCode(char *pBuffer, unsigned Size, char *pSeed, const NETADDR *pAddrs, int NumAddrs, bool Dummy)
587{
588 MD5_CTX Md5;
589 md5_init(ctxt: &Md5);
590 const char *pDummy = Dummy ? "dummy" : "normal";
591 md5_update(ctxt: &Md5, data: (unsigned char *)pDummy, data_len: str_length(str: pDummy) + 1);
592 md5_update(ctxt: &Md5, data: (unsigned char *)pSeed, data_len: str_length(str: pSeed) + 1);
593 for(int i = 0; i < NumAddrs; i++)
594 {
595 md5_update(ctxt: &Md5, data: (unsigned char *)&pAddrs[i], data_len: sizeof(pAddrs[i]));
596 }
597 MD5_DIGEST Digest = md5_finish(ctxt: &Md5);
598
599 unsigned short aRandom[8];
600 mem_copy(dest: aRandom, source: Digest.data, size: sizeof(aRandom));
601 generate_password(buffer: pBuffer, length: Size, random: aRandom, random_length: 8);
602}
603
604void CClient::GenerateTimeoutSeed()
605{
606 secure_random_password(buffer: g_Config.m_ClTimeoutSeed, length: sizeof(g_Config.m_ClTimeoutSeed), pw_length: 16);
607}
608
609void CClient::GenerateTimeoutCodes(const NETADDR *pAddrs, int NumAddrs)
610{
611 if(g_Config.m_ClTimeoutSeed[0] == '\0')
612 {
613 GenerateTimeoutSeed();
614 }
615 for(int Dummy = 0; Dummy < NUM_DUMMIES; Dummy++)
616 {
617 GenerateTimeoutCode(pBuffer: m_aTimeoutCodes[Dummy], Size: sizeof(m_aTimeoutCodes[Dummy]), pSeed: g_Config.m_ClTimeoutSeed, pAddrs, NumAddrs, Dummy);
618 log_debug("client", "timeout code '%s' (%s)", m_aTimeoutCodes[Dummy], Dummy == 0 ? "normal" : "dummy");
619 }
620}
621
622void CClient::Connect(const char *pAddress, const char *pPassword)
623{
624 // Disconnect will not change the state if we are already quitting/restarting
625 if(m_State == IClient::STATE_QUITTING || m_State == IClient::STATE_RESTARTING)
626 return;
627 Disconnect();
628 dbg_assert(m_State == IClient::STATE_OFFLINE, "Disconnect must ensure that client is offline");
629
630 const NETADDR LastAddr = ServerAddress();
631
632 if(pAddress != m_aConnectAddressStr)
633 str_copy(dst&: m_aConnectAddressStr, src: pAddress);
634
635 char aMsg[512];
636 str_format(buffer: aMsg, buffer_size: sizeof(aMsg), format: "connecting to '%s'", m_aConnectAddressStr);
637 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aMsg, PrintColor: CLIENT_NETWORK_PRINT_COLOR);
638
639 int NumConnectAddrs = 0;
640 NETADDR aConnectAddrs[MAX_SERVER_ADDRESSES];
641 mem_zero(block: aConnectAddrs, size: sizeof(aConnectAddrs));
642 const char *pNextAddr = pAddress;
643 char aBuffer[128];
644 bool OnlySixup = true;
645 while((pNextAddr = str_next_token(str: pNextAddr, delim: ",", buffer: aBuffer, buffer_size: sizeof(aBuffer))))
646 {
647 NETADDR NextAddr;
648 char aHost[128];
649 const int UrlParseResult = net_addr_from_url(addr: &NextAddr, string: aBuffer, host_buf: aHost, host_buf_size: sizeof(aHost));
650 bool Sixup = NextAddr.type & NETTYPE_TW7;
651 if(UrlParseResult > 0)
652 str_copy(dst&: aHost, src: aBuffer);
653
654 if(net_host_lookup(hostname: aHost, addr: &NextAddr, types: m_aNetClient[CONN_MAIN].NetType()) != 0)
655 {
656 log_error("client", "could not find address of %s", aHost);
657 continue;
658 }
659 if(NumConnectAddrs == (int)std::size(aConnectAddrs))
660 {
661 log_warn("client", "too many connect addresses, ignoring %s", aHost);
662 continue;
663 }
664 if(NextAddr.port == 0)
665 {
666 NextAddr.port = 8303;
667 }
668 if(Sixup)
669 NextAddr.type |= NETTYPE_TW7;
670 else
671 OnlySixup = false;
672
673 char aNextAddr[NETADDR_MAXSTRSIZE];
674 net_addr_str(addr: &NextAddr, string: aNextAddr, max_length: sizeof(aNextAddr), add_port: true);
675 log_debug("client", "resolved connect address '%s' to %s", aBuffer, aNextAddr);
676
677 if(NextAddr == LastAddr)
678 {
679 m_SendPassword = true;
680 }
681
682 aConnectAddrs[NumConnectAddrs] = NextAddr;
683 NumConnectAddrs += 1;
684 }
685
686 if(NumConnectAddrs == 0)
687 {
688 log_error("client", "could not find any connect address");
689 char aWarning[256];
690 str_format(buffer: aWarning, buffer_size: sizeof(aWarning), format: Localize(pStr: "Could not resolve connect address '%s'. See local console for details."), m_aConnectAddressStr);
691 SWarning Warning(Localize(pStr: "Connect address error"), aWarning);
692 Warning.m_AutoHide = false;
693 AddWarning(Warning);
694 return;
695 }
696
697 m_ConnectionId = RandomUuid();
698 ServerInfoRequest();
699
700 if(m_SendPassword)
701 {
702 str_copy(dst&: m_aPassword, src: g_Config.m_Password);
703 m_SendPassword = false;
704 }
705 else if(!pPassword)
706 {
707 m_aPassword[0] = 0;
708 }
709 else
710 {
711 str_copy(dst&: m_aPassword, src: pPassword);
712 }
713
714 m_CanReceiveServerCapabilities = true;
715
716 m_Sixup = OnlySixup;
717 if(m_Sixup)
718 {
719 m_aNetClient[CONN_MAIN].Connect7(pAddr: aConnectAddrs, NumAddrs: NumConnectAddrs);
720 }
721 else
722 {
723 m_aNetClient[CONN_MAIN].Connect(pAddr: aConnectAddrs, NumAddrs: NumConnectAddrs);
724 }
725
726 m_aNetClient[CONN_MAIN].RefreshStun();
727 SetState(IClient::STATE_CONNECTING);
728
729 m_aInputtimeMarginGraphs[CONN_MAIN].Init(Min: -150.0f, Max: 150.0f);
730 m_aGametimeMarginGraphs[CONN_MAIN].Init(Min: -150.0f, Max: 150.0f);
731
732 GenerateTimeoutCodes(pAddrs: aConnectAddrs, NumAddrs: NumConnectAddrs);
733}
734
735void CClient::DisconnectWithReason(const char *pReason)
736{
737 if(pReason != nullptr && pReason[0] == '\0')
738 pReason = nullptr;
739
740 DummyDisconnect(pReason);
741
742 char aBuf[512];
743 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "disconnecting. reason='%s'", pReason ? pReason : "unknown");
744 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aBuf, PrintColor: CLIENT_NETWORK_PRINT_COLOR);
745
746 // stop demo playback and recorder
747 // make sure to remove replay tmp demo
748 m_DemoPlayer.Stop();
749 for(int Recorder = 0; Recorder < RECORDER_MAX; Recorder++)
750 {
751 DemoRecorder_Stop(Recorder);
752 }
753
754 m_aRconAuthed[0] = 0;
755 // Make sure to clear credentials completely from memory
756 mem_zero(block: m_aRconUsername, size: sizeof(m_aRconUsername));
757 mem_zero(block: m_aRconPassword, size: sizeof(m_aRconPassword));
758 m_MapDetails = std::nullopt;
759 m_ServerSentCapabilities = false;
760 m_UseTempRconCommands = 0;
761 m_ExpectedRconCommands = -1;
762 m_GotRconCommands = 0;
763 m_pConsole->DeregisterTempAll();
764 m_ExpectedMaplistEntries = -1;
765 m_vMaplistEntries.clear();
766 GameClient()->ForceUpdateConsoleRemoteCompletionSuggestions();
767 m_aNetClient[CONN_MAIN].Disconnect(pReason);
768 SetState(IClient::STATE_OFFLINE);
769 GameClient()->Map()->Unload();
770 m_CurrentServerPingInfoType = -1;
771 m_CurrentServerPingBasicToken = -1;
772 m_CurrentServerPingToken = -1;
773 mem_zero(block: &m_CurrentServerPingUuid, size: sizeof(m_CurrentServerPingUuid));
774 m_CurrentServerCurrentPingTime = -1;
775 m_CurrentServerNextPingTime = -1;
776
777 ResetMapDownload(ResetActive: true);
778
779 // clear the current server info
780 m_CurrentServerInfo = {};
781
782 // clear snapshots
783 m_aapSnapshots[0][SNAP_CURRENT] = nullptr;
784 m_aapSnapshots[0][SNAP_PREV] = nullptr;
785 m_aReceivedSnapshots[0] = 0;
786 m_LastDummy = false;
787
788 // 0.7
789 m_TranslationContext.Reset();
790 m_Sixup = false;
791}
792
793void CClient::Disconnect()
794{
795 if(m_State != IClient::STATE_OFFLINE)
796 {
797 DisconnectWithReason(pReason: nullptr);
798 }
799}
800
801bool CClient::DummyConnected() const
802{
803 return m_DummyConnected;
804}
805
806bool CClient::DummyConnecting() const
807{
808 return m_DummyConnecting;
809}
810
811bool CClient::DummyConnectingDelayed() const
812{
813 return !DummyConnected() && !DummyConnecting() && m_LastDummyConnectTime > 0.0f && m_LastDummyConnectTime + 5.0f > GlobalTime();
814}
815
816void CClient::DummyConnect()
817{
818 if(m_aNetClient[CONN_MAIN].State() != NETSTATE_ONLINE)
819 {
820 log_info("client", "Not online.");
821 return;
822 }
823
824 if(!DummyAllowed())
825 {
826 log_info("client", "Dummy is not allowed on this server.");
827 return;
828 }
829 if(DummyConnecting())
830 {
831 log_info("client", "Dummy is already connecting.");
832 return;
833 }
834 if(DummyConnected())
835 {
836 // causes log spam with connect+swap binds
837 // https://github.com/ddnet/ddnet/issues/9426
838 // log_info("client", "Dummy is already connected.");
839 return;
840 }
841 if(DummyConnectingDelayed())
842 {
843 log_info("client", "Wait before connecting dummy again.");
844 return;
845 }
846
847 m_LastDummyConnectTime = GlobalTime();
848 m_aRconAuthed[1] = 0;
849 m_DummySendConnInfo = true;
850
851 g_Config.m_ClDummyCopyMoves = 0;
852 g_Config.m_ClDummyHammer = 0;
853
854 m_DummyConnecting = true;
855 // connect to the server
856 if(IsSixup())
857 m_aNetClient[CONN_DUMMY].Connect7(pAddr: m_aNetClient[CONN_MAIN].ServerAddress(), NumAddrs: 1);
858 else
859 m_aNetClient[CONN_DUMMY].Connect(pAddr: m_aNetClient[CONN_MAIN].ServerAddress(), NumAddrs: 1);
860
861 m_aInputtimeMarginGraphs[CONN_DUMMY].Init(Min: -150.0f, Max: 150.0f);
862 m_aGametimeMarginGraphs[CONN_DUMMY].Init(Min: -150.0f, Max: 150.0f);
863}
864
865void CClient::DummyDisconnect(const char *pReason)
866{
867 m_aNetClient[CONN_DUMMY].Disconnect(pReason);
868 g_Config.m_ClDummy = 0;
869
870 m_aRconAuthed[1] = 0;
871 m_aapSnapshots[1][SNAP_CURRENT] = nullptr;
872 m_aapSnapshots[1][SNAP_PREV] = nullptr;
873 m_aReceivedSnapshots[1] = 0;
874 m_DummyConnected = false;
875 m_DummyConnecting = false;
876 m_DummyReconnectOnReload = false;
877 m_DummyDeactivateOnReconnect = false;
878#if defined(CONF_PLATFORM_IOS)
879 m_DummyReconnectOnResume = false;
880#endif
881 GameClient()->OnDummyDisconnect();
882}
883
884bool CClient::DummyAllowed() const
885{
886 return m_ServerCapabilities.m_AllowDummy;
887}
888
889const CServerInfo &CClient::ServerInfo() const
890{
891 return m_CurrentServerInfo;
892}
893
894void CClient::ServerInfoRequest()
895{
896 m_CurrentServerInfo = {};
897 m_CurrentServerInfoRequestTime = 0;
898}
899
900void CClient::SetCurrentServerInfo(const CServerInfo &ServerInfo)
901{
902 m_CurrentServerInfo = ServerInfo;
903 m_CurrentServerInfoRequestTime = -1;
904 str_copy(dst&: m_CurrentServerInfo.m_aMap, src: GameClient()->Map()->BaseName());
905 m_CurrentServerInfo.m_MapCrc = GameClient()->Map()->Crc();
906 m_CurrentServerInfo.m_MapSize = GameClient()->Map()->Size();
907}
908
909void CClient::LoadDebugFont()
910{
911 m_DebugFont = Graphics()->LoadTexture(pFilename: "debug_font.png", StorageType: IStorage::TYPE_ALL);
912}
913
914// ---
915
916IClient::CSnapItem CClient::SnapGetItem(int SnapId, int Index) const
917{
918 dbg_assert(SnapId >= 0 && SnapId < NUM_SNAPSHOT_TYPES, "invalid SnapId");
919 const CSnapshot *pSnapshot = m_aapSnapshots[g_Config.m_ClDummy][SnapId]->m_pAltSnap;
920 const CSnapshotItem *pSnapshotItem = pSnapshot->GetItem(Index);
921 CSnapItem Item;
922 Item.m_Type = pSnapshot->GetItemType(Index);
923 Item.m_Id = pSnapshotItem->Id();
924 Item.m_pData = pSnapshotItem->Data();
925 Item.m_DataSize = pSnapshot->GetItemSize(Index);
926 return Item;
927}
928
929const void *CClient::SnapFindItem(int SnapId, int Type, int Id) const
930{
931 if(!m_aapSnapshots[g_Config.m_ClDummy][SnapId])
932 return nullptr;
933
934 return m_aapSnapshots[g_Config.m_ClDummy][SnapId]->m_pAltSnap->FindItem(Type, Id);
935}
936
937int CClient::SnapNumItems(int SnapId) const
938{
939 dbg_assert(SnapId >= 0 && SnapId < NUM_SNAPSHOT_TYPES, "invalid SnapId");
940 if(!m_aapSnapshots[g_Config.m_ClDummy][SnapId])
941 return 0;
942 return m_aapSnapshots[g_Config.m_ClDummy][SnapId]->m_pAltSnap->NumItems();
943}
944
945void CClient::SnapSetStaticsize(int ItemType, int Size)
946{
947 m_SnapshotDelta.SetStaticsize(ItemType, Size);
948}
949
950void CClient::SnapSetStaticsize7(int ItemType, int Size)
951{
952 m_SnapshotDeltaSixup.SetStaticsize(ItemType, Size);
953}
954
955void CClient::RenderDebug()
956{
957 if(!g_Config.m_Debug)
958 {
959 return;
960 }
961
962 const std::chrono::nanoseconds Now = time_get_nanoseconds();
963 if(Now - m_NetstatsLastUpdate > 1s)
964 {
965 m_NetstatsLastUpdate = Now;
966 m_NetstatsPrev = m_NetstatsCurrent;
967 net_stats(stats: &m_NetstatsCurrent);
968 }
969
970 char aBuffer[512];
971 const float FontSize = 16.0f;
972
973 Graphics()->TextureSet(Texture: m_DebugFont);
974 Graphics()->MapScreenToSize(Width: Graphics()->ScreenWidth(), Height: Graphics()->ScreenHeight());
975 Graphics()->QuadsBegin();
976
977 str_format(buffer: aBuffer, buffer_size: sizeof(aBuffer), format: "Game/predicted tick: %d/%d", m_aCurGameTick[g_Config.m_ClDummy], m_aPredTick[g_Config.m_ClDummy]);
978 Graphics()->QuadsText(x: 2, y: 2, Size: FontSize, pText: aBuffer);
979
980 str_format(buffer: aBuffer, buffer_size: sizeof(aBuffer), format: "Prediction time: %d ms", GetPredictionTime());
981 Graphics()->QuadsText(x: 2, y: 2 + FontSize, Size: FontSize, pText: aBuffer);
982
983 str_format(buffer: aBuffer, buffer_size: sizeof(aBuffer), format: "FPS: %3d", round_to_int(f: 1.0f / m_FrameTimeAverage));
984 Graphics()->QuadsText(x: 20.0f * FontSize, y: 2, Size: FontSize, pText: aBuffer);
985
986 str_format(buffer: aBuffer, buffer_size: sizeof(aBuffer), format: "Frametime: %4d us", round_to_int(f: m_FrameTimeAverage * 1000000.0f));
987 Graphics()->QuadsText(x: 20.0f * FontSize, y: 2 + FontSize, Size: FontSize, pText: aBuffer);
988
989 str_format(aBuffer, sizeof(aBuffer), "%16s: %" PRIu64 " KiB", "Texture memory", Graphics()->TextureMemoryUsage() / 1024);
990 Graphics()->QuadsText(x: 32.0f * FontSize, y: 2, Size: FontSize, pText: aBuffer);
991
992 str_format(aBuffer, sizeof(aBuffer), "%16s: %" PRIu64 " KiB", "Buffer memory", Graphics()->BufferMemoryUsage() / 1024);
993 Graphics()->QuadsText(x: 32.0f * FontSize, y: 2 + FontSize, Size: FontSize, pText: aBuffer);
994
995 str_format(aBuffer, sizeof(aBuffer), "%16s: %" PRIu64 " KiB", "Streamed memory", Graphics()->StreamedMemoryUsage() / 1024);
996 Graphics()->QuadsText(x: 32.0f * FontSize, y: 2 + 2 * FontSize, Size: FontSize, pText: aBuffer);
997
998 str_format(aBuffer, sizeof(aBuffer), "%16s: %" PRIu64 " KiB", "Staging memory", Graphics()->StagingMemoryUsage() / 1024);
999 Graphics()->QuadsText(x: 32.0f * FontSize, y: 2 + 3 * FontSize, Size: FontSize, pText: aBuffer);
1000
1001 // Network
1002 {
1003 const uint64_t OverheadSize = 14 + 20 + 8; // ETH + IP + UDP
1004 const uint64_t SendPackets = m_NetstatsCurrent.sent_packets - m_NetstatsPrev.sent_packets;
1005 const uint64_t SendBytes = m_NetstatsCurrent.sent_bytes - m_NetstatsPrev.sent_bytes;
1006 const uint64_t SendTotal = SendBytes + SendPackets * OverheadSize;
1007 const uint64_t RecvPackets = m_NetstatsCurrent.recv_packets - m_NetstatsPrev.recv_packets;
1008 const uint64_t RecvBytes = m_NetstatsCurrent.recv_bytes - m_NetstatsPrev.recv_bytes;
1009 const uint64_t RecvTotal = RecvBytes + RecvPackets * OverheadSize;
1010
1011 str_format(aBuffer, sizeof(aBuffer), "Send: %3" PRIu64 " %5" PRIu64 "+%4" PRIu64 "=%5" PRIu64 " (%3" PRIu64 " Kibit/s) average: %5" PRIu64,
1012 SendPackets, SendBytes, SendPackets * OverheadSize, SendTotal, (SendTotal * 8) / 1024, SendPackets == 0 ? 0 : SendBytes / SendPackets);
1013 Graphics()->QuadsText(x: 2, y: 2 + 3 * FontSize, Size: FontSize, pText: aBuffer);
1014 str_format(aBuffer, sizeof(aBuffer), "Recv: %3" PRIu64 " %5" PRIu64 "+%4" PRIu64 "=%5" PRIu64 " (%3" PRIu64 " Kibit/s) average: %5" PRIu64,
1015 RecvPackets, RecvBytes, RecvPackets * OverheadSize, RecvTotal, (RecvTotal * 8) / 1024, RecvPackets == 0 ? 0 : RecvBytes / RecvPackets);
1016 Graphics()->QuadsText(x: 2, y: 2 + 4 * FontSize, Size: FontSize, pText: aBuffer);
1017 }
1018
1019 // Snapshots
1020 {
1021 const float OffsetY = 2 + 6 * FontSize;
1022 int Row = 0;
1023 str_format(buffer: aBuffer, buffer_size: sizeof(aBuffer), format: "%5s %20s: %8s %8s %8s", "ID", "Name", "Rate", "Updates", "R/U");
1024 Graphics()->QuadsText(x: 2, y: OffsetY + Row * 12, Size: FontSize, pText: aBuffer);
1025 Row++;
1026 for(int i = 0; i < NUM_NETOBJTYPES; i++)
1027 {
1028 if(SnapshotDelta()->GetDataRate(Index: i))
1029 {
1030 str_format(
1031 aBuffer,
1032 sizeof(aBuffer),
1033 "%5d %20s: %8" PRIu64 " %8" PRIu64 " %8" PRIu64,
1034 i,
1035 GameClient()->GetItemName(i),
1036 SnapshotDelta()->GetDataRate(i) / 8, SnapshotDelta()->GetDataUpdates(i),
1037 (SnapshotDelta()->GetDataRate(i) / SnapshotDelta()->GetDataUpdates(i)) / 8);
1038 Graphics()->QuadsText(x: 2, y: OffsetY + Row * 12, Size: FontSize, pText: aBuffer);
1039 Row++;
1040 }
1041 }
1042 for(int i = CSnapshot::MAX_TYPE; i > (CSnapshot::MAX_TYPE - 64); i--)
1043 {
1044 if(SnapshotDelta()->GetDataRate(Index: i) && m_aapSnapshots[g_Config.m_ClDummy][IClient::SNAP_CURRENT])
1045 {
1046 const int Type = m_aapSnapshots[g_Config.m_ClDummy][IClient::SNAP_CURRENT]->m_pAltSnap->GetExternalItemType(InternalType: i);
1047 if(Type == UUID_INVALID)
1048 {
1049 str_format(
1050 aBuffer,
1051 sizeof(aBuffer),
1052 "%5d %20s: %8" PRIu64 " %8" PRIu64 " %8" PRIu64,
1053 i,
1054 "Unknown UUID",
1055 SnapshotDelta()->GetDataRate(i) / 8,
1056 SnapshotDelta()->GetDataUpdates(i),
1057 (SnapshotDelta()->GetDataRate(i) / SnapshotDelta()->GetDataUpdates(i)) / 8);
1058 Graphics()->QuadsText(x: 2, y: OffsetY + Row * 12, Size: FontSize, pText: aBuffer);
1059 Row++;
1060 }
1061 else if(Type != i)
1062 {
1063 str_format(
1064 aBuffer,
1065 sizeof(aBuffer),
1066 "%5d %20s: %8" PRIu64 " %8" PRIu64 " %8" PRIu64,
1067 Type,
1068 GameClient()->GetItemName(Type),
1069 SnapshotDelta()->GetDataRate(i) / 8,
1070 SnapshotDelta()->GetDataUpdates(i),
1071 (SnapshotDelta()->GetDataRate(i) / SnapshotDelta()->GetDataUpdates(i)) / 8);
1072 Graphics()->QuadsText(x: 2, y: OffsetY + Row * 12, Size: FontSize, pText: aBuffer);
1073 Row++;
1074 }
1075 }
1076 }
1077 }
1078
1079 Graphics()->QuadsEnd();
1080}
1081
1082void CClient::RenderGraphs()
1083{
1084 if(!g_Config.m_DbgGraphs)
1085 return;
1086
1087 // Make sure graph positions and sizes are aligned with pixels to avoid lines overlapping graph edges
1088 Graphics()->MapScreenToSize(Width: Graphics()->ScreenWidth(), Height: Graphics()->ScreenHeight());
1089 const float GraphW = std::round(x: Graphics()->ScreenWidth() / 4.0f);
1090 const float GraphH = std::round(x: Graphics()->ScreenHeight() / 6.0f);
1091 const float GraphSpacing = std::round(x: Graphics()->ScreenWidth() / 100.0f);
1092 const float GraphX = Graphics()->ScreenWidth() - GraphW - GraphSpacing;
1093
1094 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1095 TextRender()->Text(x: GraphX, y: GraphSpacing * 5 - 12.0f - 10.0f, Size: 12.0f, pText: Localize(pStr: "Press Ctrl+Shift+G to disable debug graphs."));
1096
1097 m_FpsGraph.Scale(WantedTotalTime: time_freq());
1098 m_FpsGraph.Render(pGraphics: Graphics(), pTextRender: TextRender(), x: GraphX, y: GraphSpacing * 5, w: GraphW, h: GraphH, pDescription: "FPS");
1099 m_aInputtimeMarginGraphs[g_Config.m_ClDummy].Scale(WantedTotalTime: 5 * time_freq());
1100 m_aInputtimeMarginGraphs[g_Config.m_ClDummy].Render(pGraphics: Graphics(), pTextRender: TextRender(), x: GraphX, y: GraphSpacing * 6 + GraphH, w: GraphW, h: GraphH, pDescription: "Prediction Margin");
1101 m_aGametimeMarginGraphs[g_Config.m_ClDummy].Scale(WantedTotalTime: 5 * time_freq());
1102 m_aGametimeMarginGraphs[g_Config.m_ClDummy].Render(pGraphics: Graphics(), pTextRender: TextRender(), x: GraphX, y: GraphSpacing * 7 + GraphH * 2, w: GraphW, h: GraphH, pDescription: "Gametime Margin");
1103}
1104
1105void CClient::Restart()
1106{
1107 SetState(IClient::STATE_RESTARTING);
1108}
1109
1110void CClient::Quit()
1111{
1112 SetState(IClient::STATE_QUITTING);
1113}
1114
1115void CClient::ResetSocket()
1116{
1117 NETADDR BindAddr;
1118 if(g_Config.m_Bindaddr[0] == '\0')
1119 {
1120 mem_zero(block: &BindAddr, size: sizeof(BindAddr));
1121 }
1122 else if(net_host_lookup(hostname: g_Config.m_Bindaddr, addr: &BindAddr, types: NETTYPE_ALL) != 0)
1123 {
1124 log_error("client", "The configured bindaddr '%s' cannot be resolved.", g_Config.m_Bindaddr);
1125 return;
1126 }
1127 BindAddr.type = NETTYPE_ALL;
1128 for(size_t Conn = 0; Conn < std::size(m_aNetClient); Conn++)
1129 {
1130 char aError[256];
1131 if(!InitNetworkClientImpl(BindAddr, Conn, pError: aError, ErrorSize: sizeof(aError)))
1132 log_error("client", "%s", aError);
1133 }
1134}
1135
1136#if defined(CONF_PLATFORM_IOS)
1137void CClient::RecreateBrokenSockets()
1138{
1139 if(std::none_of(std::begin(m_aNetClient), std::end(m_aNetClient), [](const CNetClient &NetClient) { return NetClient.SocketIsBroken(); }))
1140 {
1141 return;
1142 }
1143
1144 // iOS closes the sockets of suspended apps. Sending on them keeps failing
1145 // with EPIPE, so they have to be recreated once the app is resumed.
1146 log_info("client", "network sockets were closed by the system, recreating them");
1147
1148 // Reconnect afterwards, so the server can be rejoined with timeout protection.
1149 char aConnectAddress[sizeof(m_aConnectAddressStr)];
1150 str_copy(aConnectAddress, m_aConnectAddressStr);
1151 const bool Reconnect = m_State != IClient::STATE_OFFLINE && m_State < IClient::STATE_QUITTING;
1152 const bool ReconnectDummy = Reconnect && m_DummyConnected;
1153 const bool DeactivateDummy = g_Config.m_ClDummy == 0;
1154
1155 Disconnect();
1156 ResetSocket();
1157 // The recreated sockets do not know the stun servers of the old ones yet.
1158 LoadDDNetInfo();
1159
1160 if(Reconnect)
1161 {
1162 Connect(aConnectAddress);
1163 if(ReconnectDummy)
1164 {
1165 // The dummy is connected again when the main connection is ready.
1166 m_DummyReconnectOnResume = true;
1167 m_DummyDeactivateOnReconnect = DeactivateDummy;
1168 }
1169 }
1170}
1171#endif
1172
1173const char *CClient::PlayerName() const
1174{
1175 if(g_Config.m_PlayerName[0])
1176 {
1177 return g_Config.m_PlayerName;
1178 }
1179 if(g_Config.m_SteamName[0])
1180 {
1181 return g_Config.m_SteamName;
1182 }
1183 return "nameless tee";
1184}
1185
1186const char *CClient::DummyName()
1187{
1188 if(g_Config.m_ClDummyName[0])
1189 {
1190 return g_Config.m_ClDummyName;
1191 }
1192 const char *pBase = nullptr;
1193 if(g_Config.m_PlayerName[0])
1194 {
1195 pBase = g_Config.m_PlayerName;
1196 }
1197 else if(g_Config.m_SteamName[0])
1198 {
1199 pBase = g_Config.m_SteamName;
1200 }
1201 if(pBase)
1202 {
1203 str_format(buffer: m_aAutomaticDummyName, buffer_size: sizeof(m_aAutomaticDummyName), format: "[D] %s", pBase);
1204 return m_aAutomaticDummyName;
1205 }
1206 return "brainless tee";
1207}
1208
1209const char *CClient::ErrorString() const
1210{
1211 return m_aNetClient[CONN_MAIN].ErrorString();
1212}
1213
1214void CClient::Render()
1215{
1216 if(m_EditorActive)
1217 {
1218 m_pEditor->OnRender();
1219 }
1220 else
1221 {
1222 GameClient()->OnRender();
1223 }
1224
1225 RenderDebug();
1226 RenderGraphs();
1227}
1228
1229const char *CClient::LoadMap(const char *pName, const char *pFilename, const std::optional<SHA256_DIGEST> &WantedSha256, unsigned WantedCrc)
1230{
1231 static char s_aErrorMsg[128];
1232
1233 SetState(IClient::STATE_LOADING);
1234 SetLoadingStateDetail(IClient::ELoadingStateDetail::LOADING_MAP);
1235 if((bool)m_LoadingCallback)
1236 m_LoadingCallback(IClient::ELoadingCallbackDetail::MAP);
1237
1238 // Stop demo recording before loading a new map.
1239 for(int Recorder = 0; Recorder < RECORDER_MAX; Recorder++)
1240 {
1241 DemoRecorder(Recorder)->Stop(Mode: Recorder == RECORDER_REPLAYS ? IDemoRecorder::EStopMode::REMOVE_FILE : IDemoRecorder::EStopMode::KEEP_FILE);
1242 }
1243
1244 // Unload the current map and reset all snapshots before loading a new map,
1245 // because the snapshots are only valid for the old map.
1246 GameClient()->Map()->Unload();
1247 for(int Dummy = 0; Dummy < NUM_DUMMIES; Dummy++)
1248 {
1249 m_aapSnapshots[Dummy][SNAP_CURRENT] = nullptr;
1250 m_aapSnapshots[Dummy][SNAP_PREV] = nullptr;
1251 m_aSnapshotStorage[Dummy].PurgeAll();
1252 m_aReceivedSnapshots[Dummy] = 0;
1253 m_aSnapshotParts[Dummy] = 0;
1254 m_aSnapshotIncomingDataSize[Dummy] = 0;
1255 }
1256 m_SnapCrcErrors = 0;
1257 GameClient()->InvalidateSnapshot();
1258
1259 if(!GameClient()->Map()->Load(pFullName: pName, pStorage: Storage(), pPath: pFilename, StorageType: IStorage::TYPE_ALL))
1260 {
1261 str_format(buffer: s_aErrorMsg, buffer_size: sizeof(s_aErrorMsg), format: "map '%s' not found", pFilename);
1262 return s_aErrorMsg;
1263 }
1264
1265 if(WantedSha256.has_value() && GameClient()->Map()->Sha256() != WantedSha256.value())
1266 {
1267 char aWanted[SHA256_MAXSTRSIZE];
1268 char aGot[SHA256_MAXSTRSIZE];
1269 sha256_str(digest: WantedSha256.value(), str: aWanted, max_len: sizeof(aWanted));
1270 sha256_str(digest: GameClient()->Map()->Sha256(), str: aGot, max_len: sizeof(aWanted));
1271 str_format(buffer: s_aErrorMsg, buffer_size: sizeof(s_aErrorMsg), format: "map differs from the server. %s != %s", aGot, aWanted);
1272 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client", pStr: s_aErrorMsg);
1273 GameClient()->Map()->Unload();
1274 return s_aErrorMsg;
1275 }
1276
1277 // Only check CRC if we don't have the secure SHA256.
1278 if(!WantedSha256.has_value() && GameClient()->Map()->Crc() != WantedCrc)
1279 {
1280 str_format(buffer: s_aErrorMsg, buffer_size: sizeof(s_aErrorMsg), format: "map differs from the server. %08x != %08x", GameClient()->Map()->Crc(), WantedCrc);
1281 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client", pStr: s_aErrorMsg);
1282 GameClient()->Map()->Unload();
1283 return s_aErrorMsg;
1284 }
1285
1286 char aBuf[256];
1287 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "loaded map '%s'", pFilename);
1288 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client", pStr: aBuf);
1289
1290 return nullptr;
1291}
1292
1293static void FormatMapDownloadFilename(const char *pName, const std::optional<SHA256_DIGEST> &Sha256, int Crc, bool Temp, char *pBuffer, int BufferSize)
1294{
1295 char aSuffix[32];
1296 if(Temp)
1297 {
1298 IStorage::FormatTmpPath(aBuf: aSuffix, BufSize: sizeof(aSuffix), pPath: "");
1299 }
1300 else
1301 {
1302 str_copy(dst&: aSuffix, src: ".map");
1303 }
1304
1305 if(Sha256.has_value())
1306 {
1307 char aSha256[SHA256_MAXSTRSIZE];
1308 sha256_str(digest: Sha256.value(), str: aSha256, max_len: sizeof(aSha256));
1309 str_format(buffer: pBuffer, buffer_size: BufferSize, format: "downloadedmaps/%s_%s%s", pName, aSha256, aSuffix);
1310 }
1311 else
1312 {
1313 str_format(buffer: pBuffer, buffer_size: BufferSize, format: "downloadedmaps/%s_%08x%s", pName, Crc, aSuffix);
1314 }
1315}
1316
1317const char *CClient::LoadMapSearch(const char *pMapName, const std::optional<SHA256_DIGEST> &WantedSha256, int WantedCrc)
1318{
1319 char aBuf[512];
1320 char aWanted[SHA256_MAXSTRSIZE + 16];
1321 aWanted[0] = 0;
1322 if(WantedSha256.has_value())
1323 {
1324 char aWantedSha256[SHA256_MAXSTRSIZE];
1325 sha256_str(digest: WantedSha256.value(), str: aWantedSha256, max_len: sizeof(aWantedSha256));
1326 str_format(buffer: aWanted, buffer_size: sizeof(aWanted), format: "sha256=%s ", aWantedSha256);
1327 }
1328 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "loading map, map=%s wanted %scrc=%08x", pMapName, aWanted, WantedCrc);
1329 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client", pStr: aBuf);
1330
1331 // try the normal maps folder
1332 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "maps/%s.map", pMapName);
1333 const char *pError = LoadMap(pName: pMapName, pFilename: aBuf, WantedSha256, WantedCrc);
1334 if(!pError)
1335 return nullptr;
1336
1337 // try the downloaded maps
1338 FormatMapDownloadFilename(pName: pMapName, Sha256: WantedSha256, Crc: WantedCrc, Temp: false, pBuffer: aBuf, BufferSize: sizeof(aBuf));
1339 pError = LoadMap(pName: pMapName, pFilename: aBuf, WantedSha256, WantedCrc);
1340 if(!pError)
1341 return nullptr;
1342
1343 // backward compatibility with old names
1344 if(WantedSha256.has_value())
1345 {
1346 FormatMapDownloadFilename(pName: pMapName, Sha256: std::nullopt, Crc: WantedCrc, Temp: false, pBuffer: aBuf, BufferSize: sizeof(aBuf));
1347 pError = LoadMap(pName: pMapName, pFilename: aBuf, WantedSha256, WantedCrc);
1348 if(!pError)
1349 return nullptr;
1350 }
1351
1352 // search for the map within subfolders
1353 char aFilename[IO_MAX_PATH_LENGTH];
1354 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "%s.map", pMapName);
1355 if(Storage()->FindFile(pFilename: aFilename, pPath: "maps", Type: IStorage::TYPE_ALL, pBuffer: aBuf, BufferSize: sizeof(aBuf)))
1356 {
1357 pError = LoadMap(pName: pMapName, pFilename: aBuf, WantedSha256, WantedCrc);
1358 if(!pError)
1359 return nullptr;
1360 }
1361
1362 static char s_aErrorMsg[256];
1363 str_format(buffer: s_aErrorMsg, buffer_size: sizeof(s_aErrorMsg), format: "Could not find map '%s'", pMapName);
1364 return s_aErrorMsg;
1365}
1366
1367void CClient::ProcessConnlessPacket(CNetChunk *pPacket)
1368{
1369 // server info
1370 if(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_INFO))
1371 {
1372 int Type = -1;
1373 if(mem_comp(a: pPacket->m_pData, b: SERVERBROWSE_INFO, size: sizeof(SERVERBROWSE_INFO)) == 0)
1374 Type = SERVERINFO_VANILLA;
1375 else if(mem_comp(a: pPacket->m_pData, b: SERVERBROWSE_INFO_EXTENDED, size: sizeof(SERVERBROWSE_INFO_EXTENDED)) == 0)
1376 Type = SERVERINFO_EXTENDED;
1377 else if(mem_comp(a: pPacket->m_pData, b: SERVERBROWSE_INFO_EXTENDED_MORE, size: sizeof(SERVERBROWSE_INFO_EXTENDED_MORE)) == 0)
1378 Type = SERVERINFO_EXTENDED_MORE;
1379
1380 if(Type != -1)
1381 {
1382 void *pData = (unsigned char *)pPacket->m_pData + sizeof(SERVERBROWSE_INFO);
1383 int DataSize = pPacket->m_DataSize - sizeof(SERVERBROWSE_INFO);
1384 ProcessServerInfo(Type, pFrom: &pPacket->m_Address, pData, DataSize);
1385 }
1386 }
1387}
1388
1389static int SavedServerInfoType(int Type)
1390{
1391 if(Type == SERVERINFO_EXTENDED_MORE)
1392 return SERVERINFO_EXTENDED;
1393
1394 return Type;
1395}
1396
1397void CClient::ProcessServerInfo(int RawType, NETADDR *pFrom, const void *pData, int DataSize)
1398{
1399 CServerBrowser::CServerEntry *pEntry = m_ServerBrowser.Find(Addr: *pFrom);
1400
1401 CServerInfo Info = {.m_ServerIndex: 0};
1402 int SavedType = SavedServerInfoType(Type: RawType);
1403 if(SavedType == SERVERINFO_EXTENDED && pEntry && pEntry->m_GotInfo && SavedType == pEntry->m_Info.m_Type)
1404 {
1405 Info = pEntry->m_Info;
1406 }
1407 else
1408 {
1409 Info.m_NumAddresses = 1;
1410 Info.m_aAddresses[0] = *pFrom;
1411 }
1412
1413 Info.m_Type = SavedType;
1414
1415 net_addr_str(addr: pFrom, string: Info.m_aAddress, max_length: sizeof(Info.m_aAddress), add_port: true);
1416
1417 CUnpacker Up;
1418 Up.Reset(pData, Size: DataSize);
1419
1420#define GET_STRING(array) str_copy(array, Up.GetString(CUnpacker::SANITIZE_CC | CUnpacker::SKIP_START_WHITESPACES))
1421#define GET_INT(integer) (integer) = str_toint(Up.GetString())
1422
1423 int Token;
1424 int PacketNo = 0; // Only used if SavedType == SERVERINFO_EXTENDED
1425
1426 GET_INT(Token);
1427 if(RawType != SERVERINFO_EXTENDED_MORE)
1428 {
1429 GET_STRING(Info.m_aVersion);
1430 GET_STRING(Info.m_aName);
1431 GET_STRING(Info.m_aMap);
1432
1433 if(SavedType == SERVERINFO_EXTENDED)
1434 {
1435 GET_INT(Info.m_MapCrc);
1436 GET_INT(Info.m_MapSize);
1437 }
1438
1439 GET_STRING(Info.m_aGameType);
1440 GET_INT(Info.m_Flags);
1441 GET_INT(Info.m_NumPlayers);
1442 GET_INT(Info.m_MaxPlayers);
1443 GET_INT(Info.m_NumClients);
1444 GET_INT(Info.m_MaxClients);
1445
1446 // don't add invalid info to the server browser list
1447 if(Info.m_NumClients < 0 || Info.m_MaxClients < 0 ||
1448 Info.m_NumPlayers < 0 || Info.m_MaxPlayers < 0 ||
1449 Info.m_NumPlayers > Info.m_NumClients || Info.m_MaxPlayers > Info.m_MaxClients)
1450 {
1451 return;
1452 }
1453
1454 m_ServerBrowser.UpdateServerCommunity(pInfo: &Info);
1455 m_ServerBrowser.UpdateServerRank(pInfo: &Info);
1456
1457 switch(SavedType)
1458 {
1459 case SERVERINFO_VANILLA:
1460 if(Info.m_MaxPlayers > VANILLA_MAX_CLIENTS ||
1461 Info.m_MaxClients > VANILLA_MAX_CLIENTS)
1462 {
1463 return;
1464 }
1465 break;
1466 case SERVERINFO_64_LEGACY:
1467 if(Info.m_MaxPlayers > MAX_CLIENTS ||
1468 Info.m_MaxClients > MAX_CLIENTS)
1469 {
1470 return;
1471 }
1472 break;
1473 case SERVERINFO_EXTENDED:
1474 if(Info.m_NumPlayers > Info.m_NumClients)
1475 return;
1476 break;
1477 default:
1478 dbg_assert_failed("unknown serverinfo type");
1479 }
1480
1481 if(SavedType == SERVERINFO_EXTENDED)
1482 PacketNo = 0;
1483 }
1484 else
1485 {
1486 GET_INT(PacketNo);
1487 // 0 needs to be excluded because that's reserved for the main packet.
1488 if(PacketNo <= 0 || PacketNo >= 64)
1489 return;
1490 }
1491
1492 bool DuplicatedPacket = false;
1493 if(SavedType == SERVERINFO_EXTENDED)
1494 {
1495 Up.GetString(); // extra info, reserved
1496
1497 uint64_t Flag = (uint64_t)1 << PacketNo;
1498 DuplicatedPacket = Info.m_ReceivedPackets & Flag;
1499 Info.m_ReceivedPackets |= Flag;
1500 }
1501
1502 bool IgnoreError = false;
1503 for(int i = 0; i < MAX_CLIENTS && (int)Info.m_vClients.size() < MAX_CLIENTS && !Up.Error(); i++)
1504 {
1505 CServerInfo::CClient Client = {};
1506 GET_STRING(Client.m_aName);
1507 if(Up.Error())
1508 {
1509 // Packet end, no problem unless it happens during one
1510 // player info, so ignore the error.
1511 IgnoreError = true;
1512 break;
1513 }
1514 GET_STRING(Client.m_aClan);
1515 GET_INT(Client.m_Country);
1516 if(!in_range(a: Client.m_Country, lower: CountryCode::MINIMUM, upper: CountryCode::MAXIMUM))
1517 {
1518 Client.m_Country = CountryCode::DEFAULT;
1519 }
1520 GET_INT(Client.m_Score);
1521 GET_INT(Client.m_Player);
1522 if(SavedType == SERVERINFO_EXTENDED)
1523 {
1524 Up.GetString(); // extra info, reserved
1525 }
1526 if(!Up.Error())
1527 {
1528 if(SavedType == SERVERINFO_64_LEGACY)
1529 {
1530 uint64_t Flag = (uint64_t)1 << i;
1531 if(!(Info.m_ReceivedPackets & Flag))
1532 {
1533 Info.m_ReceivedPackets |= Flag;
1534 Info.m_vClients.push_back(x: Client);
1535 }
1536 }
1537 else
1538 {
1539 Info.m_vClients.push_back(x: Client);
1540 }
1541 }
1542 }
1543
1544 str_clean_whitespaces(str: Info.m_aName);
1545
1546 if(!Up.Error() || IgnoreError)
1547 {
1548 if(!DuplicatedPacket && (!pEntry || !pEntry->m_GotInfo || SavedType >= pEntry->m_Info.m_Type))
1549 {
1550 m_ServerBrowser.OnServerInfoUpdate(Addr: *pFrom, Token, pInfo: &Info);
1551 }
1552
1553 // Player info is irrelevant for the client (while connected),
1554 // it gets its info from elsewhere.
1555 //
1556 // SERVERINFO_EXTENDED_MORE doesn't carry any server
1557 // information, so just skip it.
1558 if(m_aNetClient[CONN_MAIN].State() == NETSTATE_ONLINE &&
1559 ServerAddress() == *pFrom &&
1560 RawType != SERVERINFO_EXTENDED_MORE)
1561 {
1562 // Only accept server info that has a type that is
1563 // newer or equal to something the server already sent
1564 // us.
1565 if(SavedType >= m_CurrentServerInfo.m_Type &&
1566 GameClient()->Map()->IsLoaded())
1567 {
1568 SetCurrentServerInfo(Info);
1569 Discord()->UpdateServerInfo(ServerInfo: m_CurrentServerInfo);
1570 }
1571
1572 bool ValidPong = false;
1573 if(!m_ServerCapabilities.m_PingEx && m_CurrentServerCurrentPingTime >= 0 && SavedType >= m_CurrentServerPingInfoType)
1574 {
1575 if(RawType == SERVERINFO_VANILLA)
1576 {
1577 ValidPong = Token == m_CurrentServerPingBasicToken;
1578 }
1579 else if(RawType == SERVERINFO_EXTENDED)
1580 {
1581 ValidPong = Token == m_CurrentServerPingToken;
1582 }
1583 }
1584 if(ValidPong)
1585 {
1586 int LatencyMs = (time_get() - m_CurrentServerCurrentPingTime) * 1000 / time_freq();
1587 m_ServerBrowser.SetCurrentServerPing(Addr: ServerAddress(), Ping: LatencyMs);
1588 m_CurrentServerPingInfoType = SavedType;
1589 m_CurrentServerCurrentPingTime = -1;
1590
1591 char aBuf[64];
1592 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "got pong from current server, latency=%dms", LatencyMs);
1593 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aBuf);
1594 }
1595 }
1596 }
1597
1598#undef GET_STRING
1599#undef GET_INT
1600}
1601
1602static CServerCapabilities GetServerCapabilities(int Version, int Flags, bool Sixup)
1603{
1604 CServerCapabilities Result;
1605 bool DDNet = false;
1606 if(Version >= 1)
1607 {
1608 DDNet = Flags & SERVERCAPFLAG_DDNET;
1609 }
1610 Result.m_ChatTimeoutCode = DDNet;
1611 Result.m_AnyPlayerFlag = !Sixup;
1612 Result.m_PingEx = false;
1613 Result.m_AllowDummy = true;
1614 Result.m_SyncWeaponInput = false;
1615 if(Version >= 1)
1616 {
1617 Result.m_ChatTimeoutCode = Flags & SERVERCAPFLAG_CHATTIMEOUTCODE;
1618 }
1619 if(Version >= 2)
1620 {
1621 Result.m_AnyPlayerFlag = Flags & SERVERCAPFLAG_ANYPLAYERFLAG;
1622 }
1623 if(Version >= 3)
1624 {
1625 Result.m_PingEx = Flags & SERVERCAPFLAG_PINGEX;
1626 }
1627 if(Version >= 4)
1628 {
1629 Result.m_AllowDummy = Flags & SERVERCAPFLAG_ALLOWDUMMY;
1630 }
1631 if(Version >= 5)
1632 {
1633 Result.m_SyncWeaponInput = Flags & SERVERCAPFLAG_SYNCWEAPONINPUT;
1634 }
1635 return Result;
1636}
1637
1638void CClient::ProcessServerPacket(CNetChunk *pPacket, int Conn, bool Dummy)
1639{
1640 CUnpacker Unpacker;
1641 Unpacker.Reset(pData: pPacket->m_pData, Size: pPacket->m_DataSize);
1642 CMsgPacker Packer(NETMSG_EX, true);
1643
1644 // unpack msgid and system flag
1645 int Msg;
1646 bool Sys;
1647
1648 int Result = UnpackMessageId(pId: &Msg, pSys: &Sys, pUnpacker: &Unpacker, pPacker: &Packer);
1649 if(Result == UNPACKMESSAGE_ERROR)
1650 {
1651 return;
1652 }
1653 else if(Result == UNPACKMESSAGE_ANSWER)
1654 {
1655 SendMsg(Conn, pMsg: &Packer, Flags: MSGFLAG_VITAL);
1656 }
1657
1658 // allocates the memory for the translated data
1659 CPacker Packer6;
1660 if(IsSixup())
1661 {
1662 bool IsExMsg = false;
1663 int Success = !TranslateSysMsg(pMsgId: &Msg, System: Sys, pUnpacker: &Unpacker, pPacker: &Packer6, pPacket, pIsExMsg: &IsExMsg);
1664 if(Msg < 0)
1665 return;
1666 if(Success && !IsExMsg)
1667 {
1668 Unpacker.Reset(pData: Packer6.Data(), Size: Packer6.Size());
1669 }
1670 }
1671
1672 if(Sys)
1673 {
1674 // system message
1675 if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_DETAILS)
1676 {
1677 const char *pMap = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC | CUnpacker::SKIP_START_WHITESPACES);
1678 SHA256_DIGEST *pMapSha256 = (SHA256_DIGEST *)Unpacker.GetRaw(Size: sizeof(*pMapSha256));
1679 int MapCrc = Unpacker.GetInt();
1680 int MapSize = Unpacker.GetInt();
1681 if(Unpacker.Error())
1682 {
1683 return;
1684 }
1685
1686 const char *pMapUrl = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
1687 if(Unpacker.Error())
1688 {
1689 pMapUrl = "";
1690 }
1691
1692 m_MapDetails = std::make_optional<CMapDetails>();
1693 CMapDetails &MapDetails = m_MapDetails.value();
1694 str_copy(dst&: MapDetails.m_aName, src: pMap);
1695 MapDetails.m_Size = MapSize;
1696 MapDetails.m_Crc = MapCrc;
1697 MapDetails.m_Sha256 = *pMapSha256;
1698 str_copy(dst&: MapDetails.m_aUrl, src: pMapUrl);
1699 }
1700 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_CAPABILITIES)
1701 {
1702 if(!m_CanReceiveServerCapabilities)
1703 {
1704 return;
1705 }
1706 int Version = Unpacker.GetInt();
1707 int Flags = Unpacker.GetInt();
1708 if(Unpacker.Error() || Version <= 0)
1709 {
1710 return;
1711 }
1712 m_ServerCapabilities = GetServerCapabilities(Version, Flags, Sixup: IsSixup());
1713 m_CanReceiveServerCapabilities = false;
1714 m_ServerSentCapabilities = true;
1715 }
1716 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_CHANGE)
1717 {
1718 if(m_CanReceiveServerCapabilities)
1719 {
1720 m_ServerCapabilities = GetServerCapabilities(Version: 0, Flags: 0, Sixup: IsSixup());
1721 m_CanReceiveServerCapabilities = false;
1722 }
1723 std::optional<CMapDetails> MapDetails = std::nullopt;
1724 std::swap(lhs&: MapDetails, rhs&: m_MapDetails);
1725
1726 const char *pMap = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC | CUnpacker::SKIP_START_WHITESPACES);
1727 int MapCrc = Unpacker.GetInt();
1728 int MapSize = Unpacker.GetInt();
1729 if(Unpacker.Error())
1730 {
1731 return;
1732 }
1733 if(MapSize < 0 || MapSize > 1024 * 1024 * 1024) // 1 GiB
1734 {
1735 DisconnectWithReason(pReason: "invalid map size");
1736 return;
1737 }
1738
1739 if(!str_valid_filename(str: pMap))
1740 {
1741 DisconnectWithReason(pReason: "map name is not a valid filename");
1742 return;
1743 }
1744
1745 if(m_DummyConnected && !m_DummyReconnectOnReload)
1746 {
1747 DummyDisconnect(pReason: nullptr);
1748 }
1749
1750 ResetMapDownload(ResetActive: true);
1751
1752 std::optional<SHA256_DIGEST> MapSha256;
1753 const char *pMapUrl = nullptr;
1754 if(MapDetails.has_value() &&
1755 str_comp(a: MapDetails->m_aName, b: pMap) == 0 &&
1756 MapDetails->m_Size == MapSize &&
1757 MapDetails->m_Crc == MapCrc)
1758 {
1759 MapSha256 = MapDetails->m_Sha256;
1760 pMapUrl = MapDetails->m_aUrl[0] ? MapDetails->m_aUrl : nullptr;
1761 }
1762
1763 if(LoadMapSearch(pMapName: pMap, WantedSha256: MapSha256, WantedCrc: MapCrc) == nullptr)
1764 {
1765 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client/network", pStr: "loading done");
1766 SetLoadingStateDetail(IClient::ELoadingStateDetail::SENDING_READY);
1767 SendReady(Conn: CONN_MAIN);
1768 }
1769 else
1770 {
1771 // start map download
1772 FormatMapDownloadFilename(pName: pMap, Sha256: MapSha256, Crc: MapCrc, Temp: false, pBuffer: m_aMapdownloadFilename, BufferSize: sizeof(m_aMapdownloadFilename));
1773 FormatMapDownloadFilename(pName: pMap, Sha256: MapSha256, Crc: MapCrc, Temp: true, pBuffer: m_aMapdownloadFilenameTemp, BufferSize: sizeof(m_aMapdownloadFilenameTemp));
1774
1775 char aBuf[256];
1776 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "starting to download map to '%s'", m_aMapdownloadFilenameTemp);
1777 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client/network", pStr: aBuf);
1778
1779 str_copy(dst&: m_aMapdownloadName, src: pMap);
1780 m_MapdownloadSha256 = MapSha256;
1781 m_MapdownloadCrc = MapCrc;
1782 m_MapdownloadTotalsize = MapSize;
1783
1784 if(MapSha256.has_value())
1785 {
1786 char aUrl[256];
1787 char aEscaped[256];
1788 EscapeUrl(aBuf&: aEscaped, pStr: str_startswith(str: m_aMapdownloadFilename, prefix: "downloadedmaps/"));
1789 bool UseConfigUrl = str_comp(a: g_Config.m_ClMapDownloadUrl, b: "https://maps.ddnet.org") != 0 || m_aMapDownloadUrl[0] == '\0';
1790 str_format(buffer: aUrl, buffer_size: sizeof(aUrl), format: "%s/%s", UseConfigUrl ? g_Config.m_ClMapDownloadUrl : m_aMapDownloadUrl, aEscaped);
1791
1792 m_pMapdownloadTask = HttpGetFile(pUrl: pMapUrl ? pMapUrl : aUrl, pStorage: Storage(), pOutputFile: m_aMapdownloadFilenameTemp, StorageType: IStorage::TYPE_SAVE);
1793 m_pMapdownloadTask->Timeout(Timeout: CTimeout{.m_ConnectTimeoutMs: g_Config.m_ClMapDownloadConnectTimeoutMs, .m_TimeoutMs: 0, .m_LowSpeedLimit: g_Config.m_ClMapDownloadLowSpeedLimit, .m_LowSpeedTime: g_Config.m_ClMapDownloadLowSpeedTime});
1794 m_pMapdownloadTask->MaxResponseSize(MaxResponseSize: MapSize);
1795 m_pMapdownloadTask->ExpectSha256(Sha256: MapSha256.value());
1796 Http()->Run(pRequest: m_pMapdownloadTask);
1797 }
1798 else
1799 {
1800 SendMapRequest();
1801 }
1802 }
1803 }
1804 else if(Conn == CONN_MAIN && Msg == NETMSG_MAP_DATA)
1805 {
1806 if(!m_MapdownloadFileTemp)
1807 {
1808 return;
1809 }
1810 int Last = -1;
1811 int MapCRC = -1;
1812 int Chunk = -1;
1813 int Size = -1;
1814
1815 if(IsSixup())
1816 {
1817 if(m_TranslationContext.m_MapdownloadTotalsize <= 0 ||
1818 m_TranslationContext.m_MapDownloadChunkSize <= 0 ||
1819 m_TranslationContext.m_MapDownloadChunksPerRequest <= 0)
1820 {
1821 return;
1822 }
1823 MapCRC = m_MapdownloadCrc;
1824 Chunk = m_MapdownloadChunk;
1825 Size = std::min(a: m_TranslationContext.m_MapDownloadChunkSize, b: m_TranslationContext.m_MapdownloadTotalsize - m_MapdownloadAmount);
1826 }
1827 else
1828 {
1829 Last = Unpacker.GetInt();
1830 MapCRC = Unpacker.GetInt();
1831 Chunk = Unpacker.GetInt();
1832 Size = Unpacker.GetInt();
1833 }
1834
1835 const unsigned char *pData = Unpacker.GetRaw(Size);
1836 if(Unpacker.Error() || Size <= 0 || MapCRC != m_MapdownloadCrc || Chunk != m_MapdownloadChunk)
1837 {
1838 return;
1839 }
1840
1841 io_write(io: m_MapdownloadFileTemp, buffer: pData, size: Size);
1842
1843 m_MapdownloadAmount += Size;
1844
1845 if(IsSixup())
1846 Last = m_MapdownloadAmount == m_TranslationContext.m_MapdownloadTotalsize;
1847
1848 if(Last)
1849 {
1850 if(m_MapdownloadFileTemp)
1851 {
1852 io_close(io: m_MapdownloadFileTemp);
1853 m_MapdownloadFileTemp = nullptr;
1854 }
1855 FinishMapDownload();
1856 }
1857 else
1858 {
1859 // request new chunk
1860 m_MapdownloadChunk++;
1861
1862 if(IsSixup() && (m_MapdownloadChunk % m_TranslationContext.m_MapDownloadChunksPerRequest == 0))
1863 {
1864 CMsgPacker MsgP(protocol7::NETMSG_REQUEST_MAP_DATA, true, true);
1865 SendMsg(Conn: CONN_MAIN, pMsg: &MsgP, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
1866 }
1867 else
1868 {
1869 CMsgPacker MsgP(NETMSG_REQUEST_MAP_DATA, true);
1870 MsgP.AddInt(i: m_MapdownloadChunk);
1871 SendMsg(Conn: CONN_MAIN, pMsg: &MsgP, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
1872 }
1873
1874 if(g_Config.m_Debug)
1875 {
1876 char aBuf[256];
1877 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "requested chunk %d", m_MapdownloadChunk);
1878 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "client/network", pStr: aBuf);
1879 }
1880 }
1881 }
1882 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_RELOAD)
1883 {
1884 if(m_DummyConnected)
1885 {
1886 m_DummyReconnectOnReload = true;
1887 m_DummyDeactivateOnReconnect = g_Config.m_ClDummy == 0;
1888 g_Config.m_ClDummy = 0;
1889 }
1890 else
1891 {
1892 m_DummyDeactivateOnReconnect = false;
1893 }
1894 }
1895 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_CON_READY)
1896 {
1897 if(!GameClient()->Map()->IsLoaded())
1898 {
1899 return;
1900 }
1901 GameClient()->OnConnected();
1902 if(m_DummyReconnectOnReload)
1903 {
1904 m_DummySendConnInfo = true;
1905 m_DummyReconnectOnReload = false;
1906 }
1907#if defined(CONF_PLATFORM_IOS)
1908 else if(m_DummyReconnectOnResume)
1909 {
1910 m_DummyReconnectOnResume = false;
1911 DummyConnect();
1912 }
1913#endif
1914 }
1915 else if(Conn == CONN_DUMMY && Msg == NETMSG_CON_READY)
1916 {
1917 m_DummyConnected = true;
1918 m_DummyConnecting = false;
1919 g_Config.m_ClDummy = 1;
1920 Rcon(pCmd: "crashmeplx");
1921 if(m_aRconAuthed[0] && !m_aRconAuthed[1])
1922 RconAuth(pName: m_aRconUsername, pPassword: m_aRconPassword);
1923 }
1924 else if(Msg == NETMSG_PING)
1925 {
1926 CMsgPacker MsgP(NETMSG_PING_REPLY, true);
1927 int Vital = (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 ? MSGFLAG_VITAL : 0;
1928 SendMsg(Conn, pMsg: &MsgP, Flags: MSGFLAG_FLUSH | Vital);
1929 }
1930 else if(Msg == NETMSG_PINGEX)
1931 {
1932 CUuid *pId = (CUuid *)Unpacker.GetRaw(Size: sizeof(*pId));
1933 if(Unpacker.Error())
1934 {
1935 return;
1936 }
1937 CMsgPacker MsgP(NETMSG_PONGEX, true);
1938 MsgP.AddRaw(pData: pId, Size: sizeof(*pId));
1939 int Vital = (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 ? MSGFLAG_VITAL : 0;
1940 SendMsg(Conn, pMsg: &MsgP, Flags: MSGFLAG_FLUSH | Vital);
1941 }
1942 else if(Conn == CONN_MAIN && Msg == NETMSG_PONGEX)
1943 {
1944 CUuid *pId = (CUuid *)Unpacker.GetRaw(Size: sizeof(*pId));
1945 if(Unpacker.Error())
1946 {
1947 return;
1948 }
1949 if(m_ServerCapabilities.m_PingEx && m_CurrentServerCurrentPingTime >= 0 && *pId == m_CurrentServerPingUuid)
1950 {
1951 int LatencyMs = (time_get() - m_CurrentServerCurrentPingTime) * 1000 / time_freq();
1952 m_ServerBrowser.SetCurrentServerPing(Addr: ServerAddress(), Ping: LatencyMs);
1953 m_CurrentServerCurrentPingTime = -1;
1954
1955 char aBuf[64];
1956 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "got pong from current server, latency=%dms", LatencyMs);
1957 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aBuf);
1958 }
1959 }
1960 else if(Msg == NETMSG_CHECKSUM_REQUEST)
1961 {
1962 CUuid *pUuid = (CUuid *)Unpacker.GetRaw(Size: sizeof(*pUuid));
1963 if(Unpacker.Error())
1964 {
1965 return;
1966 }
1967 int ResultCheck = HandleChecksum(Conn, Uuid: *pUuid, pUnpacker: &Unpacker);
1968 if(ResultCheck)
1969 {
1970 CMsgPacker MsgP(NETMSG_CHECKSUM_ERROR, true);
1971 MsgP.AddRaw(pData: pUuid, Size: sizeof(*pUuid));
1972 MsgP.AddInt(i: ResultCheck);
1973 SendMsg(Conn, pMsg: &MsgP, Flags: MSGFLAG_VITAL);
1974 }
1975 }
1976 else if(Msg == NETMSG_RECONNECT)
1977 {
1978 if(Conn == CONN_MAIN)
1979 {
1980 Connect(pAddress: m_aConnectAddressStr);
1981 }
1982 else
1983 {
1984 DummyDisconnect(pReason: "reconnect");
1985 // Reset dummy connect time to allow immediate reconnect
1986 m_LastDummyConnectTime = 0.0f;
1987 DummyConnect();
1988 }
1989 }
1990 else if(Msg == NETMSG_REDIRECT)
1991 {
1992 int RedirectPort = Unpacker.GetInt();
1993 if(Unpacker.Error())
1994 {
1995 return;
1996 }
1997 if(Conn == CONN_MAIN)
1998 {
1999 NETADDR ServerAddr = ServerAddress();
2000 ServerAddr.port = RedirectPort;
2001 char aAddr[NETADDR_MAXSTRSIZE];
2002 net_addr_str(addr: &ServerAddr, string: aAddr, max_length: sizeof(aAddr), add_port: true);
2003 Connect(pAddress: aAddr);
2004 }
2005 else
2006 {
2007 DummyDisconnect(pReason: "redirect");
2008 if(ServerAddress().port != RedirectPort)
2009 {
2010 // Only allow redirecting to the same port to reconnect. The dummy
2011 // should not be connected to a different server than the main, as
2012 // the client assumes that main and dummy use the same map.
2013 return;
2014 }
2015 // Reset dummy connect time to allow immediate reconnect
2016 m_LastDummyConnectTime = 0.0f;
2017 DummyConnect();
2018 }
2019 }
2020 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_ADD)
2021 {
2022 const char *pName = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
2023 const char *pHelp = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
2024 const char *pParams = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
2025 if(!Unpacker.Error())
2026 {
2027 m_pConsole->RegisterTemp(pName, pParams, Flags: CFGFLAG_SERVER, pHelp);
2028 GameClient()->ForceUpdateConsoleRemoteCompletionSuggestions();
2029 }
2030 m_GotRconCommands++;
2031 }
2032 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_REM)
2033 {
2034 const char *pName = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
2035 if(!Unpacker.Error())
2036 {
2037 m_pConsole->DeregisterTemp(pName);
2038 GameClient()->ForceUpdateConsoleRemoteCompletionSuggestions();
2039 }
2040 }
2041 else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_AUTH_STATUS)
2042 {
2043 int ResultInt = Unpacker.GetInt();
2044 if(!Unpacker.Error())
2045 {
2046 m_aRconAuthed[Conn] = ResultInt;
2047
2048 if(m_aRconAuthed[Conn])
2049 RconAuth(pName: m_aRconUsername, pPassword: m_aRconPassword, Dummy: g_Config.m_ClDummy ^ 1);
2050 }
2051 if(Conn == CONN_MAIN)
2052 {
2053 int Old = m_UseTempRconCommands;
2054 m_UseTempRconCommands = Unpacker.GetInt();
2055 if(Unpacker.Error())
2056 {
2057 m_UseTempRconCommands = 0;
2058 }
2059 if(Old != 0 && m_UseTempRconCommands == 0)
2060 {
2061 m_pConsole->DeregisterTempAll();
2062 m_ExpectedRconCommands = -1;
2063 m_vMaplistEntries.clear();
2064 GameClient()->ForceUpdateConsoleRemoteCompletionSuggestions();
2065 m_ExpectedMaplistEntries = -1;
2066 }
2067 }
2068 }
2069 else if(!Dummy && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_LINE)
2070 {
2071 const char *pLine = Unpacker.GetString();
2072 if(!Unpacker.Error())
2073 {
2074 GameClient()->OnRconLine(pLine);
2075 }
2076 }
2077 else if(Conn == CONN_MAIN && Msg == NETMSG_PING_REPLY)
2078 {
2079 char aBuf[256];
2080 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "latency %.2f", (time_get() - m_PingStartTime) * 1000 / (float)time_freq());
2081 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client/network", pStr: aBuf);
2082 }
2083 else if(Msg == NETMSG_INPUTTIMING)
2084 {
2085 int InputPredTick = Unpacker.GetInt();
2086 int TimeLeft = Unpacker.GetInt();
2087 if(Unpacker.Error())
2088 {
2089 return;
2090 }
2091
2092 int64_t Now = time_get();
2093
2094 // adjust our prediction time
2095 int64_t Target = 0;
2096 for(int k = 0; k < 200; k++)
2097 {
2098 if(m_aInputs[Conn][k].m_Tick == InputPredTick)
2099 {
2100 Target = m_aInputs[Conn][k].m_PredictedTime + (Now - m_aInputs[Conn][k].m_Time);
2101 Target = Target - (int64_t)((TimeLeft / 1000.0f) * time_freq());
2102 break;
2103 }
2104 }
2105
2106 if(Target)
2107 m_PredictedTime.Update(pGraph: &m_aInputtimeMarginGraphs[Conn], Target, TimeLeft, AdjustDirection: CSmoothTime::ADJUSTDIRECTION_UP);
2108 }
2109 else if(Msg == NETMSG_SNAP || Msg == NETMSG_SNAPSINGLE || Msg == NETMSG_SNAPEMPTY)
2110 {
2111 // We are not allowed to process snapshots yet.
2112 if(State() < IClient::STATE_LOADING ||
2113 !GameClient()->Map()->IsLoaded())
2114 {
2115 return;
2116 }
2117
2118 int GameTick = Unpacker.GetInt();
2119 int DeltaTick = GameTick - Unpacker.GetInt();
2120
2121 int NumParts = 1;
2122 int Part = 0;
2123 if(Msg == NETMSG_SNAP)
2124 {
2125 NumParts = Unpacker.GetInt();
2126 Part = Unpacker.GetInt();
2127 }
2128
2129 unsigned int Crc = 0;
2130 int PartSize = 0;
2131 if(Msg != NETMSG_SNAPEMPTY)
2132 {
2133 Crc = Unpacker.GetInt();
2134 PartSize = Unpacker.GetInt();
2135 }
2136
2137 const char *pData = (const char *)Unpacker.GetRaw(Size: PartSize);
2138 if(Unpacker.Error() || NumParts < 1 || NumParts > CSnapshot::MAX_PARTS || Part < 0 || Part >= NumParts || PartSize < 0 || PartSize > MAX_SNAPSHOT_PACKSIZE)
2139 {
2140 return;
2141 }
2142
2143 // Check m_aAckGameTick to see if we already got a snapshot for that tick
2144 if(GameTick >= m_aCurrentRecvTick[Conn] && GameTick > m_aAckGameTick[Conn])
2145 {
2146 if(GameTick != m_aCurrentRecvTick[Conn])
2147 {
2148 m_aSnapshotParts[Conn] = 0;
2149 m_aCurrentRecvTick[Conn] = GameTick;
2150 m_aSnapshotIncomingDataSize[Conn] = 0;
2151 }
2152
2153 mem_copy(dest: (char *)m_aaSnapshotIncomingData[Conn] + Part * MAX_SNAPSHOT_PACKSIZE, source: pData, size: std::clamp(val: PartSize, lo: 0, hi: (int)sizeof(m_aaSnapshotIncomingData[Conn]) - Part * MAX_SNAPSHOT_PACKSIZE));
2154 m_aSnapshotParts[Conn] |= (uint64_t)(1) << Part;
2155
2156 if(Part == NumParts - 1)
2157 {
2158 m_aSnapshotIncomingDataSize[Conn] = (NumParts - 1) * MAX_SNAPSHOT_PACKSIZE + PartSize;
2159 }
2160
2161 if((NumParts < CSnapshot::MAX_PARTS && m_aSnapshotParts[Conn] == (((uint64_t)(1) << NumParts) - 1)) ||
2162 (NumParts == CSnapshot::MAX_PARTS && m_aSnapshotParts[Conn] == std::numeric_limits<uint64_t>::max()))
2163 {
2164 CSnapshotDeltaBuffer TmpBuffer2;
2165 CSnapshotBuffer TmpBuffer3;
2166
2167 // reset snapshotting
2168 m_aSnapshotParts[Conn] = 0;
2169
2170 // find snapshot that we should use as delta
2171 const CSnapshot *pDeltaShot = CSnapshot::EmptySnapshot();
2172 if(DeltaTick >= 0)
2173 {
2174 int DeltashotSize = m_aSnapshotStorage[Conn].Get(Tick: DeltaTick, pTagtime: nullptr, ppData: &pDeltaShot, ppAltData: nullptr);
2175
2176 if(DeltashotSize < 0)
2177 {
2178 // couldn't find the delta snapshots that the server used
2179 // to compress this snapshot. force the server to resync
2180 if(g_Config.m_Debug)
2181 {
2182 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "client", pStr: "error, couldn't find the delta snapshot");
2183 }
2184
2185 // ack snapshot
2186 m_aAckGameTick[Conn] = -1;
2187 SendInput();
2188 return;
2189 }
2190 }
2191
2192 // decompress snapshot
2193 const void *pDeltaData = SnapshotDelta()->EmptyDelta();
2194 int DeltaSize = sizeof(int) * 3;
2195
2196 if(m_aSnapshotIncomingDataSize[Conn])
2197 {
2198 int IntSize = CVariableInt::Decompress(pSrc: m_aaSnapshotIncomingData[Conn], SrcSize: m_aSnapshotIncomingDataSize[Conn], pDst: TmpBuffer2.m_aData, DstSize: sizeof(TmpBuffer2.m_aData));
2199
2200 if(IntSize < 0) // failure during decompression
2201 return;
2202
2203 pDeltaData = TmpBuffer2.m_aData;
2204 DeltaSize = IntSize;
2205 }
2206
2207 // unpack delta
2208 const int SnapSize = SnapshotDelta()->UnpackDelta(pFrom: pDeltaShot, pTo: &TmpBuffer3, pSrcData: pDeltaData, DataSize: DeltaSize);
2209 if(SnapSize < 0)
2210 {
2211 dbg_msg(sys: "client", fmt: "delta unpack failed. error=%d", SnapSize);
2212 return;
2213 }
2214 if(!TmpBuffer3.AsSnapshot()->IsValid(ActualSize: SnapSize))
2215 {
2216 dbg_msg(sys: "client", fmt: "snapshot invalid. SnapSize=%d, DeltaSize=%d", SnapSize, DeltaSize);
2217 return;
2218 }
2219
2220 if(Msg != NETMSG_SNAPEMPTY && TmpBuffer3.AsSnapshot()->Crc() != Crc)
2221 {
2222 log_error("client", "snapshot crc error #%d - tick=%d wantedcrc=%d gotcrc=%d compressed_size=%d delta_tick=%d",
2223 m_SnapCrcErrors, GameTick, Crc, TmpBuffer3.AsSnapshot()->Crc(), m_aSnapshotIncomingDataSize[Conn], DeltaTick);
2224
2225 m_SnapCrcErrors++;
2226 if(m_SnapCrcErrors > 10)
2227 {
2228 // to many errors, send reset
2229 m_aAckGameTick[Conn] = -1;
2230 SendInput();
2231 m_SnapCrcErrors = 0;
2232 }
2233 return;
2234 }
2235 else
2236 {
2237 if(m_SnapCrcErrors)
2238 m_SnapCrcErrors--;
2239 }
2240
2241 // purge old snapshots
2242 int PurgeTick = DeltaTick;
2243 if(m_aapSnapshots[Conn][SNAP_PREV] && m_aapSnapshots[Conn][SNAP_PREV]->m_Tick < PurgeTick)
2244 PurgeTick = m_aapSnapshots[Conn][SNAP_PREV]->m_Tick;
2245 if(m_aapSnapshots[Conn][SNAP_CURRENT] && m_aapSnapshots[Conn][SNAP_CURRENT]->m_Tick < PurgeTick)
2246 PurgeTick = m_aapSnapshots[Conn][SNAP_CURRENT]->m_Tick;
2247 m_aSnapshotStorage[Conn].PurgeUntil(Tick: PurgeTick);
2248
2249 // create a verified and unpacked snapshot
2250 int AltSnapSize = -1;
2251 CSnapshotBuffer AltSnapBuffer;
2252
2253 if(IsSixup())
2254 {
2255 CSnapshotBuffer TmpTransSnapBuffer;
2256 mem_copy(dest: &TmpTransSnapBuffer, source: &TmpBuffer3, size: sizeof(TmpTransSnapBuffer));
2257 AltSnapSize = GameClient()->TranslateSnap(pSnapDstSix: &AltSnapBuffer, pSnapSrcSeven: TmpTransSnapBuffer.AsSnapshot(), Conn, Dummy);
2258 }
2259 else
2260 {
2261 AltSnapSize = UnpackAndValidateSnapshot(pFrom: TmpBuffer3.AsSnapshot(), pTo: &AltSnapBuffer);
2262 }
2263
2264 if(AltSnapSize < 0)
2265 {
2266 dbg_msg(sys: "client", fmt: "unpack snapshot and validate failed. error=%d", AltSnapSize);
2267 return;
2268 }
2269
2270 // add new
2271 m_aSnapshotStorage[Conn].Add(Tick: GameTick, Tagtime: time_get(), DataSize: SnapSize, pData: TmpBuffer3.AsSnapshot(), AltDataSize: AltSnapSize, pAltData: AltSnapBuffer.AsSnapshot());
2272
2273 if(!Dummy)
2274 {
2275 GameClient()->ProcessDemoSnapshot(pSnap: TmpBuffer3.AsSnapshot());
2276
2277 CSnapshotBuffer SnapSeven;
2278 int DemoSnapSize = SnapSize;
2279 if(IsSixup())
2280 {
2281 DemoSnapSize = GameClient()->OnDemoRecSnap7(pFrom: TmpBuffer3.AsSnapshot(), pTo: &SnapSeven, Conn);
2282 if(DemoSnapSize < 0)
2283 {
2284 dbg_msg(sys: "sixup", fmt: "demo snapshot failed. error=%d", DemoSnapSize);
2285 }
2286 }
2287
2288 if(DemoSnapSize >= 0)
2289 {
2290 // add snapshot to demo
2291 for(auto &DemoRecorder : DemoRecorders())
2292 {
2293 if(DemoRecorder.IsRecording())
2294 {
2295 // write snapshot
2296 DemoRecorder.RecordSnapshot(Tick: GameTick, pData: IsSixup() ? SnapSeven.AsSnapshot() : TmpBuffer3.AsSnapshot(), Size: DemoSnapSize);
2297 }
2298 }
2299 }
2300 }
2301
2302 // apply snapshot, cycle pointers
2303 m_aReceivedSnapshots[Conn]++;
2304
2305 // we got two snapshots until we see us self as connected
2306 if(m_aReceivedSnapshots[Conn] == 2)
2307 {
2308 // start at 200ms and work from there
2309 if(!Dummy)
2310 {
2311 m_PredictedTime.Init(Target: GameTick * time_freq() / GameTickSpeed());
2312 m_PredictedTime.SetAdjustSpeed(Direction: CSmoothTime::ADJUSTDIRECTION_UP, Value: 1000.0f);
2313 m_PredictedTime.UpdateMargin(Margin: PredictionMargin() * time_freq() / 1000);
2314 }
2315 m_aGameTime[Conn].Init(Target: (GameTick - 1) * time_freq() / GameTickSpeed());
2316 m_aapSnapshots[Conn][SNAP_PREV] = m_aSnapshotStorage[Conn].m_pFirst;
2317 m_aapSnapshots[Conn][SNAP_CURRENT] = m_aSnapshotStorage[Conn].m_pLast;
2318 m_aPrevGameTick[Conn] = m_aapSnapshots[Conn][SNAP_PREV]->m_Tick;
2319 m_aCurGameTick[Conn] = m_aapSnapshots[Conn][SNAP_CURRENT]->m_Tick;
2320 if(Conn == CONN_MAIN)
2321 {
2322 m_LocalStartTime = time_get();
2323#if defined(CONF_VIDEORECORDER)
2324 if(IVideo::Current())
2325 {
2326 IVideo::Current()->SetLocalStartTime(m_LocalStartTime);
2327 }
2328#endif
2329 }
2330 if(!Dummy)
2331 {
2332 GameClient()->OnNewSnapshot(DummySwapped: false);
2333 }
2334 SetState(IClient::STATE_ONLINE);
2335 if(Conn == CONN_MAIN)
2336 {
2337 DemoRecorder_HandleAutoStart();
2338 }
2339 }
2340
2341 // adjust game time
2342 if(m_aReceivedSnapshots[Conn] > 2)
2343 {
2344 int64_t Now = m_aGameTime[Conn].Get(Now: time_get());
2345 int64_t TickStart = GameTick * time_freq() / GameTickSpeed();
2346 int64_t TimeLeft = (TickStart - Now) * 1000 / time_freq();
2347 m_aGameTime[Conn].Update(pGraph: &m_aGametimeMarginGraphs[Conn], Target: (GameTick - 1) * time_freq() / GameTickSpeed(), TimeLeft, AdjustDirection: CSmoothTime::ADJUSTDIRECTION_DOWN);
2348 }
2349
2350 if(m_aReceivedSnapshots[Conn] > GameTickSpeed() && !m_aDidPostConnect[Conn])
2351 {
2352 OnPostConnect(Conn);
2353 m_aDidPostConnect[Conn] = true;
2354 }
2355
2356 // ack snapshot
2357 m_aAckGameTick[Conn] = GameTick;
2358 }
2359 }
2360 }
2361 else if(Conn == CONN_MAIN && Msg == NETMSG_RCONTYPE)
2362 {
2363 bool UsernameReq = Unpacker.GetInt() & 1;
2364 if(!Unpacker.Error())
2365 {
2366 GameClient()->OnRconType(UsernameReq);
2367 }
2368 }
2369 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_GROUP_START)
2370 {
2371 const int ExpectedRconCommands = Unpacker.GetInt();
2372 if(Unpacker.Error() || ExpectedRconCommands < 0)
2373 return;
2374
2375 m_ExpectedRconCommands = ExpectedRconCommands;
2376 m_GotRconCommands = 0;
2377 }
2378 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_GROUP_END)
2379 {
2380 m_ExpectedRconCommands = -1;
2381 }
2382 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAPLIST_ADD)
2383 {
2384 while(true)
2385 {
2386 const char *pMapName = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC | CUnpacker::SKIP_START_WHITESPACES);
2387 if(Unpacker.Error())
2388 {
2389 return;
2390 }
2391 if(pMapName[0] != '\0')
2392 {
2393 m_vMaplistEntries.emplace_back(args&: pMapName);
2394 GameClient()->ForceUpdateConsoleRemoteCompletionSuggestions();
2395 }
2396 }
2397 }
2398 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAPLIST_GROUP_START)
2399 {
2400 const int ExpectedMaplistEntries = Unpacker.GetInt();
2401 if(Unpacker.Error() || ExpectedMaplistEntries < 0)
2402 return;
2403
2404 m_vMaplistEntries.clear();
2405 GameClient()->ForceUpdateConsoleRemoteCompletionSuggestions();
2406 m_ExpectedMaplistEntries = ExpectedMaplistEntries;
2407 }
2408 else if(Conn == CONN_MAIN && (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAPLIST_GROUP_END)
2409 {
2410 m_ExpectedMaplistEntries = -1;
2411 }
2412 }
2413 // the client handles only vital messages https://github.com/ddnet/ddnet/issues/11178
2414 else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 || Msg == NETMSGTYPE_SV_PREINPUT)
2415 {
2416 // game message
2417 if(!Dummy)
2418 {
2419 for(auto &DemoRecorder : DemoRecorders())
2420 {
2421 if(DemoRecorder.IsRecording())
2422 {
2423 DemoRecorder.RecordMessage(pData: pPacket->m_pData, Size: pPacket->m_DataSize);
2424 }
2425 }
2426 }
2427
2428 GameClient()->OnMessage(MsgId: Msg, pUnpacker: &Unpacker, Conn, Dummy);
2429 }
2430}
2431
2432int CClient::UnpackAndValidateSnapshot(CSnapshot *pFrom, CSnapshotBuffer *pTo)
2433{
2434 CUnpacker Unpacker;
2435 CSnapshotBuilder Builder;
2436 Builder.Init();
2437 CNetObjHandler *pNetObjHandler = GameClient()->GetNetObjHandler();
2438
2439 int Num = pFrom->NumItems();
2440 for(int Index = 0; Index < Num; Index++)
2441 {
2442 const CSnapshotItem *pFromItem = pFrom->GetItem(Index);
2443 const int FromItemSize = pFrom->GetItemSize(Index);
2444 const int ItemType = pFrom->GetItemType(Index);
2445 const void *pData = pFromItem->Data();
2446 Unpacker.Reset(pData, Size: FromItemSize);
2447
2448 if(ItemType <= 0)
2449 {
2450 // Don't add extended item type descriptions, they get
2451 // added implicitly (== 0).
2452 //
2453 // Don't add items of unknown item types either (< 0).
2454 continue;
2455 }
2456
2457 void *pSecuredData = pNetObjHandler->SecureUnpackObj(Type: ItemType, pUnpacker: &Unpacker);
2458 if(!pSecuredData)
2459 {
2460 if(g_Config.m_Debug && ItemType != UUID_UNKNOWN)
2461 {
2462 char aBuf[256];
2463 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "dropped weird object '%s' (%d), failed on '%s'", pNetObjHandler->GetObjName(Type: ItemType), ItemType, pNetObjHandler->FailedObjOn());
2464 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client", pStr: aBuf);
2465 }
2466 continue;
2467 }
2468 const int ItemSize = pNetObjHandler->GetUnpackedObjSize(Type: ItemType);
2469
2470 if(!Builder.NewItem(Type: ItemType, Id: pFromItem->Id(), pData: pSecuredData, Size: ItemSize))
2471 {
2472 return -4;
2473 }
2474 }
2475
2476 return Builder.Finish(pBuffer: pTo);
2477}
2478
2479void CClient::ResetMapDownload(bool ResetActive)
2480{
2481 if(m_pMapdownloadTask)
2482 {
2483 m_pMapdownloadTask->Abort();
2484 m_pMapdownloadTask = nullptr;
2485 }
2486
2487 if(m_MapdownloadFileTemp)
2488 {
2489 io_close(io: m_MapdownloadFileTemp);
2490 m_MapdownloadFileTemp = nullptr;
2491 }
2492
2493 if(Storage()->FileExists(pFilename: m_aMapdownloadFilenameTemp, Type: IStorage::TYPE_SAVE))
2494 {
2495 Storage()->RemoveFile(pFilename: m_aMapdownloadFilenameTemp, Type: IStorage::TYPE_SAVE);
2496 }
2497
2498 if(ResetActive)
2499 {
2500 m_MapdownloadChunk = 0;
2501 m_MapdownloadSha256 = std::nullopt;
2502 m_MapdownloadCrc = 0;
2503 m_MapdownloadTotalsize = -1;
2504 m_MapdownloadAmount = 0;
2505 m_aMapdownloadFilename[0] = '\0';
2506 m_aMapdownloadFilenameTemp[0] = '\0';
2507 m_aMapdownloadName[0] = '\0';
2508 }
2509}
2510
2511void CClient::FinishMapDownload()
2512{
2513 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client/network", pStr: "download complete, loading map");
2514
2515 if(!Storage()->RenameFile(pOldFilename: m_aMapdownloadFilenameTemp, pNewFilename: m_aMapdownloadFilename, Type: IStorage::TYPE_SAVE))
2516 {
2517 char aError[128 + IO_MAX_PATH_LENGTH];
2518 str_format(buffer: aError, buffer_size: sizeof(aError), format: Localize(pStr: "Could not save downloaded map. Try manually deleting this file: %s"), m_aMapdownloadFilename);
2519 DisconnectWithReason(pReason: aError);
2520 return;
2521 }
2522
2523 const char *pError = LoadMap(pName: m_aMapdownloadName, pFilename: m_aMapdownloadFilename, WantedSha256: m_MapdownloadSha256, WantedCrc: m_MapdownloadCrc);
2524 if(!pError)
2525 {
2526 ResetMapDownload(ResetActive: true);
2527 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client/network", pStr: "loading done");
2528 SendReady(Conn: CONN_MAIN);
2529 }
2530 else if(m_pMapdownloadTask) // fallback
2531 {
2532 ResetMapDownload(ResetActive: false);
2533 SendMapRequest();
2534 }
2535 else
2536 {
2537 DisconnectWithReason(pReason: pError);
2538 }
2539}
2540
2541void CClient::ResetDDNetInfoTask()
2542{
2543 if(m_pDDNetInfoTask)
2544 {
2545 m_pDDNetInfoTask->Abort();
2546 m_pDDNetInfoTask = nullptr;
2547 }
2548}
2549
2550typedef std::tuple<int, int, int> TVersion;
2551static const TVersion gs_InvalidVersion = std::make_tuple(args: -1, args: -1, args: -1);
2552
2553static TVersion ToVersion(char *pStr)
2554{
2555 int aVersion[3] = {0, 0, 0};
2556 const char *p = strtok(s: pStr, delim: ".");
2557
2558 for(int i = 0; i < 3 && p; ++i)
2559 {
2560 if(!str_isallnum(str: p))
2561 return gs_InvalidVersion;
2562
2563 aVersion[i] = str_toint(str: p);
2564 p = strtok(s: nullptr, delim: ".");
2565 }
2566
2567 if(p)
2568 return gs_InvalidVersion;
2569
2570 return std::make_tuple(args&: aVersion[0], args&: aVersion[1], args&: aVersion[2]);
2571}
2572
2573void CClient::LoadDDNetInfo()
2574{
2575 const json_value *pDDNetInfo = m_ServerBrowser.LoadDDNetInfo();
2576
2577 if(!pDDNetInfo)
2578 {
2579 m_InfoState = EInfoState::ERROR;
2580 return;
2581 }
2582
2583 const json_value &DDNetInfo = *pDDNetInfo;
2584 const json_value &CurrentVersion = DDNetInfo["version"];
2585 if(CurrentVersion.type == json_string)
2586 {
2587 char aNewVersionStr[64];
2588 str_copy(dst&: aNewVersionStr, src: CurrentVersion);
2589 char aCurVersionStr[64];
2590 str_copy(dst&: aCurVersionStr, GAME_RELEASE_VERSION);
2591 if(ToVersion(pStr: aNewVersionStr) > ToVersion(pStr: aCurVersionStr))
2592 {
2593 str_copy(dst&: m_aVersionStr, src: CurrentVersion);
2594 }
2595 else
2596 {
2597 m_aVersionStr[0] = '0';
2598 m_aVersionStr[1] = '\0';
2599 }
2600 }
2601
2602 const json_value &News = DDNetInfo["news"];
2603 if(News.type == json_string)
2604 {
2605 // Only mark news button if something new was added to the news
2606 if(m_aNews[0] && str_find(haystack: m_aNews, needle: News) == nullptr)
2607 g_Config.m_UiUnreadNews = true;
2608
2609 str_copy(dst&: m_aNews, src: News);
2610 }
2611
2612 const json_value &MapDownloadUrl = DDNetInfo["map-download-url"];
2613 if(MapDownloadUrl.type == json_string)
2614 {
2615 str_copy(dst&: m_aMapDownloadUrl, src: MapDownloadUrl);
2616 }
2617
2618 const json_value &Points = DDNetInfo["points"];
2619 if(Points.type == json_integer)
2620 {
2621 m_Points = Points.u.integer;
2622 }
2623
2624 const json_value &StunServersIpv6 = DDNetInfo["stun-servers-ipv6"];
2625 if(StunServersIpv6.type == json_array && StunServersIpv6[0].type == json_string)
2626 {
2627 NETADDR Addr;
2628 if(!net_addr_from_str(addr: &Addr, string: StunServersIpv6[0]))
2629 {
2630 m_aNetClient[CONN_MAIN].FeedStunServer(StunServer: Addr);
2631 }
2632 }
2633 const json_value &StunServersIpv4 = DDNetInfo["stun-servers-ipv4"];
2634 if(StunServersIpv4.type == json_array && StunServersIpv4[0].type == json_string)
2635 {
2636 NETADDR Addr;
2637 if(!net_addr_from_str(addr: &Addr, string: StunServersIpv4[0]))
2638 {
2639 m_aNetClient[CONN_MAIN].FeedStunServer(StunServer: Addr);
2640 }
2641 }
2642 const json_value &ConnectingIp = DDNetInfo["connecting-ip"];
2643 if(ConnectingIp.type == json_string)
2644 {
2645 NETADDR Addr;
2646 if(!net_addr_from_str(addr: &Addr, string: ConnectingIp))
2647 {
2648 m_HaveGlobalTcpAddr = true;
2649 m_GlobalTcpAddr = Addr;
2650 log_debug("info", "got global tcp ip address: %s", (const char *)ConnectingIp);
2651 }
2652 }
2653 const json_value &WarnPngliteIncompatibleImages = DDNetInfo["warn-pnglite-incompatible-images"];
2654 Graphics()->WarnPngliteIncompatibleImages(Warn: WarnPngliteIncompatibleImages.type == json_boolean && (bool)WarnPngliteIncompatibleImages);
2655 m_InfoState = EInfoState::SUCCESS;
2656}
2657
2658int CClient::ConnectNetTypes() const
2659{
2660 const NETADDR *pConnectAddrs;
2661 int NumConnectAddrs;
2662 m_aNetClient[CONN_MAIN].ConnectAddresses(ppAddrs: &pConnectAddrs, pNumAddrs: &NumConnectAddrs);
2663 int NetType = 0;
2664 for(int i = 0; i < NumConnectAddrs; i++)
2665 {
2666 NetType |= pConnectAddrs[i].type;
2667 }
2668 return NetType;
2669}
2670
2671void CClient::PumpNetwork()
2672{
2673#if defined(CONF_PLATFORM_IOS)
2674 RecreateBrokenSockets();
2675#endif
2676
2677 for(auto &NetClient : m_aNetClient)
2678 {
2679 NetClient.Update();
2680 }
2681
2682 if(State() != IClient::STATE_DEMOPLAYBACK)
2683 {
2684 // check for errors of main and dummy
2685 if(State() != IClient::STATE_OFFLINE && State() < IClient::STATE_QUITTING)
2686 {
2687 if(m_aNetClient[CONN_MAIN].State() == NETSTATE_OFFLINE)
2688 {
2689 // This will also disconnect the dummy, so the branch below is an `else if`
2690 Disconnect();
2691 char aBuf[256];
2692 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "offline error='%s'", m_aNetClient[CONN_MAIN].ErrorString());
2693 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aBuf, PrintColor: CLIENT_NETWORK_PRINT_ERROR_COLOR);
2694 }
2695 else if((DummyConnecting() || DummyConnected()) && m_aNetClient[CONN_DUMMY].State() == NETSTATE_OFFLINE)
2696 {
2697 const bool WasConnecting = DummyConnecting();
2698 DummyDisconnect(pReason: nullptr);
2699 char aBuf[256];
2700 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "offline dummy error='%s'", m_aNetClient[CONN_DUMMY].ErrorString());
2701 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aBuf, PrintColor: CLIENT_NETWORK_PRINT_ERROR_COLOR);
2702 if(WasConnecting)
2703 {
2704 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s: %s", Localize(pStr: "Could not connect dummy"), m_aNetClient[CONN_DUMMY].ErrorString());
2705 GameClient()->Echo(pString: aBuf);
2706 }
2707 }
2708 }
2709
2710 // check if main was connected
2711 if(State() == IClient::STATE_CONNECTING && m_aNetClient[CONN_MAIN].State() == NETSTATE_ONLINE)
2712 {
2713 // we switched to online
2714 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: "connected, sending info", PrintColor: CLIENT_NETWORK_PRINT_COLOR);
2715 SetState(IClient::STATE_LOADING);
2716 SetLoadingStateDetail(IClient::ELoadingStateDetail::INITIAL);
2717 SendInfo(Conn: CONN_MAIN);
2718 }
2719
2720 // progress on dummy connect when the connection is online
2721 if(m_DummySendConnInfo && m_aNetClient[CONN_DUMMY].State() == NETSTATE_ONLINE)
2722 {
2723 m_DummySendConnInfo = false;
2724 SendInfo(Conn: CONN_DUMMY);
2725 m_aNetClient[CONN_DUMMY].Update();
2726 SendReady(Conn: CONN_DUMMY);
2727 GameClient()->SendDummyInfo(Start: true);
2728 SendEnterGame(Conn: CONN_DUMMY);
2729 }
2730 }
2731
2732 // process packets
2733 CNetChunk Packet;
2734 SECURITY_TOKEN ResponseToken;
2735 for(int Conn = 0; Conn < NUM_CONNS; Conn++)
2736 {
2737 while(m_aNetClient[Conn].Recv(pChunk: &Packet, pResponseToken: &ResponseToken, Sixup: IsSixup()))
2738 {
2739 if(Packet.m_ClientId == -1)
2740 {
2741 if(ResponseToken != NET_SECURITY_TOKEN_UNKNOWN && !PreprocessConnlessPacket7(pPacket: &Packet))
2742 continue;
2743
2744 ProcessConnlessPacket(pPacket: &Packet);
2745 continue;
2746 }
2747 if(Conn == CONN_MAIN || Conn == CONN_DUMMY)
2748 {
2749 ProcessServerPacket(pPacket: &Packet, Conn, Dummy: g_Config.m_ClDummy ^ Conn);
2750 }
2751 }
2752 }
2753}
2754
2755void CClient::OnDemoPlayerSnapshot(void *pData, int Size)
2756{
2757 // update ticks, they could have changed
2758 const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info();
2759 m_aCurGameTick[0] = pInfo->m_Info.m_CurrentTick;
2760 m_aPrevGameTick[0] = pInfo->m_PreviousTick;
2761
2762 // create a verified and unpacked snapshot
2763 CSnapshotBuffer AltSnapBuffer;
2764 int AltSnapSize;
2765
2766 if(IsSixup())
2767 {
2768 AltSnapSize = GameClient()->TranslateSnap(pSnapDstSix: &AltSnapBuffer, pSnapSrcSeven: (CSnapshot *)pData, Conn: CONN_MAIN, Dummy: false);
2769 if(AltSnapSize < 0)
2770 {
2771 dbg_msg(sys: "sixup", fmt: "failed to translate snapshot. error=%d", AltSnapSize);
2772 return;
2773 }
2774 }
2775 else
2776 {
2777 AltSnapSize = UnpackAndValidateSnapshot(pFrom: (CSnapshot *)pData, pTo: &AltSnapBuffer);
2778 if(AltSnapSize < 0)
2779 {
2780 dbg_msg(sys: "client", fmt: "unpack snapshot and validate failed. error=%d", AltSnapSize);
2781 return;
2782 }
2783 }
2784
2785 // handle snapshots after validation
2786 std::swap(a&: m_aapSnapshots[0][SNAP_PREV], b&: m_aapSnapshots[0][SNAP_CURRENT]);
2787 mem_copy(dest: m_aapSnapshots[0][SNAP_CURRENT]->m_pSnap, source: pData, size: Size);
2788 mem_copy(dest: m_aapSnapshots[0][SNAP_CURRENT]->m_pAltSnap, source: &AltSnapBuffer, size: AltSnapSize);
2789
2790 GameClient()->OnNewSnapshot(DummySwapped: false);
2791}
2792
2793void CClient::OnDemoPlayerMessage(void *pData, int Size)
2794{
2795 CUnpacker Unpacker;
2796 Unpacker.Reset(pData, Size);
2797 CMsgPacker Packer(NETMSG_EX, true);
2798
2799 // unpack msgid and system flag
2800 int Msg;
2801 bool Sys;
2802
2803 int Result = UnpackMessageId(pId: &Msg, pSys: &Sys, pUnpacker: &Unpacker, pPacker: &Packer);
2804 if(Result == UNPACKMESSAGE_ERROR)
2805 {
2806 return;
2807 }
2808
2809 if(!Sys)
2810 GameClient()->OnMessage(MsgId: Msg, pUnpacker: &Unpacker, Conn: CONN_MAIN, Dummy: false);
2811}
2812
2813void CClient::UpdateDemoIntraTimers()
2814{
2815 // update timers
2816 const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info();
2817 m_aCurGameTick[0] = pInfo->m_Info.m_CurrentTick;
2818 m_aPrevGameTick[0] = pInfo->m_PreviousTick;
2819 m_aGameIntraTick[0] = pInfo->m_IntraTick;
2820 m_aGameTickTime[0] = pInfo->m_TickTime;
2821 m_aGameIntraTickSincePrev[0] = pInfo->m_IntraTickSincePrev;
2822}
2823
2824void CClient::Update()
2825{
2826 PumpNetwork();
2827
2828 // update editor/gameclient, before input snapping
2829 if(m_EditorActive)
2830 m_pEditor->OnUpdate();
2831 else
2832 GameClient()->OnUpdate();
2833
2834 if(State() == IClient::STATE_DEMOPLAYBACK)
2835 {
2836 if(m_DemoPlayer.IsPlaying())
2837 {
2838#if defined(CONF_VIDEORECORDER)
2839 if(IVideo::Current())
2840 {
2841 IVideo::Current()->NextVideoFrame();
2842 IVideo::Current()->NextAudioFrameTimeline(Mix: [this](short *pFinalOut, unsigned Frames) {
2843 Sound()->Mix(pFinalOut, Frames);
2844 });
2845 }
2846#endif
2847
2848 m_DemoPlayer.Update();
2849
2850 // update timers
2851 const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info();
2852 m_aCurGameTick[0] = pInfo->m_Info.m_CurrentTick;
2853 m_aPrevGameTick[0] = pInfo->m_PreviousTick;
2854 m_aGameIntraTick[0] = pInfo->m_IntraTick;
2855 m_aGameTickTime[0] = pInfo->m_TickTime;
2856 }
2857 else
2858 {
2859 // Disconnect when demo playback stopped, either due to playback error
2860 // or because the end of the demo was reached when rendering it.
2861 DisconnectWithReason(pReason: m_DemoPlayer.ErrorMessage());
2862 if(m_DemoPlayer.ErrorMessage()[0] != '\0')
2863 {
2864 SWarning Warning(Localize(pStr: "Error playing demo"), m_DemoPlayer.ErrorMessage());
2865 Warning.m_AutoHide = false;
2866 AddWarning(Warning);
2867 }
2868 }
2869 }
2870 else if(State() == IClient::STATE_ONLINE)
2871 {
2872 if(m_LastDummy != (bool)g_Config.m_ClDummy)
2873 {
2874 // Invalidate references to !m_ClDummy snapshots
2875 GameClient()->InvalidateSnapshot();
2876 GameClient()->OnDummySwap();
2877 }
2878
2879 if(m_aapSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT])
2880 {
2881 // switch dummy snapshot
2882 int64_t Now = m_aGameTime[!g_Config.m_ClDummy].Get(Now: time_get());
2883 while(true)
2884 {
2885 if(!m_aapSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_pNext)
2886 break;
2887 int64_t TickStart = m_aapSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick * time_freq() / GameTickSpeed();
2888 if(TickStart >= Now)
2889 break;
2890
2891 m_aapSnapshots[!g_Config.m_ClDummy][SNAP_PREV] = m_aapSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT];
2892 m_aapSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT] = m_aapSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_pNext;
2893
2894 // set ticks
2895 m_aCurGameTick[!g_Config.m_ClDummy] = m_aapSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick;
2896 m_aPrevGameTick[!g_Config.m_ClDummy] = m_aapSnapshots[!g_Config.m_ClDummy][SNAP_PREV]->m_Tick;
2897 }
2898 }
2899
2900 if(m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT])
2901 {
2902 // switch snapshot
2903 bool Repredict = false;
2904 int64_t Now = m_aGameTime[g_Config.m_ClDummy].Get(Now: time_get());
2905 int64_t PredNow = m_PredictedTime.Get(Now: time_get());
2906
2907 if(m_LastDummy != (bool)g_Config.m_ClDummy && m_aapSnapshots[g_Config.m_ClDummy][SNAP_PREV])
2908 {
2909 // Load snapshot for m_ClDummy
2910 GameClient()->OnNewSnapshot(DummySwapped: true);
2911 Repredict = true;
2912 }
2913
2914 while(true)
2915 {
2916 if(!m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_pNext)
2917 break;
2918 int64_t TickStart = m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick * time_freq() / GameTickSpeed();
2919 if(TickStart >= Now)
2920 break;
2921
2922 m_aapSnapshots[g_Config.m_ClDummy][SNAP_PREV] = m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT];
2923 m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] = m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_pNext;
2924
2925 // set ticks
2926 m_aCurGameTick[g_Config.m_ClDummy] = m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick;
2927 m_aPrevGameTick[g_Config.m_ClDummy] = m_aapSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick;
2928
2929 GameClient()->OnNewSnapshot(DummySwapped: false);
2930 Repredict = true;
2931 }
2932
2933 if(m_aapSnapshots[g_Config.m_ClDummy][SNAP_PREV])
2934 {
2935 int64_t CurTickStart = m_aapSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick * time_freq() / GameTickSpeed();
2936 int64_t PrevTickStart = m_aapSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick * time_freq() / GameTickSpeed();
2937 int PrevPredTick = (int)(PredNow * GameTickSpeed() / time_freq());
2938 int NewPredTick = PrevPredTick + 1;
2939
2940 m_aGameIntraTick[g_Config.m_ClDummy] = (Now - PrevTickStart) / (float)(CurTickStart - PrevTickStart);
2941 m_aGameTickTime[g_Config.m_ClDummy] = (Now - PrevTickStart) / (float)time_freq();
2942 m_aGameIntraTickSincePrev[g_Config.m_ClDummy] = (Now - PrevTickStart) / (float)(time_freq() / GameTickSpeed());
2943
2944 int64_t CurPredTickStart = NewPredTick * time_freq() / GameTickSpeed();
2945 int64_t PrevPredTickStart = PrevPredTick * time_freq() / GameTickSpeed();
2946 m_aPredIntraTick[g_Config.m_ClDummy] = (PredNow - PrevPredTickStart) / (float)(CurPredTickStart - PrevPredTickStart);
2947
2948 if(absolute(a: NewPredTick - m_aapSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick) > MaxLatencyTicks())
2949 {
2950 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client", pStr: "prediction time reset!");
2951 m_PredictedTime.Init(Target: CurTickStart + 2 * time_freq() / GameTickSpeed());
2952 }
2953
2954 if(NewPredTick > m_aPredTick[g_Config.m_ClDummy])
2955 {
2956 m_aPredTick[g_Config.m_ClDummy] = NewPredTick;
2957 Repredict = true;
2958
2959 // send input
2960 SendInput();
2961 }
2962 }
2963
2964 // only do sane predictions
2965 if(Repredict)
2966 {
2967 if(m_aPredTick[g_Config.m_ClDummy] > m_aCurGameTick[g_Config.m_ClDummy] && m_aPredTick[g_Config.m_ClDummy] < m_aCurGameTick[g_Config.m_ClDummy] + MaxLatencyTicks())
2968 GameClient()->OnPredict();
2969 }
2970
2971 // fetch server info if we don't have it
2972 if(m_CurrentServerInfoRequestTime >= 0 &&
2973 time_get() > m_CurrentServerInfoRequestTime)
2974 {
2975 m_ServerBrowser.RequestCurrentServer(Addr: ServerAddress());
2976 m_CurrentServerInfoRequestTime = time_get() + time_freq() * 2;
2977 }
2978
2979 // periodically ping server
2980 if(m_CurrentServerNextPingTime >= 0 &&
2981 time_get() > m_CurrentServerNextPingTime)
2982 {
2983 int64_t NowPing = time_get();
2984 int64_t Freq = time_freq();
2985
2986 char aBuf[64];
2987 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "pinging current server%s", !m_ServerCapabilities.m_PingEx ? ", using fallback via server info" : "");
2988 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "client", pStr: aBuf);
2989
2990 m_CurrentServerPingUuid = RandomUuid();
2991 if(!m_ServerCapabilities.m_PingEx)
2992 {
2993 m_ServerBrowser.RequestCurrentServerWithRandomToken(Addr: ServerAddress(), pBasicToken: &m_CurrentServerPingBasicToken, pToken: &m_CurrentServerPingToken);
2994 }
2995 else
2996 {
2997 CMsgPacker Msg(NETMSG_PINGEX, true);
2998 Msg.AddRaw(pData: &m_CurrentServerPingUuid, Size: sizeof(m_CurrentServerPingUuid));
2999 SendMsg(Conn: CONN_MAIN, pMsg: &Msg, Flags: MSGFLAG_FLUSH);
3000 }
3001 m_CurrentServerCurrentPingTime = NowPing;
3002 m_CurrentServerNextPingTime = NowPing + 600 * Freq; // ping every 10 minutes
3003 }
3004 }
3005
3006 if(m_DummyDeactivateOnReconnect && g_Config.m_ClDummy == 1)
3007 {
3008 m_DummyDeactivateOnReconnect = false;
3009 g_Config.m_ClDummy = 0;
3010 }
3011 else if(!m_DummyConnected && !m_DummyConnecting && m_DummyDeactivateOnReconnect)
3012 {
3013 m_DummyDeactivateOnReconnect = false;
3014 }
3015
3016 m_LastDummy = (bool)g_Config.m_ClDummy;
3017 }
3018
3019 // STRESS TEST: join the server again
3020 if(g_Config.m_DbgStress)
3021 {
3022 static int64_t s_ActionTaken = 0;
3023 int64_t Now = time_get();
3024 if(State() == IClient::STATE_OFFLINE)
3025 {
3026 if(Now > s_ActionTaken + time_freq() * 2)
3027 {
3028 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "stress", pStr: "reconnecting!");
3029 Connect(pAddress: g_Config.m_DbgStressServer);
3030 s_ActionTaken = Now;
3031 }
3032 }
3033 else
3034 {
3035 if(Now > s_ActionTaken + time_freq() * (10 + g_Config.m_DbgStress))
3036 {
3037 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "stress", pStr: "disconnecting!");
3038 Disconnect();
3039 s_ActionTaken = Now;
3040 }
3041 }
3042 }
3043
3044 if(m_pMapdownloadTask)
3045 {
3046 if(m_pMapdownloadTask->State() == EHttpState::DONE)
3047 {
3048 FinishMapDownload();
3049 }
3050 else if(m_pMapdownloadTask->State() == EHttpState::ERROR || m_pMapdownloadTask->State() == EHttpState::ABORTED)
3051 {
3052 dbg_msg(sys: "webdl", fmt: "http failed, falling back to gameserver");
3053 ResetMapDownload(ResetActive: false);
3054 SendMapRequest();
3055 }
3056 }
3057
3058 if(m_pDDNetInfoTask)
3059 {
3060 if(m_pDDNetInfoTask->State() == EHttpState::DONE)
3061 {
3062 if(m_ServerBrowser.DDNetInfoSha256() == m_pDDNetInfoTask->ResultSha256())
3063 {
3064 log_debug("client/info", "DDNet info already up-to-date");
3065 m_InfoState = EInfoState::SUCCESS;
3066 }
3067 else
3068 {
3069 log_debug("client/info", "Loading new DDNet info");
3070 LoadDDNetInfo();
3071 }
3072
3073 ResetDDNetInfoTask();
3074 }
3075 else if(m_pDDNetInfoTask->State() == EHttpState::ERROR || m_pDDNetInfoTask->State() == EHttpState::ABORTED)
3076 {
3077 ResetDDNetInfoTask();
3078 m_InfoState = EInfoState::ERROR;
3079 }
3080 }
3081
3082 if(State() == IClient::STATE_ONLINE)
3083 {
3084 if(!m_EditJobs.empty())
3085 {
3086 std::shared_ptr<CDemoEdit> pJob = m_EditJobs.front();
3087 if(pJob->State() == IJob::STATE_DONE)
3088 {
3089 char aBuf[IO_MAX_PATH_LENGTH + 64];
3090 if(pJob->Success())
3091 {
3092 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Successfully saved the replay to '%s'!", pJob->Destination());
3093 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: aBuf);
3094
3095 GameClient()->Echo(pString: Localize(pStr: "Successfully saved the replay!"));
3096 }
3097 else
3098 {
3099 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Failed saving the replay to '%s'...", pJob->Destination());
3100 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: aBuf);
3101
3102 GameClient()->Echo(pString: Localize(pStr: "Failed saving the replay!"));
3103 }
3104 m_EditJobs.pop_front();
3105 }
3106 }
3107 }
3108
3109 // update the server browser
3110 m_ServerBrowser.Update();
3111
3112 Discord()->Update();
3113 Steam()->Update();
3114 if(Steam()->GetConnectAddress())
3115 {
3116 HandleConnectAddress(pAddr: Steam()->GetConnectAddress());
3117 Steam()->ClearConnectAddress();
3118 }
3119
3120 if(m_ReconnectTime > 0 && time_get() > m_ReconnectTime)
3121 {
3122 if(State() != STATE_ONLINE)
3123 Connect(pAddress: m_aConnectAddressStr);
3124 m_ReconnectTime = 0;
3125 }
3126
3127 m_PredictedTime.UpdateMargin(Margin: PredictionMargin() * time_freq() / 1000);
3128}
3129
3130void CClient::RegisterInterfaces()
3131{
3132 Kernel()->RegisterInterface(pInterface: static_cast<IDemoPlayer *>(&m_DemoPlayer), Destroy: false);
3133 Kernel()->RegisterInterface(pInterface: static_cast<IGhostRecorder *>(&m_GhostRecorder), Destroy: false);
3134 Kernel()->RegisterInterface(pInterface: static_cast<IGhostLoader *>(&m_GhostLoader), Destroy: false);
3135 Kernel()->RegisterInterface(pInterface: static_cast<IServerBrowser *>(&m_ServerBrowser), Destroy: false);
3136#if defined(CONF_AUTOUPDATE)
3137 Kernel()->RegisterInterface(pInterface: static_cast<IUpdater *>(&m_Updater), Destroy: false);
3138#endif
3139 Kernel()->RegisterInterface(pInterface: static_cast<IFriends *>(&m_Friends), Destroy: false);
3140 Kernel()->ReregisterInterface(pInterface: static_cast<IFriends *>(&m_Foes));
3141}
3142
3143void CClient::InitInterfaces()
3144{
3145 // fetch interfaces
3146 m_pEngine = Kernel()->RequestInterface<IEngine>();
3147 m_pEditor = Kernel()->RequestInterface<IEditor>();
3148 m_pFavorites = Kernel()->RequestInterface<IFavorites>();
3149 m_pSound = Kernel()->RequestInterface<IEngineSound>();
3150 m_pGameClient = Kernel()->RequestInterface<IGameClient>();
3151 m_pHttp = Kernel()->RequestInterface<IEngineHttp>();
3152 m_pInput = Kernel()->RequestInterface<IEngineInput>();
3153 m_pConfigManager = Kernel()->RequestInterface<IConfigManager>();
3154 m_pConfig = m_pConfigManager->Values();
3155#if defined(CONF_AUTOUPDATE)
3156 m_pUpdater = Kernel()->RequestInterface<IUpdater>();
3157#endif
3158 m_pDiscord = Kernel()->RequestInterface<IDiscord>();
3159 m_pSteam = Kernel()->RequestInterface<ISteam>();
3160 m_pNotifications = Kernel()->RequestInterface<INotifications>();
3161 m_pStorage = Kernel()->RequestInterface<IStorage>();
3162
3163 m_DemoEditor.Init(pSnapshotDelta: &m_SnapshotDelta, pSnapshotDeltaSixup: &m_SnapshotDeltaSixup, pStorage: m_pStorage);
3164
3165 m_ServerBrowser.SetBaseInfo(pClient: &m_aNetClient[CONN_CONTACT], pNetVersion: m_pGameClient->NetVersion());
3166
3167#if defined(CONF_AUTOUPDATE)
3168 m_Updater.Init();
3169#endif
3170
3171 m_pConfigManager->RegisterCallback(pfnFunc: IFavorites::ConfigSaveCallback, pUserData: m_pFavorites);
3172 m_Friends.Init();
3173 m_Foes.Init(Foes: true);
3174
3175 m_GhostRecorder.Init();
3176 m_GhostLoader.Init();
3177}
3178
3179void CClient::Run()
3180{
3181 m_LocalStartTime = m_GlobalStartTime = time_get();
3182 m_aSnapshotParts[0] = 0;
3183 m_aSnapshotParts[1] = 0;
3184
3185 if(m_GenerateTimeoutSeed)
3186 {
3187 GenerateTimeoutSeed();
3188 }
3189
3190 unsigned int Seed;
3191 secure_random_fill(bytes: &Seed, length: sizeof(Seed));
3192 srand(seed: Seed);
3193
3194 if(g_Config.m_Debug)
3195 {
3196 g_UuidManager.DebugDump();
3197 }
3198
3199 char aNetworkError[256];
3200 if(!InitNetworkClient(pError: aNetworkError, ErrorSize: sizeof(aNetworkError)))
3201 {
3202 log_error("client", "%s", aNetworkError);
3203 ShowMessageBox(MessageBox: {.m_pTitle = "Network Error", .m_pMessage = aNetworkError});
3204 return;
3205 }
3206
3207 if(!m_pHttp->Init(ShutdownDelay: std::chrono::seconds{1}))
3208 {
3209 const char *pErrorMessage = "Failed to initialize the HTTP client.";
3210 log_error("client", "%s", pErrorMessage);
3211 ShowMessageBox(MessageBox: {.m_pTitle = "HTTP Error", .m_pMessage = pErrorMessage});
3212 return;
3213 }
3214
3215 // init graphics
3216 m_pGraphics = CreateEngineGraphicsThreaded();
3217 Kernel()->RegisterInterface(pInterface: m_pGraphics); // IEngineGraphics
3218 Kernel()->RegisterInterface(pInterface: static_cast<IGraphics *>(m_pGraphics), Destroy: false);
3219 {
3220 CMemoryLogger MemoryLogger;
3221 MemoryLogger.SetParent(log_get_scope_logger());
3222 bool Success;
3223 {
3224 CLogScope LogScope(&MemoryLogger);
3225 Success = m_pGraphics->Init() == 0;
3226 }
3227 if(!Success)
3228 {
3229 log_error("client", "Failed to initialize the graphics (see details above)");
3230 const std::string Message = std::string(
3231 "Failed to initialize the graphics. See details below.\n\n"
3232 "For detailed troubleshooting instructions please read our Wiki:\n"
3233 "https://wiki.ddnet.org/wiki/GFX_Troubleshooting\n\n") +
3234 MemoryLogger.ConcatenatedLines();
3235 const std::vector<IGraphics::CMessageBoxButton> vButtons = {
3236 {.m_pLabel = "Show Wiki"},
3237 {.m_pLabel = "OK", .m_Confirm = true, .m_Cancel = true},
3238 };
3239 const std::optional<int> MessageResult = ShowMessageBox(MessageBox: {.m_pTitle = "Graphics Initialization Error", .m_pMessage = Message.c_str(), .m_vButtons = vButtons});
3240 if(MessageResult && *MessageResult == 0)
3241 {
3242 ViewLink(pLink: "https://wiki.ddnet.org/wiki/GFX_Troubleshooting");
3243 }
3244 return;
3245 }
3246 }
3247
3248 // make sure the first frame just clears everything to prevent undesired colors when waiting for io
3249 Graphics()->Clear(r: 0, g: 0, b: 0);
3250 Graphics()->Swap();
3251
3252 // init localization first, making sure all errors during init can be localized
3253 GameClient()->InitializeLanguage();
3254
3255 // init sound, allowed to fail
3256 const bool SoundInitFailed = Sound()->Init() != 0;
3257
3258#if defined(CONF_VIDEORECORDER)
3259 // init video recorder aka ffmpeg
3260 CVideo::Init();
3261#endif
3262
3263 // init text render
3264 m_pTextRender = Kernel()->RequestInterface<IEngineTextRender>();
3265 m_pTextRender->Init();
3266
3267 // init the input
3268 Input()->Init();
3269
3270 // init the editor
3271 m_pEditor->Init();
3272
3273 m_ServerBrowser.OnInit();
3274 // loads the existing ddnet info file if it exists
3275 LoadDDNetInfo();
3276
3277 LoadDebugFont();
3278
3279 if(Steam()->GetPlayerName())
3280 {
3281 str_copy(dst&: g_Config.m_SteamName, src: Steam()->GetPlayerName());
3282 }
3283
3284 Graphics()->AddWindowResizeListener(pFunc: [this] { OnWindowResize(); });
3285
3286 GameClient()->OnInit();
3287
3288 m_Fifo.Init(pConsole: m_pConsole, pFifoFile: g_Config.m_ClInputFifo, Flag: CFGFLAG_CLIENT);
3289
3290 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: "version " GAME_RELEASE_VERSION " on " CONF_PLATFORM_STRING " " CONF_ARCH_STRING, PrintColor: ColorRGBA(0.7f, 0.7f, 1.0f, 1.0f));
3291 if(GIT_SHORTREV_HASH)
3292 {
3293 char aBuf[64];
3294 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "git revision hash: %s", GIT_SHORTREV_HASH);
3295 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aBuf, PrintColor: ColorRGBA(0.7f, 0.7f, 1.0f, 1.0f));
3296 }
3297
3298 //
3299 m_FpsGraph.Init(Min: 0.0f, Max: 120.0f);
3300
3301 // never start with the editor
3302 g_Config.m_ClEditor = 0;
3303
3304 // process pending commands
3305 m_pConsole->StoreCommands(Store: false);
3306
3307 InitChecksum();
3308 m_pConsole->InitChecksum(pData: ChecksumData());
3309
3310 // request the new ddnet info from server if already past the welcome dialog
3311 if(g_Config.m_ClShowWelcome)
3312 g_Config.m_ClShowWelcome = 0;
3313 else
3314 RequestDDNetInfo();
3315
3316 if(SoundInitFailed)
3317 {
3318 SWarning Warning(Localize(pStr: "Sound error"), Localize(pStr: "The audio device couldn't be initialised."));
3319 Warning.m_AutoHide = false;
3320 AddWarning(Warning);
3321 }
3322
3323 bool LastD = false;
3324 bool LastE = false;
3325 bool LastG = false;
3326
3327 int64_t NextUpdateTime = time_get();
3328 int64_t NextRenderTime = time_get();
3329
3330 while(true)
3331 {
3332 set_new_tick();
3333
3334 // handle pending connects
3335 if(m_aCmdConnect[0])
3336 {
3337 str_copy(dst&: g_Config.m_UiServerAddress, src: m_aCmdConnect);
3338 Connect(pAddress: m_aCmdConnect);
3339 m_aCmdConnect[0] = 0;
3340 }
3341
3342 // handle pending demo play
3343 if(m_aCmdPlayDemo[0])
3344 {
3345 const char *pError = DemoPlayer_Play(pFilename: m_aCmdPlayDemo, StorageType: IStorage::TYPE_ALL_OR_ABSOLUTE);
3346 if(pError)
3347 log_error("demo_player", "playing passed demo file '%s' failed: %s", m_aCmdPlayDemo, pError);
3348 m_aCmdPlayDemo[0] = 0;
3349 }
3350
3351 // handle pending map edits
3352 if(m_aCmdEditMap[0])
3353 {
3354 int Result = m_pEditor->HandleMapDrop(pFilename: m_aCmdEditMap, StorageType: IStorage::TYPE_ALL_OR_ABSOLUTE);
3355 if(Result)
3356 g_Config.m_ClEditor = true;
3357 else
3358 log_error("editor", "editing passed map file '%s' failed", m_aCmdEditMap);
3359 m_aCmdEditMap[0] = 0;
3360 }
3361
3362 // update input
3363 if(Input()->Update())
3364 {
3365 if(State() == IClient::STATE_QUITTING)
3366 break;
3367 else
3368 SetState(IClient::STATE_QUITTING); // SDL_QUIT
3369 }
3370
3371 char aFile[IO_MAX_PATH_LENGTH];
3372 if(Input()->GetDropFile(aBuf: aFile, Len: sizeof(aFile)))
3373 {
3374 if(str_startswith(str: aFile, CONNECTLINK_NO_SLASH))
3375 HandleConnectLink(pLink: aFile);
3376 else if(str_endswith(str: aFile, suffix: ".demo"))
3377 HandleDemoPath(pPath: aFile);
3378 else if(str_endswith(str: aFile, suffix: ".map"))
3379 HandleMapPath(pPath: aFile);
3380 }
3381
3382#if defined(CONF_AUTOUPDATE)
3383 Updater()->Update();
3384#endif
3385
3386 // update sound
3387 Sound()->Update();
3388
3389 if(CtrlShiftKey(Key: KEY_D, Last&: LastD))
3390 g_Config.m_Debug ^= 1;
3391
3392 if(CtrlShiftKey(Key: KEY_G, Last&: LastG))
3393 g_Config.m_DbgGraphs ^= 1;
3394
3395 if(CtrlShiftKey(Key: KEY_E, Last&: LastE))
3396 {
3397 if(g_Config.m_ClEditor)
3398 m_pEditor->OnClose();
3399 g_Config.m_ClEditor = g_Config.m_ClEditor ^ 1;
3400 }
3401
3402 bool Inactive = false;
3403 int64_t WakeTime = std::numeric_limits<int64_t>::max();
3404
3405 // render
3406 {
3407 if(g_Config.m_ClEditor)
3408 {
3409 if(!m_EditorActive)
3410 {
3411 Input()->MouseModeRelative();
3412 GameClient()->OnActivateEditor();
3413 m_pEditor->OnActivate();
3414 m_EditorActive = true;
3415 }
3416 }
3417 else if(m_EditorActive)
3418 {
3419 m_EditorActive = false;
3420 }
3421
3422 Update();
3423 int64_t Now = time_get();
3424
3425 bool IsRenderActive = (g_Config.m_GfxBackgroundRender || m_pGraphics->WindowOpen());
3426
3427 bool AsyncRenderOld = g_Config.m_GfxAsyncRenderOld;
3428
3429 // Update at cl_refresh_rate, or at cl_refresh_rate_inactive while the window is inactive.
3430 Inactive = g_Config.m_ClRefreshRateInactive && !m_pGraphics->WindowActive();
3431 const int RefreshRate = Inactive ? g_Config.m_ClRefreshRateInactive : g_Config.m_ClRefreshRate;
3432 bool UpdateDue = true;
3433 if(RefreshRate)
3434 {
3435 UpdateDue = Now >= NextUpdateTime;
3436 if(UpdateDue)
3437 {
3438 // Stay on the grid so that late wakeups do not lower the rate, unless a whole interval was missed.
3439 NextUpdateTime = std::max(a: NextUpdateTime + time_freq() / RefreshRate, b: Now);
3440 }
3441 }
3442
3443 // Render on the updates, unless gfx_refresh_rate is lower.
3444 int GfxRefreshRate = g_Config.m_GfxRefreshRate;
3445 if(RefreshRate && GfxRefreshRate >= RefreshRate)
3446 GfxRefreshRate = 0;
3447
3448#if defined(CONF_VIDEORECORDER)
3449 // keep rendering synced
3450 if(IVideo::Current())
3451 {
3452 AsyncRenderOld = false;
3453 GfxRefreshRate = 0;
3454 }
3455#endif
3456
3457 const bool RenderDue = GfxRefreshRate ? Now >= NextRenderTime : UpdateDue;
3458 if(IsRenderActive &&
3459 (!AsyncRenderOld || m_pGraphics->IsIdle()) &&
3460 RenderDue)
3461 {
3462 // update frametime
3463 m_RenderFrameTime = (Now - m_LastRenderTime) / (float)time_freq();
3464 m_FpsGraph.Add(Value: 1.0f / m_RenderFrameTime);
3465
3466 if(m_BenchmarkFile)
3467 {
3468 char aBuf[64];
3469 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Frametime %d us\n", (int)(m_RenderFrameTime * 1000000));
3470 io_write(io: m_BenchmarkFile, buffer: aBuf, size: str_length(str: aBuf));
3471 if(time_get() > m_BenchmarkStopTime)
3472 {
3473 io_close(io: m_BenchmarkFile);
3474 m_BenchmarkFile = nullptr;
3475 Quit();
3476 }
3477 }
3478
3479 m_FrameTimeAverage = m_FrameTimeAverage * 0.9f + m_RenderFrameTime * 0.1f;
3480
3481 if(GfxRefreshRate)
3482 NextRenderTime = std::max(a: NextRenderTime + time_freq() / GfxRefreshRate, b: Now);
3483 m_LastRenderTime = Now;
3484
3485 Render();
3486 m_pGraphics->Swap();
3487 }
3488
3489 // Wake up for the next update or frame, whichever comes first. While playing, also wake up for
3490 // the next prediction tick to send its input without delay, unless the window is inactive or
3491 // the loop is not rate limited at all.
3492 if(RefreshRate)
3493 {
3494 WakeTime = NextUpdateTime;
3495 if(IsRenderActive && GfxRefreshRate && NextRenderTime > Now)
3496 WakeTime = std::min(a: WakeTime, b: NextRenderTime);
3497 if(State() == IClient::STATE_ONLINE && m_aPredTick[g_Config.m_ClDummy] > 0 && !Inactive)
3498 WakeTime = std::min(a: WakeTime, b: Now + (m_aPredTick[g_Config.m_ClDummy] * time_freq() / GameTickSpeed() - m_PredictedTime.Get(Now)));
3499 }
3500 }
3501
3502 AutoScreenshot_Cleanup();
3503 AutoStatScreenshot_Cleanup();
3504 AutoCSV_Cleanup();
3505
3506 m_Fifo.Update();
3507
3508 if(State() == IClient::STATE_QUITTING || State() == IClient::STATE_RESTARTING)
3509 break;
3510
3511 // beNice
3512 if(WakeTime != std::numeric_limits<int64_t>::max())
3513 {
3514 const std::chrono::nanoseconds Deadline(WakeTime);
3515 std::chrono::nanoseconds WaitTime = Deadline - time_get_nanoseconds();
3516 if(Inactive)
3517 {
3518 // Without focus, save power by not waking up for packets.
3519 std::this_thread::sleep_for(rtime: WaitTime);
3520 }
3521 else
3522 {
3523 // Packets end the wait early. The wait can overshoot by a fraction of its duration, so approach the deadline in halving steps.
3524 while(WaitTime > 0ns && net_socket_read_wait(sock: m_aNetClient[CONN_MAIN].m_Socket, nanoseconds: WaitTime > 1000us ? WaitTime / 2 : 0ns) == 0)
3525 {
3526 WaitTime = Deadline - time_get_nanoseconds();
3527 }
3528 }
3529 }
3530
3531 // update local and global time
3532 m_LocalTime = (time_get() - m_LocalStartTime) / (float)time_freq();
3533 m_GlobalTime = (time_get() - m_GlobalStartTime) / (float)time_freq();
3534 }
3535
3536 GameClient()->RenderShutdownMessage();
3537 Disconnect();
3538
3539 if(!m_pConfigManager->Save())
3540 {
3541 char aError[128];
3542 str_format(buffer: aError, buffer_size: sizeof(aError), format: Localize(pStr: "Saving settings to '%s' failed"), CONFIG_FILE);
3543 m_vQuittingWarnings.emplace_back(args: Localize(pStr: "Error saving settings"), args&: aError);
3544 }
3545
3546 m_ServerBrowser.Shutdown();
3547 m_Fifo.Shutdown();
3548 m_pHttp->Shutdown();
3549 Engine()->ShutdownJobs();
3550
3551 GameClient()->RenderShutdownMessage();
3552 GameClient()->OnShutdown();
3553 delete m_pEditor;
3554
3555 // close sockets
3556 for(unsigned int i = 0; i < std::size(m_aNetClient); i++)
3557 m_aNetClient[i].Close();
3558
3559 // shutdown text render while graphics are still available
3560 m_pTextRender->Shutdown();
3561}
3562
3563bool CClient::InitNetworkClient(char *pError, size_t ErrorSize)
3564{
3565 NETADDR BindAddr;
3566 if(g_Config.m_Bindaddr[0] == '\0')
3567 {
3568 mem_zero(block: &BindAddr, size: sizeof(BindAddr));
3569 }
3570 else if(net_host_lookup(hostname: g_Config.m_Bindaddr, addr: &BindAddr, types: NETTYPE_ALL) != 0)
3571 {
3572 str_format(buffer: pError, buffer_size: ErrorSize, format: "The configured bindaddr '%s' cannot be resolved.", g_Config.m_Bindaddr);
3573 return false;
3574 }
3575 BindAddr.type = NETTYPE_ALL;
3576 for(size_t i = 0; i < std::size(m_aNetClient); i++)
3577 {
3578 if(!InitNetworkClientImpl(BindAddr, Conn: i, pError, ErrorSize))
3579 {
3580 return false;
3581 }
3582 }
3583 return true;
3584}
3585
3586bool CClient::InitNetworkClientImpl(NETADDR BindAddr, int Conn, char *pError, size_t ErrorSize)
3587{
3588 int *pPort;
3589 const char *pName;
3590 switch(Conn)
3591 {
3592 case CONN_MAIN:
3593 pPort = &g_Config.m_ClPort;
3594 pName = "main";
3595 break;
3596 case CONN_DUMMY:
3597 pPort = &g_Config.m_ClDummyPort;
3598 pName = "dummy";
3599 break;
3600 case CONN_CONTACT:
3601 pPort = &g_Config.m_ClContactPort;
3602 pName = "contact";
3603 break;
3604 default:
3605 dbg_assert_failed("unreachable");
3606 }
3607 if(m_aNetClient[Conn].State() != NETSTATE_OFFLINE)
3608 {
3609 str_format(buffer: pError, buffer_size: ErrorSize, format: "Could not open network client '%s' while already connected.", pName);
3610 return false;
3611 }
3612 if(*pPort < 1024) // Reject users setting ports that we don't want to use
3613 *pPort = 0;
3614 BindAddr.port = *pPort;
3615
3616 unsigned RemainingAttempts = 25;
3617 while(!m_aNetClient[Conn].Open(BindAddr))
3618 {
3619 --RemainingAttempts;
3620 if(RemainingAttempts == 0)
3621 {
3622 if(g_Config.m_Bindaddr[0])
3623 str_format(buffer: pError, buffer_size: ErrorSize, format: "Could not open network client '%s', try changing or unsetting the bindaddr '%s'.", pName, g_Config.m_Bindaddr);
3624 else
3625 str_format(buffer: pError, buffer_size: ErrorSize, format: "Could not open network client '%s'.", pName);
3626 return false;
3627 }
3628 if(BindAddr.port != 0)
3629 {
3630 log_warn("client", "Could not open network client '%s' with port %d, choosing random port instead.", pName, BindAddr.port);
3631 BindAddr.port = 0;
3632 }
3633 }
3634 return true;
3635}
3636
3637bool CClient::CtrlShiftKey(int Key, bool &Last)
3638{
3639 if(Input()->ModifierIsPressed() && Input()->ShiftIsPressed() && !Last && Input()->KeyIsPressed(Key))
3640 {
3641 Last = true;
3642 return true;
3643 }
3644 else if(Last && !Input()->KeyIsPressed(Key))
3645 {
3646 Last = false;
3647 }
3648
3649 return false;
3650}
3651
3652void CClient::Con_Connect(IConsole::IResult *pResult, void *pUserData)
3653{
3654 CClient *pSelf = (CClient *)pUserData;
3655 pSelf->HandleConnectLink(pLink: pResult->GetString(Index: 0));
3656}
3657
3658void CClient::Con_Disconnect(IConsole::IResult *pResult, void *pUserData)
3659{
3660 CClient *pSelf = (CClient *)pUserData;
3661 pSelf->Disconnect();
3662}
3663
3664void CClient::Con_DummyConnect(IConsole::IResult *pResult, void *pUserData)
3665{
3666 CClient *pSelf = (CClient *)pUserData;
3667 pSelf->DummyConnect();
3668}
3669
3670void CClient::Con_DummyDisconnect(IConsole::IResult *pResult, void *pUserData)
3671{
3672 CClient *pSelf = (CClient *)pUserData;
3673 pSelf->DummyDisconnect(pReason: nullptr);
3674}
3675
3676void CClient::Con_DummyResetInput(IConsole::IResult *pResult, void *pUserData)
3677{
3678 CClient *pSelf = (CClient *)pUserData;
3679 pSelf->GameClient()->DummyResetInput();
3680}
3681
3682void CClient::Con_Quit(IConsole::IResult *pResult, void *pUserData)
3683{
3684 CClient *pSelf = (CClient *)pUserData;
3685 pSelf->Quit();
3686}
3687
3688void CClient::Con_Restart(IConsole::IResult *pResult, void *pUserData)
3689{
3690 CClient *pSelf = (CClient *)pUserData;
3691 pSelf->Restart();
3692}
3693
3694void CClient::Con_Minimize(IConsole::IResult *pResult, void *pUserData)
3695{
3696 CClient *pSelf = (CClient *)pUserData;
3697 pSelf->Graphics()->Minimize();
3698}
3699
3700void CClient::Con_Ping(IConsole::IResult *pResult, void *pUserData)
3701{
3702 CClient *pSelf = (CClient *)pUserData;
3703
3704 CMsgPacker Msg(NETMSG_PING, true);
3705 pSelf->SendMsg(Conn: CONN_MAIN, pMsg: &Msg, Flags: MSGFLAG_FLUSH);
3706 pSelf->m_PingStartTime = time_get();
3707}
3708
3709void CClient::ConNetReset(IConsole::IResult *pResult, void *pUserData)
3710{
3711 CClient *pSelf = (CClient *)pUserData;
3712 if(pSelf->m_LocalStartTime > 0)
3713 {
3714 pSelf->ResetSocket();
3715 }
3716}
3717
3718void CClient::AutoScreenshot_Start()
3719{
3720 if(g_Config.m_ClAutoScreenshot)
3721 {
3722 Graphics()->TakeScreenshot(pFilename: "auto/autoscreen");
3723 m_AutoScreenshotRecycle = true;
3724 }
3725}
3726
3727void CClient::AutoStatScreenshot_Start()
3728{
3729 if(g_Config.m_ClAutoStatboardScreenshot)
3730 {
3731 Graphics()->TakeScreenshot(pFilename: "auto/stats/autoscreen");
3732 m_AutoStatScreenshotRecycle = true;
3733 }
3734}
3735
3736void CClient::AutoScreenshot_Cleanup()
3737{
3738 if(m_AutoScreenshotRecycle)
3739 {
3740 if(g_Config.m_ClAutoScreenshotMax)
3741 {
3742 // clean up auto taken screens
3743 CFileCollection AutoScreens;
3744 AutoScreens.Init(pStorage: Storage(), pPath: "screenshots/auto", pFileDesc: "autoscreen", pFileExt: ".png", MaxEntries: g_Config.m_ClAutoScreenshotMax);
3745 }
3746 m_AutoScreenshotRecycle = false;
3747 }
3748}
3749
3750void CClient::AutoStatScreenshot_Cleanup()
3751{
3752 if(m_AutoStatScreenshotRecycle)
3753 {
3754 if(g_Config.m_ClAutoStatboardScreenshotMax)
3755 {
3756 // clean up auto taken screens
3757 CFileCollection AutoScreens;
3758 AutoScreens.Init(pStorage: Storage(), pPath: "screenshots/auto/stats", pFileDesc: "autoscreen", pFileExt: ".png", MaxEntries: g_Config.m_ClAutoStatboardScreenshotMax);
3759 }
3760 m_AutoStatScreenshotRecycle = false;
3761 }
3762}
3763
3764void CClient::AutoCSV_Start()
3765{
3766 if(g_Config.m_ClAutoCSV)
3767 m_AutoCSVRecycle = true;
3768}
3769
3770void CClient::AutoCSV_Cleanup()
3771{
3772 if(m_AutoCSVRecycle)
3773 {
3774 if(g_Config.m_ClAutoCSVMax)
3775 {
3776 // clean up auto csvs
3777 CFileCollection AutoRecord;
3778 AutoRecord.Init(pStorage: Storage(), pPath: "record/csv", pFileDesc: "autorecord", pFileExt: ".csv", MaxEntries: g_Config.m_ClAutoCSVMax);
3779 }
3780 m_AutoCSVRecycle = false;
3781 }
3782}
3783
3784void CClient::Con_Screenshot(IConsole::IResult *pResult, void *pUserData)
3785{
3786 CClient *pSelf = (CClient *)pUserData;
3787 pSelf->Graphics()->TakeScreenshot(pFilename: nullptr);
3788}
3789
3790#if defined(CONF_VIDEORECORDER)
3791
3792void CClient::Con_StartVideo(IConsole::IResult *pResult, void *pUserData)
3793{
3794 CClient *pSelf = static_cast<CClient *>(pUserData);
3795
3796 if(pResult->NumArguments())
3797 {
3798 pSelf->StartVideo(pFilename: pResult->GetString(Index: 0), WithTimestamp: false);
3799 }
3800 else
3801 {
3802 pSelf->StartVideo(pFilename: "video", WithTimestamp: true);
3803 }
3804}
3805
3806void CClient::StartVideo(const char *pFilename, bool WithTimestamp)
3807{
3808 if(State() != IClient::STATE_DEMOPLAYBACK)
3809 {
3810 log_error("videorecorder", "Video can only be recorded in demo player.");
3811 return;
3812 }
3813
3814 if(IVideo::Current())
3815 {
3816 log_error("videorecorder", "Already recording.");
3817 return;
3818 }
3819
3820 char aFilename[IO_MAX_PATH_LENGTH];
3821 if(WithTimestamp)
3822 {
3823 char aTimestamp[20];
3824 str_timestamp(buffer: aTimestamp, buffer_size: sizeof(aTimestamp));
3825 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "videos/%s_%s.mp4", pFilename, aTimestamp);
3826 }
3827 else
3828 {
3829 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "videos/%s.mp4", pFilename);
3830 }
3831
3832 // wait for idle, so there is no data race
3833 Graphics()->WaitForIdle();
3834 // pause the sound device while creating the video instance
3835 Sound()->PauseAudioDevice();
3836 new CVideo(Graphics(), Sound(), Storage(), Graphics()->ScreenWidth(), Graphics()->ScreenHeight(), m_LocalStartTime, aFilename);
3837 Sound()->UnpauseAudioDevice();
3838 if(!IVideo::Current()->Start())
3839 {
3840 log_error("videorecorder", "Failed to start recording to '%s'", aFilename);
3841 m_DemoPlayer.Stop(pErrorMessage: "Failed to start video recording. See local console for details.");
3842 return;
3843 }
3844 if(m_DemoPlayer.Info()->m_Info.m_Paused)
3845 {
3846 IVideo::Current()->Pause(Pause: true);
3847 }
3848 log_info("videorecorder", "Recording to '%s'", aFilename);
3849}
3850
3851void CClient::Con_StopVideo(IConsole::IResult *pResult, void *pUserData)
3852{
3853 if(!IVideo::Current())
3854 {
3855 log_error("videorecorder", "Not recording.");
3856 return;
3857 }
3858
3859 IVideo::Current()->Stop();
3860 log_info("videorecorder", "Stopped recording.");
3861}
3862
3863#endif
3864
3865void CClient::Con_Rcon(IConsole::IResult *pResult, void *pUserData)
3866{
3867 CClient *pSelf = (CClient *)pUserData;
3868 pSelf->Rcon(pCmd: pResult->GetString(Index: 0));
3869}
3870
3871void CClient::Con_RconAuth(IConsole::IResult *pResult, void *pUserData)
3872{
3873 CClient *pSelf = (CClient *)pUserData;
3874 pSelf->RconAuth(pName: "", pPassword: pResult->GetString(Index: 0));
3875}
3876
3877void CClient::Con_RconLogin(IConsole::IResult *pResult, void *pUserData)
3878{
3879 CClient *pSelf = (CClient *)pUserData;
3880 pSelf->RconAuth(pName: pResult->GetString(Index: 0), pPassword: pResult->GetString(Index: 1));
3881}
3882
3883void CClient::Con_BeginFavoriteGroup(IConsole::IResult *pResult, void *pUserData)
3884{
3885 CClient *pSelf = (CClient *)pUserData;
3886 if(pSelf->m_FavoritesGroup)
3887 {
3888 log_error("client", "opening favorites group while there is already one, discarding old one");
3889 for(int i = 0; i < pSelf->m_FavoritesGroupNum; i++)
3890 {
3891 char aAddr[NETADDR_MAXSTRSIZE];
3892 net_addr_str(addr: &pSelf->m_aFavoritesGroupAddresses[i], string: aAddr, max_length: sizeof(aAddr), add_port: true);
3893 log_warn("client", "discarding %s", aAddr);
3894 }
3895 }
3896 pSelf->m_FavoritesGroup = true;
3897 pSelf->m_FavoritesGroupAllowPing = false;
3898 pSelf->m_FavoritesGroupNum = 0;
3899}
3900
3901void CClient::Con_EndFavoriteGroup(IConsole::IResult *pResult, void *pUserData)
3902{
3903 CClient *pSelf = (CClient *)pUserData;
3904 if(!pSelf->m_FavoritesGroup)
3905 {
3906 log_error("client", "closing favorites group while there is none, ignoring");
3907 return;
3908 }
3909 log_info("client", "adding group of %d favorites", pSelf->m_FavoritesGroupNum);
3910 pSelf->m_pFavorites->Add(pAddrs: pSelf->m_aFavoritesGroupAddresses, NumAddrs: pSelf->m_FavoritesGroupNum);
3911 if(pSelf->m_FavoritesGroupAllowPing)
3912 {
3913 pSelf->m_pFavorites->AllowPing(pAddrs: pSelf->m_aFavoritesGroupAddresses, NumAddrs: pSelf->m_FavoritesGroupNum, AllowPing: true);
3914 }
3915 pSelf->m_FavoritesGroup = false;
3916}
3917
3918void CClient::Con_AddFavorite(IConsole::IResult *pResult, void *pUserData)
3919{
3920 CClient *pSelf = (CClient *)pUserData;
3921 NETADDR Addr;
3922
3923 if(net_addr_from_url(addr: &Addr, string: pResult->GetString(Index: 0), host_buf: nullptr, host_buf_size: 0) != 0 && net_addr_from_str(addr: &Addr, string: pResult->GetString(Index: 0)) != 0)
3924 {
3925 char aBuf[128];
3926 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "invalid address '%s'", pResult->GetString(Index: 0));
3927 pSelf->m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "client", pStr: aBuf);
3928 return;
3929 }
3930 bool AllowPing = pResult->NumArguments() > 1 && str_find(haystack: pResult->GetString(Index: 1), needle: "allow_ping");
3931 char aAddr[NETADDR_MAXSTRSIZE];
3932 net_addr_str(addr: &Addr, string: aAddr, max_length: sizeof(aAddr), add_port: true);
3933 if(pSelf->m_FavoritesGroup)
3934 {
3935 if(pSelf->m_FavoritesGroupNum == (int)std::size(pSelf->m_aFavoritesGroupAddresses))
3936 {
3937 log_error("client", "discarding %s because groups can have at most a size of %d", aAddr, pSelf->m_FavoritesGroupNum);
3938 return;
3939 }
3940 log_info("client", "adding %s to favorites group", aAddr);
3941 pSelf->m_aFavoritesGroupAddresses[pSelf->m_FavoritesGroupNum] = Addr;
3942 pSelf->m_FavoritesGroupAllowPing = pSelf->m_FavoritesGroupAllowPing || AllowPing;
3943 pSelf->m_FavoritesGroupNum += 1;
3944 }
3945 else
3946 {
3947 log_info("client", "adding %s to favorites", aAddr);
3948 pSelf->m_pFavorites->Add(pAddrs: &Addr, NumAddrs: 1);
3949 if(AllowPing)
3950 {
3951 pSelf->m_pFavorites->AllowPing(pAddrs: &Addr, NumAddrs: 1, AllowPing: true);
3952 }
3953 }
3954}
3955
3956void CClient::Con_RemoveFavorite(IConsole::IResult *pResult, void *pUserData)
3957{
3958 CClient *pSelf = (CClient *)pUserData;
3959 NETADDR Addr;
3960 if(net_addr_from_str(addr: &Addr, string: pResult->GetString(Index: 0)) == 0)
3961 pSelf->m_pFavorites->Remove(pAddrs: &Addr, NumAddrs: 1);
3962}
3963
3964void CClient::DemoSliceBegin()
3965{
3966 const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info();
3967 g_Config.m_ClDemoSliceBegin = pInfo->m_Info.m_CurrentTick;
3968}
3969
3970void CClient::DemoSliceEnd()
3971{
3972 const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info();
3973 g_Config.m_ClDemoSliceEnd = pInfo->m_Info.m_CurrentTick;
3974}
3975
3976void CClient::Con_DemoSliceBegin(IConsole::IResult *pResult, void *pUserData)
3977{
3978 CClient *pSelf = (CClient *)pUserData;
3979 pSelf->DemoSliceBegin();
3980}
3981
3982void CClient::Con_DemoSliceEnd(IConsole::IResult *pResult, void *pUserData)
3983{
3984 CClient *pSelf = (CClient *)pUserData;
3985 pSelf->DemoSliceEnd();
3986}
3987
3988void CClient::Con_SaveReplay(IConsole::IResult *pResult, void *pUserData)
3989{
3990 CClient *pSelf = (CClient *)pUserData;
3991 if(pResult->NumArguments())
3992 {
3993 int Length = pResult->GetInteger(Index: 0);
3994 if(Length <= 0)
3995 {
3996 pSelf->m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: "ERROR: length must be greater than 0 second.");
3997 }
3998 else
3999 {
4000 if(pResult->NumArguments() >= 2)
4001 pSelf->SaveReplay(Length, pFilename: pResult->GetString(Index: 1));
4002 else
4003 pSelf->SaveReplay(Length);
4004 }
4005 }
4006 else
4007 {
4008 pSelf->SaveReplay(Length: g_Config.m_ClReplayLength);
4009 }
4010}
4011
4012void CClient::SaveReplay(const int Length, const char *pFilename)
4013{
4014 if(!g_Config.m_ClReplays)
4015 {
4016 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: "Feature is disabled. Please enable it via configuration.");
4017 GameClient()->Echo(pString: Localize(pStr: "Replay feature is disabled!"));
4018 return;
4019 }
4020
4021 if(!DemoRecorder(Recorder: RECORDER_REPLAYS)->IsRecording())
4022 {
4023 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: "ERROR: demorecorder isn't recording. Try to rejoin to fix that.");
4024 }
4025 else if(DemoRecorder(Recorder: RECORDER_REPLAYS)->Length() < 1)
4026 {
4027 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: "ERROR: demorecorder isn't recording for at least 1 second.");
4028 }
4029 else
4030 {
4031 char aFilename[IO_MAX_PATH_LENGTH];
4032 if(pFilename[0] == '\0')
4033 {
4034 char aTimestamp[20];
4035 str_timestamp(buffer: aTimestamp, buffer_size: sizeof(aTimestamp));
4036 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/replays/%s_%s_(replay).demo", GameClient()->Map()->BaseName(), aTimestamp);
4037 }
4038 else
4039 {
4040 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/replays/%s.demo", pFilename);
4041 IOHANDLE Handle = m_pStorage->OpenFile(pFilename: aFilename, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
4042 if(!Handle)
4043 {
4044 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: "ERROR: invalid filename. Try a different one!");
4045 return;
4046 }
4047 io_close(io: Handle);
4048 m_pStorage->RemoveFile(pFilename: aFilename, Type: IStorage::TYPE_SAVE);
4049 }
4050
4051 // Stop the recorder to correctly slice the demo after
4052 DemoRecorder(Recorder: RECORDER_REPLAYS)->Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
4053
4054 // Slice the demo to get only the last cl_replay_length seconds
4055 const char *pSrc = DemoRecorder(Recorder: RECORDER_REPLAYS)->CurrentFilename();
4056 const int EndTick = GameTick(Conn: g_Config.m_ClDummy);
4057 const int StartTick = EndTick - Length * GameTickSpeed();
4058
4059 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "replay", pStr: "Saving replay...");
4060
4061 // Create a job to do this slicing in background because it can be a bit long depending on the file size
4062 std::shared_ptr<CDemoEdit> pDemoEditTask = std::make_shared<CDemoEdit>(args: GameClient()->NetVersion(), args: &m_SnapshotDelta, args: &m_SnapshotDeltaSixup, args&: m_pStorage, args&: pSrc, args&: aFilename, args: StartTick, args: EndTick);
4063 Engine()->AddJob(pJob: pDemoEditTask);
4064 m_EditJobs.push_back(x: pDemoEditTask);
4065
4066 // And we restart the recorder
4067 DemoRecorder_UpdateReplayRecorder();
4068 }
4069}
4070
4071void CClient::DemoSlice(const char *pDstPath, CLIENTFUNC_FILTER pfnFilter, void *pUser)
4072{
4073 if(m_DemoPlayer.IsPlaying())
4074 {
4075 m_DemoEditor.Slice(pDemo: m_DemoPlayer.Filename(), pDst: pDstPath, StartTick: g_Config.m_ClDemoSliceBegin, EndTick: g_Config.m_ClDemoSliceEnd, pfnFilter, pUser);
4076 }
4077}
4078
4079const char *CClient::DemoPlayer_Play(const char *pFilename, int StorageType)
4080{
4081 // Don't disconnect unless the file exists (only for play command)
4082 if(!Storage()->FileExists(pFilename, Type: StorageType))
4083 return Localize(pStr: "No demo with this filename exists");
4084
4085 Disconnect();
4086 m_aNetClient[CONN_MAIN].ResetErrorString();
4087
4088 SetState(IClient::STATE_LOADING);
4089 SetLoadingStateDetail(IClient::ELoadingStateDetail::LOADING_DEMO);
4090 if((bool)m_LoadingCallback)
4091 m_LoadingCallback(IClient::ELoadingCallbackDetail::DEMO);
4092
4093 // try to start playback
4094 m_DemoPlayer.SetListener(this);
4095 if(m_DemoPlayer.Load(pStorage: Storage(), pFilename, StorageType))
4096 {
4097 DisconnectWithReason(pReason: m_DemoPlayer.ErrorMessage());
4098 return m_DemoPlayer.ErrorMessage();
4099 }
4100
4101 m_Sixup = m_DemoPlayer.IsSixup();
4102
4103 // load map
4104 const CMapInfo *pMapInfo = m_DemoPlayer.GetMapInfo();
4105 const char *pError = LoadMapSearch(pMapName: pMapInfo->m_aName, WantedSha256: pMapInfo->m_Sha256, WantedCrc: pMapInfo->m_Crc);
4106 if(pError)
4107 {
4108 if(!m_DemoPlayer.ExtractMap(pStorage: Storage()))
4109 {
4110 DisconnectWithReason(pReason: pError);
4111 return pError;
4112 }
4113
4114 pError = LoadMapSearch(pMapName: pMapInfo->m_aName, WantedSha256: pMapInfo->m_Sha256, WantedCrc: pMapInfo->m_Crc);
4115 if(pError)
4116 {
4117 DisconnectWithReason(pReason: pError);
4118 return pError;
4119 }
4120 }
4121
4122 // setup current server info
4123 m_CurrentServerInfo = {};
4124 str_copy(dst&: m_CurrentServerInfo.m_aMap, src: pMapInfo->m_aName);
4125 m_CurrentServerInfo.m_MapCrc = pMapInfo->m_Crc;
4126 m_CurrentServerInfo.m_MapSize = pMapInfo->m_Size;
4127
4128 // enter demo playback state
4129 SetState(IClient::STATE_DEMOPLAYBACK);
4130
4131 GameClient()->OnConnected();
4132
4133 // setup buffers
4134 mem_zero(block: m_aaDemorecSnapshotData, size: sizeof(m_aaDemorecSnapshotData));
4135
4136 for(int SnapshotType = 0; SnapshotType < NUM_SNAPSHOT_TYPES; SnapshotType++)
4137 {
4138 m_aapSnapshots[0][SnapshotType] = &m_aDemorecSnapshotHolders[SnapshotType];
4139 m_aapSnapshots[0][SnapshotType]->m_pSnap = m_aaDemorecSnapshotData[SnapshotType][0].AsSnapshot();
4140 m_aapSnapshots[0][SnapshotType]->m_pAltSnap = m_aaDemorecSnapshotData[SnapshotType][1].AsSnapshot();
4141 m_aapSnapshots[0][SnapshotType]->m_SnapSize = 0;
4142 m_aapSnapshots[0][SnapshotType]->m_AltSnapSize = 0;
4143 m_aapSnapshots[0][SnapshotType]->m_Tick = -1;
4144 }
4145
4146 m_DemoPlayer.Play();
4147 GameClient()->OnEnterGame();
4148
4149 return nullptr;
4150}
4151
4152#if defined(CONF_VIDEORECORDER)
4153const char *CClient::DemoPlayer_Render(const char *pFilename, int StorageType, const char *pVideoName, int SpeedIndex, bool StartPaused)
4154{
4155 const char *pError = DemoPlayer_Play(pFilename, StorageType);
4156 if(pError)
4157 return pError;
4158
4159 StartVideo(pFilename: pVideoName, WithTimestamp: false);
4160 m_DemoPlayer.SetSpeedIndex(SpeedIndex);
4161 if(StartPaused)
4162 {
4163 m_DemoPlayer.Pause();
4164 }
4165 return nullptr;
4166}
4167#endif
4168
4169void CClient::Con_Play(IConsole::IResult *pResult, void *pUserData)
4170{
4171 CClient *pSelf = (CClient *)pUserData;
4172 pSelf->HandleDemoPath(pPath: pResult->GetString(Index: 0));
4173}
4174
4175void CClient::Con_DemoPlay(IConsole::IResult *pResult, void *pUserData)
4176{
4177 CClient *pSelf = (CClient *)pUserData;
4178 if(pSelf->m_DemoPlayer.IsPlaying())
4179 {
4180 if(pSelf->m_DemoPlayer.BaseInfo()->m_Paused)
4181 {
4182 pSelf->m_DemoPlayer.Unpause();
4183 }
4184 else
4185 {
4186 pSelf->m_DemoPlayer.Pause();
4187 }
4188 }
4189}
4190
4191void CClient::Con_DemoSpeed(IConsole::IResult *pResult, void *pUserData)
4192{
4193 CClient *pSelf = (CClient *)pUserData;
4194 pSelf->m_DemoPlayer.SetSpeed(pResult->GetFloat(Index: 0));
4195}
4196
4197void CClient::DemoRecorder_Stop(int Recorder)
4198{
4199 if(Recorder == RECORDER_AUTO && DemoRecorder(Recorder: RECORDER_AUTO)->IsRecording() && DemoRecorder(Recorder: RECORDER_AUTO)->HasMarkers())
4200 {
4201 char aFilename[IO_MAX_PATH_LENGTH];
4202 const char *pBaseName = fs_filename(path: DemoRecorder(Recorder)->CurrentFilename());
4203 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/auto/marked/%s", pBaseName);
4204
4205 DemoRecorder(Recorder)->Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE, pTargetFilename: aFilename);
4206 }
4207 else if(Recorder == RECORDER_REPLAYS)
4208 DemoRecorder(Recorder)->Stop(Mode: IDemoRecorder::EStopMode::REMOVE_FILE);
4209 else
4210 DemoRecorder(Recorder)->Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
4211}
4212
4213void CClient::DemoRecorder_Start(const char *pFilename, bool WithTimestamp, int Recorder)
4214{
4215 dbg_assert(State() == IClient::STATE_ONLINE, "Client must be online to record demo");
4216
4217 char aFilename[IO_MAX_PATH_LENGTH];
4218 if(WithTimestamp)
4219 {
4220 char aTimestamp[20];
4221 str_timestamp(buffer: aTimestamp, buffer_size: sizeof(aTimestamp));
4222 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/%s_%s.demo", pFilename, aTimestamp);
4223 }
4224 else
4225 {
4226 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/%s.demo", pFilename);
4227 }
4228
4229 DemoRecorders()[Recorder].Start(
4230 pStorage: Storage(),
4231 pFilename: aFilename,
4232 pNetversion: IsSixup() ? GameClient()->NetVersion7() : GameClient()->NetVersion(),
4233 pMap: GameClient()->Map()->BaseName(),
4234 Sha256: GameClient()->Map()->Sha256(),
4235 MapCrc: GameClient()->Map()->Crc(),
4236 pType: "client",
4237 MapSize: GameClient()->Map()->Size(),
4238 pMapData: nullptr,
4239 MapFile: GameClient()->Map()->File(),
4240 pfnFilter: nullptr,
4241 pUser: nullptr);
4242}
4243
4244void CClient::DemoRecorder_HandleAutoStart()
4245{
4246 if(State() != IClient::STATE_ONLINE)
4247 {
4248 return;
4249 }
4250
4251 if(g_Config.m_ClAutoDemoRecord)
4252 {
4253 DemoRecorder(Recorder: RECORDER_AUTO)->Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
4254
4255 char aFilename[IO_MAX_PATH_LENGTH];
4256 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "auto/%s", GameClient()->Map()->BaseName());
4257 DemoRecorder_Start(pFilename: aFilename, WithTimestamp: true, Recorder: RECORDER_AUTO);
4258
4259 if(g_Config.m_ClAutoDemoMax)
4260 {
4261 // clean up auto recorded demos
4262 CFileCollection AutoDemos;
4263 AutoDemos.Init(pStorage: Storage(), pPath: "demos/auto", pFileDesc: "" /* empty for wild card */, pFileExt: ".demo", MaxEntries: g_Config.m_ClAutoDemoMax);
4264 }
4265 }
4266
4267 DemoRecorder_UpdateReplayRecorder();
4268}
4269
4270void CClient::DemoRecorder_UpdateReplayRecorder()
4271{
4272 if(!g_Config.m_ClReplays && DemoRecorder(Recorder: RECORDER_REPLAYS)->IsRecording())
4273 {
4274 DemoRecorder(Recorder: RECORDER_REPLAYS)->Stop(Mode: IDemoRecorder::EStopMode::REMOVE_FILE);
4275 }
4276
4277 if(g_Config.m_ClReplays && !DemoRecorder(Recorder: RECORDER_REPLAYS)->IsRecording())
4278 {
4279 char aFilename[IO_MAX_PATH_LENGTH];
4280 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "replays/replay_tmp_%s", GameClient()->Map()->BaseName());
4281 DemoRecorder_Start(pFilename: aFilename, WithTimestamp: true, Recorder: RECORDER_REPLAYS);
4282 }
4283}
4284
4285void CClient::DemoRecorder_AddDemoMarker(int Recorder)
4286{
4287 auto &DemoRecorder = DemoRecorders()[Recorder];
4288 if(DemoRecorder.IsRecording())
4289 {
4290 DemoRecorder.AddDemoMarker();
4291 }
4292}
4293
4294CDemoRecorder (&CClient::DemoRecorders())[RECORDER_MAX]
4295{
4296 if(IsSixup())
4297 {
4298 return m_aDemoRecordersSixup;
4299 }
4300 return m_aDemoRecorders;
4301}
4302
4303IDemoRecorder *CClient::DemoRecorder(int Recorder)
4304{
4305 return &DemoRecorders()[Recorder];
4306}
4307
4308void CClient::Con_Record(IConsole::IResult *pResult, void *pUserData)
4309{
4310 CClient *pSelf = (CClient *)pUserData;
4311
4312 if(pSelf->State() != IClient::STATE_ONLINE)
4313 {
4314 log_error("demo_recorder", "Client is not online.");
4315 return;
4316 }
4317 if(pSelf->DemoRecorder(Recorder: RECORDER_MANUAL)->IsRecording())
4318 {
4319 log_error("demo_recorder", "Demo recorder already recording to '%s'.", pSelf->DemoRecorder(RECORDER_MANUAL)->CurrentFilename());
4320 return;
4321 }
4322
4323 if(pResult->NumArguments())
4324 pSelf->DemoRecorder_Start(pFilename: pResult->GetString(Index: 0), WithTimestamp: false, Recorder: RECORDER_MANUAL);
4325 else
4326 pSelf->DemoRecorder_Start(pFilename: pSelf->GameClient()->Map()->BaseName(), WithTimestamp: true, Recorder: RECORDER_MANUAL);
4327}
4328
4329void CClient::Con_StopRecord(IConsole::IResult *pResult, void *pUserData)
4330{
4331 CClient *pSelf = (CClient *)pUserData;
4332 pSelf->DemoRecorder(Recorder: RECORDER_MANUAL)->Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
4333}
4334
4335void CClient::Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData)
4336{
4337 CClient *pSelf = (CClient *)pUserData;
4338 for(int Recorder = 0; Recorder < RECORDER_MAX; Recorder++)
4339 pSelf->DemoRecorder_AddDemoMarker(Recorder);
4340}
4341
4342void CClient::Con_BenchmarkQuit(IConsole::IResult *pResult, void *pUserData)
4343{
4344 CClient *pSelf = (CClient *)pUserData;
4345 int Seconds = pResult->GetInteger(Index: 0);
4346 const char *pFilename = pResult->GetString(Index: 1);
4347 pSelf->BenchmarkQuit(Seconds, pFilename);
4348}
4349
4350void CClient::BenchmarkQuit(int Seconds, const char *pFilename)
4351{
4352 m_BenchmarkFile = Storage()->OpenFile(pFilename, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_ABSOLUTE);
4353 m_BenchmarkStopTime = time_get() + time_freq() * Seconds;
4354}
4355
4356void CClient::UpdateAndSwap()
4357{
4358 Input()->Update();
4359 Graphics()->Swap();
4360 Graphics()->Clear(r: 0, g: 0, b: 0);
4361 m_GlobalTime = (time_get() - m_GlobalStartTime) / (float)time_freq();
4362}
4363
4364void CClient::ServerBrowserUpdate()
4365{
4366 m_ServerBrowser.RequestResort();
4367}
4368
4369void CClient::ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4370{
4371 pfnCallback(pResult, pCallbackUserData);
4372 if(pResult->NumArguments())
4373 ((CClient *)pUserData)->ServerBrowserUpdate();
4374}
4375
4376void CClient::InitChecksum()
4377{
4378 CChecksumData *pData = &m_Checksum.m_Data;
4379 pData->m_SizeofData = sizeof(*pData);
4380 str_copy(dst&: pData->m_aVersionStr, GAME_NAME " " GAME_RELEASE_VERSION " (" CONF_PLATFORM_STRING "; " CONF_ARCH_STRING ")");
4381 pData->m_Start = time_get();
4382 os_version_str(version: pData->m_aOsVersion, length: sizeof(pData->m_aOsVersion));
4383 secure_random_fill(bytes: &pData->m_Random, length: sizeof(pData->m_Random));
4384 pData->m_Version = GameClient()->DDNetVersion();
4385 pData->m_SizeofClient = sizeof(*this);
4386 pData->m_SizeofConfig = sizeof(pData->m_Config);
4387 pData->InitFiles();
4388}
4389
4390#ifndef DDNET_CHECKSUM_SALT
4391// salt@checksum.ddnet.tw: db877f2b-2ddb-3ba6-9f67-a6d169ec671d
4392#define DDNET_CHECKSUM_SALT \
4393 { \
4394 { \
4395 0xdb, 0x87, 0x7f, 0x2b, 0x2d, 0xdb, 0x3b, 0xa6, \
4396 0x9f, 0x67, 0xa6, 0xd1, 0x69, 0xec, 0x67, 0x1d, \
4397 } \
4398 }
4399#endif
4400
4401int CClient::HandleChecksum(int Conn, CUuid Uuid, CUnpacker *pUnpacker)
4402{
4403 int Start = pUnpacker->GetInt();
4404 int Length = pUnpacker->GetInt();
4405 if(pUnpacker->Error())
4406 {
4407 return 1;
4408 }
4409 if(Start < 0 || Length < 0 || Start > std::numeric_limits<int>::max() - Length)
4410 {
4411 return 2;
4412 }
4413 int End = Start + Length;
4414 int ChecksumBytesEnd = std::min(a: End, b: (int)sizeof(m_Checksum.m_aBytes));
4415 int FileStart = std::max(a: Start, b: (int)sizeof(m_Checksum.m_aBytes));
4416 unsigned char aStartBytes[sizeof(int32_t)];
4417 unsigned char aEndBytes[sizeof(int32_t)];
4418 uint_to_bytes_be(bytes: aStartBytes, value: Start);
4419 uint_to_bytes_be(bytes: aEndBytes, value: End);
4420
4421 if(Start <= (int)sizeof(m_Checksum.m_aBytes))
4422 {
4423 mem_zero(block: &m_Checksum.m_Data.m_Config, size: sizeof(m_Checksum.m_Data.m_Config));
4424#define CHECKSUM_RECORD(Flags) (((Flags) & CFGFLAG_CLIENT) == 0 || ((Flags) & CFGFLAG_INSENSITIVE) != 0)
4425#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Flags, Desc) \
4426 if(CHECKSUM_RECORD(Flags)) \
4427 { \
4428 m_Checksum.m_Data.m_Config.m_##Name = g_Config.m_##Name; \
4429 }
4430#define MACRO_CONFIG_COL(Name, ScriptName, Def, Flags, Desc) \
4431 if(CHECKSUM_RECORD(Flags)) \
4432 { \
4433 m_Checksum.m_Data.m_Config.m_##Name = g_Config.m_##Name; \
4434 }
4435#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Flags, Desc) \
4436 if(CHECKSUM_RECORD(Flags)) \
4437 { \
4438 str_copy(m_Checksum.m_Data.m_Config.m_##Name, g_Config.m_##Name); \
4439 }
4440#include <engine/shared/config_variables.h>
4441#undef CHECKSUM_RECORD
4442#undef MACRO_CONFIG_INT
4443#undef MACRO_CONFIG_COL
4444#undef MACRO_CONFIG_STR
4445 }
4446 if(End > (int)sizeof(m_Checksum.m_aBytes))
4447 {
4448 if(m_OwnExecutableSize == 0)
4449 {
4450 m_OwnExecutable = io_current_exe();
4451 // io_length returns -1 on error.
4452 m_OwnExecutableSize = m_OwnExecutable ? io_length(io: m_OwnExecutable) : -1;
4453 }
4454 // Own executable not available.
4455 if(m_OwnExecutableSize < 0)
4456 {
4457 return 3;
4458 }
4459 if(End - (int)sizeof(m_Checksum.m_aBytes) > m_OwnExecutableSize)
4460 {
4461 return 4;
4462 }
4463 }
4464
4465 SHA256_CTX Sha256Ctxt;
4466 sha256_init(ctxt: &Sha256Ctxt);
4467 CUuid Salt = DDNET_CHECKSUM_SALT;
4468 sha256_update(ctxt: &Sha256Ctxt, data: &Salt, data_len: sizeof(Salt));
4469 sha256_update(ctxt: &Sha256Ctxt, data: &Uuid, data_len: sizeof(Uuid));
4470 sha256_update(ctxt: &Sha256Ctxt, data: aStartBytes, data_len: sizeof(aStartBytes));
4471 sha256_update(ctxt: &Sha256Ctxt, data: aEndBytes, data_len: sizeof(aEndBytes));
4472 if(Start < (int)sizeof(m_Checksum.m_aBytes))
4473 {
4474 sha256_update(ctxt: &Sha256Ctxt, data: m_Checksum.m_aBytes + Start, data_len: ChecksumBytesEnd - Start);
4475 }
4476 if(End > (int)sizeof(m_Checksum.m_aBytes))
4477 {
4478 unsigned char aBuf[2048];
4479 if(io_seek(io: m_OwnExecutable, offset: FileStart - sizeof(m_Checksum.m_aBytes), origin: EIoSeekOrigin::START))
4480 {
4481 return 5;
4482 }
4483 for(int i = FileStart; i < End; i += sizeof(aBuf))
4484 {
4485 int Read = io_read(io: m_OwnExecutable, buffer: aBuf, size: std::min(a: (int)sizeof(aBuf), b: End - i));
4486 sha256_update(ctxt: &Sha256Ctxt, data: aBuf, data_len: Read);
4487 }
4488 }
4489 SHA256_DIGEST Sha256 = sha256_finish(ctxt: &Sha256Ctxt);
4490
4491 CMsgPacker Msg(NETMSG_CHECKSUM_RESPONSE, true);
4492 Msg.AddRaw(pData: &Uuid, Size: sizeof(Uuid));
4493 Msg.AddRaw(pData: &Sha256, Size: sizeof(Sha256));
4494 SendMsg(Conn, pMsg: &Msg, Flags: MSGFLAG_VITAL);
4495
4496 return 0;
4497}
4498
4499void CClient::ConchainWindowScreen(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4500{
4501 CClient *pSelf = (CClient *)pUserData;
4502 if(pSelf->Graphics() && pResult->NumArguments())
4503 {
4504 if(g_Config.m_GfxScreen != pResult->GetInteger(Index: 0))
4505 pSelf->Graphics()->SwitchWindowScreen(Index: pResult->GetInteger(Index: 0), MoveToCenter: true);
4506 }
4507 else
4508 {
4509 pfnCallback(pResult, pCallbackUserData);
4510 }
4511}
4512
4513void CClient::ConchainFullscreen(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4514{
4515 CClient *pSelf = (CClient *)pUserData;
4516 if(pSelf->Graphics() && pResult->NumArguments())
4517 {
4518 if(g_Config.m_GfxFullscreen != pResult->GetInteger(Index: 0))
4519 pSelf->Graphics()->SetWindowParams(FullscreenMode: pResult->GetInteger(Index: 0), IsBorderless: g_Config.m_GfxBorderless);
4520 }
4521 else
4522 {
4523 pfnCallback(pResult, pCallbackUserData);
4524 }
4525}
4526
4527void CClient::ConchainWindowBordered(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4528{
4529 CClient *pSelf = (CClient *)pUserData;
4530 if(pSelf->Graphics() && pResult->NumArguments())
4531 {
4532 if(!g_Config.m_GfxFullscreen && (g_Config.m_GfxBorderless != pResult->GetInteger(Index: 0)))
4533 pSelf->Graphics()->SetWindowParams(FullscreenMode: g_Config.m_GfxFullscreen, IsBorderless: !g_Config.m_GfxBorderless);
4534 }
4535 else
4536 {
4537 pfnCallback(pResult, pCallbackUserData);
4538 }
4539}
4540
4541void CClient::Notify(const char *pTitle, const char *pMessage)
4542{
4543 if(m_pGraphics->WindowActive() || !g_Config.m_ClShowNotifications)
4544 return;
4545
4546 Notifications()->Notify(pTitle, pMessage);
4547 Graphics()->NotifyWindow();
4548}
4549
4550void CClient::OnWindowResize()
4551{
4552 TextRender()->OnPreWindowResize();
4553 GameClient()->OnWindowResize();
4554 m_pEditor->OnWindowResize();
4555 TextRender()->OnWindowResize();
4556}
4557
4558void CClient::ConchainWindowVSync(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4559{
4560 CClient *pSelf = (CClient *)pUserData;
4561 if(pSelf->Graphics() && pResult->NumArguments())
4562 {
4563 if(g_Config.m_GfxVsync != pResult->GetInteger(Index: 0))
4564 pSelf->Graphics()->SetVSync(pResult->GetInteger(Index: 0));
4565 }
4566 else
4567 {
4568 pfnCallback(pResult, pCallbackUserData);
4569 }
4570}
4571
4572void CClient::ConchainWindowResize(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4573{
4574 CClient *pSelf = (CClient *)pUserData;
4575 pfnCallback(pResult, pCallbackUserData);
4576 if(pSelf->Graphics() && pResult->NumArguments())
4577 {
4578 pSelf->Graphics()->ResizeToScreen();
4579 }
4580}
4581
4582void CClient::ConchainTimeoutSeed(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4583{
4584 CClient *pSelf = (CClient *)pUserData;
4585 pfnCallback(pResult, pCallbackUserData);
4586 if(pResult->NumArguments())
4587 pSelf->m_GenerateTimeoutSeed = false;
4588}
4589
4590void CClient::ConchainPassword(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4591{
4592 CClient *pSelf = (CClient *)pUserData;
4593 pfnCallback(pResult, pCallbackUserData);
4594 if(pResult->NumArguments() && pSelf->m_LocalStartTime) //won't set m_SendPassword before game has started
4595 pSelf->m_SendPassword = true;
4596}
4597
4598void CClient::ConchainReplays(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4599{
4600 CClient *pSelf = (CClient *)pUserData;
4601 pfnCallback(pResult, pCallbackUserData);
4602 if(pResult->NumArguments() && pSelf->State() == IClient::STATE_ONLINE)
4603 {
4604 pSelf->DemoRecorder_UpdateReplayRecorder();
4605 }
4606}
4607
4608void CClient::ConchainInputFifo(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4609{
4610 CClient *pSelf = (CClient *)pUserData;
4611 pfnCallback(pResult, pCallbackUserData);
4612 if(pSelf->m_Fifo.IsInit())
4613 {
4614 pSelf->m_Fifo.Shutdown();
4615 pSelf->m_Fifo.Init(pConsole: pSelf->m_pConsole, pFifoFile: pSelf->Config()->m_ClInputFifo, Flag: CFGFLAG_CLIENT);
4616 }
4617}
4618
4619void CClient::ConchainNetReset(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4620{
4621 CClient *pSelf = (CClient *)pUserData;
4622 pfnCallback(pResult, pCallbackUserData);
4623 if(pResult->NumArguments() && pSelf->m_LocalStartTime > 0)
4624 {
4625 pSelf->ResetSocket();
4626 }
4627}
4628
4629void CClient::ConchainLoglevel(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4630{
4631 CClient *pSelf = (CClient *)pUserData;
4632 pfnCallback(pResult, pCallbackUserData);
4633 if(pResult->NumArguments())
4634 {
4635 pSelf->m_pFileLogger->SetFilter(CLogFilter{.m_MaxLevel: IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_Loglevel)});
4636 }
4637}
4638
4639void CClient::ConchainStdoutOutputLevel(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4640{
4641 CClient *pSelf = (CClient *)pUserData;
4642 pfnCallback(pResult, pCallbackUserData);
4643 if(pResult->NumArguments() && pSelf->m_pStdoutLogger)
4644 {
4645 pSelf->m_pStdoutLogger->SetFilter(CLogFilter{.m_MaxLevel: IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_StdoutOutputLevel)});
4646 }
4647}
4648
4649void CClient::RegisterCommands()
4650{
4651 m_pConsole = Kernel()->RequestInterface<IConsole>();
4652
4653 m_pConsole->Register(pName: "dummy_connect", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_DummyConnect, pUser: this, pHelp: "Connect dummy");
4654 m_pConsole->Register(pName: "dummy_disconnect", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_DummyDisconnect, pUser: this, pHelp: "Disconnect dummy");
4655 m_pConsole->Register(pName: "dummy_reset", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_DummyResetInput, pUser: this, pHelp: "Reset dummy");
4656
4657 m_pConsole->Register(pName: "quit", pParams: "", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: Con_Quit, pUser: this, pHelp: "Quit the client");
4658 m_pConsole->Register(pName: "exit", pParams: "", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: Con_Quit, pUser: this, pHelp: "Quit the client");
4659 m_pConsole->Register(pName: "restart", pParams: "", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: Con_Restart, pUser: this, pHelp: "Restart the client");
4660 m_pConsole->Register(pName: "minimize", pParams: "", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: Con_Minimize, pUser: this, pHelp: "Minimize the client");
4661 m_pConsole->Register(pName: "connect", pParams: "r[host|ip]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_Connect, pUser: this, pHelp: "Connect to the specified host/ip");
4662 m_pConsole->Register(pName: "disconnect", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_Disconnect, pUser: this, pHelp: "Disconnect from the server");
4663 m_pConsole->Register(pName: "ping", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_Ping, pUser: this, pHelp: "Ping the current server");
4664 m_pConsole->Register(pName: "screenshot", pParams: "", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: Con_Screenshot, pUser: this, pHelp: "Take a screenshot");
4665 m_pConsole->Register(pName: "net_reset", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConNetReset, pUser: this, pHelp: "Rebinds the client's listening address and port");
4666
4667#if defined(CONF_VIDEORECORDER)
4668 m_pConsole->Register(pName: "start_video", pParams: "?r[file]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_StartVideo, pUser: this, pHelp: "Start recording a video");
4669 m_pConsole->Register(pName: "stop_video", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_StopVideo, pUser: this, pHelp: "Stop recording a video");
4670#endif
4671
4672 m_pConsole->Register(pName: "rcon", pParams: "r[rcon-command]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_Rcon, pUser: this, pHelp: "Send specified command to rcon");
4673 m_pConsole->Register(pName: "rcon_auth", pParams: "r[password]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_RconAuth, pUser: this, pHelp: "Authenticate to rcon");
4674 m_pConsole->Register(pName: "rcon_login", pParams: "s[username] r[password]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_RconLogin, pUser: this, pHelp: "Authenticate to rcon with a username");
4675 m_pConsole->Register(pName: "play", pParams: "r[file]", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: Con_Play, pUser: this, pHelp: "Play back a demo");
4676 m_pConsole->Register(pName: "record", pParams: "?r[file]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_Record, pUser: this, pHelp: "Start recording a demo");
4677 m_pConsole->Register(pName: "stoprecord", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_StopRecord, pUser: this, pHelp: "Stop recording a demo");
4678 m_pConsole->Register(pName: "add_demomarker", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_AddDemoMarker, pUser: this, pHelp: "Add demo timeline marker");
4679 m_pConsole->Register(pName: "begin_favorite_group", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_BeginFavoriteGroup, pUser: this, pHelp: "Use this before `add_favorite` to group favorites. End with `end_favorite_group`");
4680 m_pConsole->Register(pName: "end_favorite_group", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_EndFavoriteGroup, pUser: this, pHelp: "Use this after `add_favorite` to group favorites. Start with `begin_favorite_group`");
4681 m_pConsole->Register(pName: "add_favorite", pParams: "s[host|ip] ?s['allow_ping']", Flags: CFGFLAG_CLIENT, pfnFunc: Con_AddFavorite, pUser: this, pHelp: "Add a server as a favorite");
4682 m_pConsole->Register(pName: "remove_favorite", pParams: "r[host|ip]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_RemoveFavorite, pUser: this, pHelp: "Remove a server from favorites");
4683 m_pConsole->Register(pName: "demo_slice_start", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_DemoSliceBegin, pUser: this, pHelp: "Mark the beginning of a demo cut");
4684 m_pConsole->Register(pName: "demo_slice_end", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_DemoSliceEnd, pUser: this, pHelp: "Mark the end of a demo cut");
4685 m_pConsole->Register(pName: "demo_play", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_DemoPlay, pUser: this, pHelp: "Play/pause the current demo");
4686 m_pConsole->Register(pName: "demo_speed", pParams: "f[speed]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_DemoSpeed, pUser: this, pHelp: "Set current demo speed");
4687
4688 m_pConsole->Register(pName: "save_replay", pParams: "?i[length] ?r[filename]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_SaveReplay, pUser: this, pHelp: "Save a replay of the last defined amount of seconds");
4689 m_pConsole->Register(pName: "benchmark_quit", pParams: "i[seconds] r[file]", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: Con_BenchmarkQuit, pUser: this, pHelp: "Benchmark frame times for number of seconds to file, then quit");
4690
4691 RustVersionRegister(console&: *m_pConsole);
4692
4693 m_pConsole->Chain(pName: "cl_timeout_seed", pfnChainFunc: ConchainTimeoutSeed, pUser: this);
4694 m_pConsole->Chain(pName: "cl_replays", pfnChainFunc: ConchainReplays, pUser: this);
4695 m_pConsole->Chain(pName: "cl_input_fifo", pfnChainFunc: ConchainInputFifo, pUser: this);
4696 m_pConsole->Chain(pName: "cl_port", pfnChainFunc: ConchainNetReset, pUser: this);
4697 m_pConsole->Chain(pName: "cl_dummy_port", pfnChainFunc: ConchainNetReset, pUser: this);
4698 m_pConsole->Chain(pName: "cl_contact_port", pfnChainFunc: ConchainNetReset, pUser: this);
4699 m_pConsole->Chain(pName: "bindaddr", pfnChainFunc: ConchainNetReset, pUser: this);
4700
4701 m_pConsole->Chain(pName: "password", pfnChainFunc: ConchainPassword, pUser: this);
4702
4703 // used for server browser update
4704 m_pConsole->Chain(pName: "br_filter_string", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4705 m_pConsole->Chain(pName: "br_exclude_string", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4706 m_pConsole->Chain(pName: "br_filter_full", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4707 m_pConsole->Chain(pName: "br_filter_empty", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4708 m_pConsole->Chain(pName: "br_filter_spectators", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4709 m_pConsole->Chain(pName: "br_filter_friends", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4710 m_pConsole->Chain(pName: "br_filter_country", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4711 m_pConsole->Chain(pName: "br_filter_country_index", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4712 m_pConsole->Chain(pName: "br_filter_pw", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4713 m_pConsole->Chain(pName: "br_filter_gametype", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4714 m_pConsole->Chain(pName: "br_filter_gametype_strict", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4715 m_pConsole->Chain(pName: "br_filter_connecting_players", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4716 m_pConsole->Chain(pName: "br_filter_serveraddress", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4717 m_pConsole->Chain(pName: "br_filter_unfinished_map", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4718 m_pConsole->Chain(pName: "br_filter_login", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4719 m_pConsole->Chain(pName: "add_favorite", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4720 m_pConsole->Chain(pName: "remove_favorite", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4721 m_pConsole->Chain(pName: "end_favorite_group", pfnChainFunc: ConchainServerBrowserUpdate, pUser: this);
4722
4723 m_pConsole->Chain(pName: "gfx_screen", pfnChainFunc: ConchainWindowScreen, pUser: this);
4724 m_pConsole->Chain(pName: "gfx_screen_width", pfnChainFunc: ConchainWindowResize, pUser: this);
4725 m_pConsole->Chain(pName: "gfx_screen_height", pfnChainFunc: ConchainWindowResize, pUser: this);
4726 m_pConsole->Chain(pName: "gfx_screen_refresh_rate", pfnChainFunc: ConchainWindowResize, pUser: this);
4727 m_pConsole->Chain(pName: "gfx_fullscreen", pfnChainFunc: ConchainFullscreen, pUser: this);
4728 m_pConsole->Chain(pName: "gfx_borderless", pfnChainFunc: ConchainWindowBordered, pUser: this);
4729 m_pConsole->Chain(pName: "gfx_vsync", pfnChainFunc: ConchainWindowVSync, pUser: this);
4730
4731 m_pConsole->Chain(pName: "loglevel", pfnChainFunc: ConchainLoglevel, pUser: this);
4732 m_pConsole->Chain(pName: "stdout_output_level", pfnChainFunc: ConchainStdoutOutputLevel, pUser: this);
4733}
4734
4735static CClient *CreateClient()
4736{
4737 return new CClient;
4738}
4739
4740void CClient::HandleConnectAddress(const NETADDR *pAddr)
4741{
4742 net_addr_str(addr: pAddr, string: m_aCmdConnect, max_length: sizeof(m_aCmdConnect), add_port: true);
4743}
4744
4745void CClient::HandleConnectLink(const char *pLink)
4746{
4747 // Chrome works fine with ddnet:// but not with ddnet:
4748 // Check ddnet:// before ddnet: because we don't want the // as part of connect command
4749 const char *pConnectLink = nullptr;
4750 if((pConnectLink = str_startswith(str: pLink, CONNECTLINK_DOUBLE_SLASH)))
4751 str_copy(dst&: m_aCmdConnect, src: pConnectLink);
4752 else if((pConnectLink = str_startswith(str: pLink, CONNECTLINK_NO_SLASH)))
4753 str_copy(dst&: m_aCmdConnect, src: pConnectLink);
4754 else
4755 str_copy(dst&: m_aCmdConnect, src: pLink);
4756 // Edge appends / to the URL
4757 const int Length = str_length(str: m_aCmdConnect);
4758 if(m_aCmdConnect[Length - 1] == '/')
4759 m_aCmdConnect[Length - 1] = '\0';
4760}
4761
4762void CClient::HandleDemoPath(const char *pPath)
4763{
4764 str_copy(dst&: m_aCmdPlayDemo, src: pPath);
4765}
4766
4767void CClient::HandleMapPath(const char *pPath)
4768{
4769 str_copy(dst&: m_aCmdEditMap, src: pPath);
4770}
4771
4772static bool UnknownArgumentCallback(const char *pCommand, void *pUser)
4773{
4774 CClient *pClient = static_cast<CClient *>(pUser);
4775 if(str_startswith(str: pCommand, CONNECTLINK_NO_SLASH))
4776 {
4777 pClient->HandleConnectLink(pLink: pCommand);
4778 return true;
4779 }
4780 else if(str_endswith(str: pCommand, suffix: ".demo"))
4781 {
4782 pClient->HandleDemoPath(pPath: pCommand);
4783 return true;
4784 }
4785 else if(str_endswith(str: pCommand, suffix: ".map"))
4786 {
4787 pClient->HandleMapPath(pPath: pCommand);
4788 return true;
4789 }
4790 return false;
4791}
4792
4793static bool SaveUnknownCommandCallback(const char *pCommand, void *pUser)
4794{
4795 CClient *pClient = static_cast<CClient *>(pUser);
4796 pClient->ConfigManager()->StoreUnknownCommand(pCommand);
4797 return true;
4798}
4799
4800#if defined(CONF_PLATFORM_EMSCRIPTEN)
4801extern "C" {
4802
4803// This will be called from Emscripten JS code
4804void EmscriptenCallbackQuitForce()
4805{
4806 emscripten_force_exit(-1);
4807}
4808}
4809#endif
4810
4811/*
4812 Server Time
4813 Client Mirror Time
4814 Client Predicted Time
4815
4816 Snapshot Latency
4817 Downstream latency
4818
4819 Prediction Latency
4820 Upstream latency
4821*/
4822
4823#if defined(CONF_PLATFORM_MACOS)
4824extern "C" int TWMain(int argc, const char **argv)
4825#elif defined(CONF_PLATFORM_ANDROID)
4826static int gs_AndroidStarted = false;
4827extern "C" [[gnu::visibility("default")]] int SDL_main(int argc, char *argv[]);
4828int SDL_main(int argc, char *argv2[])
4829#elif defined(CONF_PLATFORM_IOS)
4830extern "C" int SDL_main(int argc, char *argv[]);
4831int SDL_main(int argc, char *argv2[])
4832#else
4833int main(int argc, const char **argv)
4834#endif
4835{
4836 const int64_t MainStart = time_get();
4837
4838#if defined(CONF_PLATFORM_ANDROID) || defined(CONF_PLATFORM_IOS)
4839 const char **argv = const_cast<const char **>(argv2);
4840#endif
4841#if defined(CONF_PLATFORM_ANDROID)
4842 // Android might not unload the library from memory, causing globals like gs_AndroidStarted
4843 // not to be initialized correctly when starting the app again.
4844 if(gs_AndroidStarted)
4845 {
4846 ShowMessageBoxWithoutGraphics({.m_pTitle = "Android Error", .m_pMessage = "The app was started, but not closed properly, this causes bugs. Please restart or manually close this task."});
4847 std::exit(0);
4848 }
4849 gs_AndroidStarted = true;
4850#elif defined(CONF_FAMILY_WINDOWS)
4851 CWindowsComLifecycle WindowsComLifecycle(true);
4852#endif
4853 CCmdlineFix CmdlineFix(&argc, &argv);
4854
4855 std::vector<std::shared_ptr<ILogger>> vpLoggers;
4856 std::shared_ptr<ILogger> pStdoutLogger = nullptr;
4857#if defined(CONF_PLATFORM_ANDROID)
4858 pStdoutLogger = std::shared_ptr<ILogger>(log_logger_android());
4859#else
4860 bool Silent = false;
4861 for(int i = 1; i < argc; i++)
4862 {
4863 if(str_comp(a: "-s", b: argv[i]) == 0 || str_comp(a: "--silent", b: argv[i]) == 0)
4864 {
4865 Silent = true;
4866 }
4867 }
4868 if(!Silent)
4869 {
4870 pStdoutLogger = std::shared_ptr<ILogger>(log_logger_stdout());
4871 }
4872#endif
4873 if(pStdoutLogger)
4874 {
4875 vpLoggers.push_back(x: pStdoutLogger);
4876 }
4877 std::shared_ptr<CFutureLogger> pFutureFileLogger = std::make_shared<CFutureLogger>();
4878 vpLoggers.push_back(x: pFutureFileLogger);
4879 std::shared_ptr<CFutureLogger> pFutureConsoleLogger = std::make_shared<CFutureLogger>();
4880 vpLoggers.push_back(x: pFutureConsoleLogger);
4881 std::shared_ptr<CFutureLogger> pFutureAssertionLogger = std::make_shared<CFutureLogger>();
4882 vpLoggers.push_back(x: pFutureAssertionLogger);
4883 log_set_global_logger(logger: log_logger_collection(vpLoggers: std::move(vpLoggers)).release());
4884
4885#if defined(CONF_PLATFORM_ANDROID)
4886 // Initialize Android after logger is available
4887 const char *pAndroidInitError = InitAndroid();
4888 if(pAndroidInitError != nullptr)
4889 {
4890 log_error("android", "%s", pAndroidInitError);
4891 ShowMessageBoxWithoutGraphics({.m_pTitle = "Android Error", .m_pMessage = pAndroidInitError});
4892 std::exit(0);
4893 }
4894#endif
4895#if defined(CONF_PLATFORM_IOS)
4896 // Initialize iOS after logger is available
4897 const char *pIosInitError = InitIos();
4898 if(pIosInitError != nullptr)
4899 {
4900 log_error("ios", "%s", pIosInitError);
4901 ShowMessageBoxWithoutGraphics({.m_pTitle = "iOS Error", .m_pMessage = pIosInitError});
4902 std::exit(0);
4903 }
4904#endif
4905
4906 std::stack<std::function<void()>> CleanerFunctions;
4907 std::function<void()> PerformCleanup = [&CleanerFunctions]() mutable {
4908 while(!CleanerFunctions.empty())
4909 {
4910 CleanerFunctions.top()();
4911 CleanerFunctions.pop();
4912 }
4913 };
4914 std::function<void()> PerformFinalCleanup = []() {
4915#if defined(CONF_PLATFORM_ANDROID)
4916 // Forcefully terminate the entire process, to ensure that static variables
4917 // will be initialized correctly when the app is started again after quitting.
4918 // Returning from the main function is not enough, as this only results in the
4919 // native thread terminating, but the Java thread will continue. Java does not
4920 // support unloading libraries once they have been loaded, so all static
4921 // variables will not have their expected initial values anymore when the app
4922 // is started again after quitting. The variable gs_AndroidStarted above is
4923 // used to check that static variables have been initialized properly.
4924 // TODO: This is not the correct way to close an activity on Android, as it
4925 // ignores the activity lifecycle entirely, which may cause issues if
4926 // we ever used any global resources like the camera.
4927 std::exit(0);
4928#elif defined(CONF_PLATFORM_IOS)
4929 // iOS does not reliably terminate when returning from SDL_main.
4930 // For local debugging we terminate explicitly on Quit.
4931 std::exit(0);
4932#elif defined(CONF_PLATFORM_EMSCRIPTEN)
4933 // We cannot use atexit with Emscripten so we finish the global logger here.
4934 // See comment in the log_set_global_logger function for details.
4935 log_global_logger_finish();
4936#endif
4937 };
4938 std::function<void()> PerformAllCleanup = [PerformCleanup, PerformFinalCleanup]() mutable {
4939 PerformCleanup();
4940 PerformFinalCleanup();
4941 };
4942
4943 // Register SDL for cleanup before creating the kernel and client,
4944 // so SDL is shutdown after kernel and client. Otherwise the client
4945 // may crash when shutting down after SDL is already shutdown.
4946 CleanerFunctions.emplace(args: []() { SDL_Quit(); });
4947
4948 CClient *pClient = CreateClient();
4949 pClient->SetLoggers(pFileLogger: pFutureFileLogger, pStdoutLogger: std::move(pStdoutLogger));
4950
4951 IKernel *pKernel = IKernel::Create();
4952 pKernel->RegisterInterface(pInterface: pClient, Destroy: false);
4953 pClient->RegisterInterfaces();
4954 CleanerFunctions.emplace(args: [pKernel, pClient]() {
4955 // Ensure that the assert handler doesn't use the client/graphics after they've been destroyed
4956 dbg_assert_set_handler(handler: nullptr);
4957 pKernel->Shutdown();
4958 delete pKernel;
4959 delete pClient;
4960 });
4961
4962 const std::thread::id MainThreadId = std::this_thread::get_id();
4963 dbg_assert_set_handler(handler: [MainThreadId, pClient](const char *pMsg) {
4964 if(MainThreadId != std::this_thread::get_id())
4965 return;
4966
4967 const char *pGraphicsError = pClient->Graphics() == nullptr ? "" : pClient->Graphics()->GetFatalError();
4968 const bool GotGraphicsError = pGraphicsError[0] != '\0';
4969 const char *pTitle;
4970 const char *pPreamble;
4971 const char *pPostamble;
4972 if(GotGraphicsError)
4973 {
4974 pTitle = "Graphics Error";
4975 pPreamble =
4976 "A graphics error occurred. Please see details and instructions below.\n\n";
4977 pPostamble =
4978 "For detailed troubleshooting instructions please read our Wiki:\n"
4979 "https://wiki.ddnet.org/wiki/GFX_Troubleshooting\n\n"
4980 "If this did not resolve the issue, please take a screenshot and report this error.\n"
4981 "Please also share the assert log"
4982#if defined(CONF_CRASHDUMP)
4983 " and crash log"
4984#endif
4985 " found in the 'dumps' folder in your config directory.\n\n";
4986 // This is more human readable and we don't care about the source location here,
4987 // because all graphics assertions come from CGraphicsBackend_Threaded::ProcessError
4988 // and the original message is also logged separately by the assertion system.
4989 pMsg = pGraphicsError;
4990 }
4991 else
4992 {
4993 pTitle = "Assertion Error";
4994 pPreamble =
4995 "An assertion error occurred. Please take a screenshot and report this error.\n"
4996 "Please also share the assert log"
4997#if defined(CONF_CRASHDUMP)
4998 " and crash log"
4999#endif
5000 " found in the 'dumps' folder in your config directory.\n\n";
5001 pPostamble = "";
5002 }
5003
5004 char aOsVersionString[128];
5005 if(!os_version_str(version: aOsVersionString, length: sizeof(aOsVersionString)))
5006 {
5007 str_copy(dst&: aOsVersionString, src: "unknown");
5008 }
5009
5010 char aGpuInfo[512];
5011 pClient->GetGpuInfoString(aGpuInfo);
5012
5013 char aMessage[2048];
5014 str_format(buffer: aMessage, buffer_size: sizeof(aMessage),
5015 format: "%s"
5016 "%s\n\n"
5017 "%s"
5018 "Platform: %s (%s)\n"
5019 "Configuration: base"
5020#if defined(CONF_AUTOUPDATE)
5021 " + autoupdate"
5022#endif
5023#if defined(CONF_CRASHDUMP)
5024 " + crashdump"
5025#endif
5026#if defined(CONF_DEBUG)
5027 " + debug"
5028#endif
5029#if defined(CONF_DISCORD)
5030 " + discord"
5031#endif
5032#if defined(CONF_VIDEORECORDER)
5033 " + videorecorder"
5034#endif
5035#if defined(CONF_WEBSOCKETS)
5036 " + websockets"
5037#endif
5038 "\n"
5039 "Game version: %s %s %s\n"
5040 "OS version: %s\n\n"
5041 "%s", // GPU info
5042 pPreamble,
5043 pMsg,
5044 pPostamble,
5045 CONF_PLATFORM_STRING, CONF_ARCH_ENDIAN_STRING,
5046 GAME_NAME, GAME_RELEASE_VERSION, GIT_SHORTREV_HASH != nullptr ? GIT_SHORTREV_HASH : "",
5047 aOsVersionString,
5048 aGpuInfo);
5049 // Also log all of this information to the assertion log file
5050 log_error("assertion", "%s", aMessage);
5051 std::vector<IGraphics::CMessageBoxButton> vButtons;
5052 if(GotGraphicsError)
5053 {
5054 vButtons.push_back(x: {.m_pLabel = "Show Wiki"});
5055 }
5056 // Storage may not have been initialized yet and viewing files is not supported on Android yet
5057#if !defined(CONF_PLATFORM_ANDROID)
5058 if(pClient->Storage() != nullptr)
5059 {
5060 vButtons.push_back(x: {.m_pLabel = "Show dumps"});
5061 }
5062#endif
5063 vButtons.push_back(x: {.m_pLabel = "OK", .m_Confirm = true, .m_Cancel = true});
5064 const std::optional<int> MessageResult = pClient->ShowMessageBox(MessageBox: {.m_pTitle = pTitle, .m_pMessage = aMessage, .m_vButtons = vButtons});
5065 if(GotGraphicsError && MessageResult && *MessageResult == 0)
5066 {
5067 pClient->ViewLink(pLink: "https://wiki.ddnet.org/wiki/GFX_Troubleshooting");
5068 }
5069#if !defined(CONF_PLATFORM_ANDROID)
5070 if(pClient->Storage() != nullptr && MessageResult && *MessageResult == (GotGraphicsError ? 1 : 0))
5071 {
5072 char aDumpsPath[IO_MAX_PATH_LENGTH];
5073 pClient->Storage()->GetCompletePath(Type: IStorage::TYPE_SAVE, pDir: "dumps", pBuffer: aDumpsPath, BufferSize: sizeof(aDumpsPath));
5074 pClient->ViewFile(pFilename: aDumpsPath);
5075 }
5076#endif
5077 // Client will crash due to assertion, don't call PerformAllCleanup in this inconsistent state
5078 });
5079
5080 // create the components
5081 IEngine *pEngine = CreateEngine(GAME_NAME, pFutureLogger: pFutureConsoleLogger);
5082 pKernel->RegisterInterface(pInterface: pEngine, Destroy: false);
5083 CleanerFunctions.emplace(args: [pEngine]() {
5084 // Engine has to be destroyed before the graphics so that skin download thread can finish
5085 delete pEngine;
5086 });
5087
5088 IStorage *pStorage;
5089 {
5090 CMemoryLogger MemoryLogger;
5091 MemoryLogger.SetParent(log_get_scope_logger());
5092 {
5093 CLogScope LogScope(&MemoryLogger);
5094 pStorage = CreateStorage(InitializationType: IStorage::EInitializationType::CLIENT, NumArgs: argc, ppArguments: argv);
5095 }
5096 if(!pStorage)
5097 {
5098 log_error("client", "Failed to initialize the storage location (see details above)");
5099 std::string Message = std::string("Failed to initialize the storage location. See details below.\n\n") + MemoryLogger.ConcatenatedLines();
5100 pClient->ShowMessageBox(MessageBox: {.m_pTitle = "Storage Error", .m_pMessage = Message.c_str()});
5101 PerformAllCleanup();
5102 return -1;
5103 }
5104 }
5105 pKernel->RegisterInterface(pInterface: pStorage);
5106
5107 pFutureAssertionLogger->Set(CreateAssertionLogger(pStorage, GAME_NAME));
5108
5109 {
5110 char aTimestamp[20];
5111 str_timestamp(buffer: aTimestamp, buffer_size: sizeof(aTimestamp));
5112
5113 char aBufName[IO_MAX_PATH_LENGTH];
5114 str_format(buffer: aBufName, buffer_size: sizeof(aBufName), format: "dumps/%s_%s_%s_%s_crash_log_%s_%d_%s.RTP",
5115 GAME_NAME,
5116 GAME_RELEASE_VERSION,
5117 CONF_PLATFORM_STRING,
5118 CONF_ARCH_STRING,
5119 aTimestamp,
5120 process_id(),
5121 GIT_SHORTREV_HASH != nullptr ? GIT_SHORTREV_HASH : "");
5122
5123 char aBufPath[IO_MAX_PATH_LENGTH];
5124 pStorage->GetCompletePath(Type: IStorage::TYPE_SAVE, pDir: aBufName, pBuffer: aBufPath, BufferSize: sizeof(aBufPath));
5125 crashdump_init_if_available(log_file_path: aBufPath);
5126 }
5127
5128 IConsole *pConsole = CreateConsole(FlagMask: CFGFLAG_CLIENT).release();
5129 pKernel->RegisterInterface(pInterface: pConsole);
5130
5131 IConfigManager *pConfigManager = CreateConfigManager();
5132 pKernel->RegisterInterface(pInterface: pConfigManager);
5133
5134 IEngineSound *pEngineSound = CreateEngineSound();
5135 pKernel->RegisterInterface(pInterface: pEngineSound); // IEngineSound
5136 pKernel->RegisterInterface(pInterface: static_cast<ISound *>(pEngineSound), Destroy: false);
5137
5138 IEngineInput *pEngineInput = CreateEngineInput();
5139 pKernel->RegisterInterface(pInterface: pEngineInput); // IEngineInput
5140 pKernel->RegisterInterface(pInterface: static_cast<IInput *>(pEngineInput), Destroy: false);
5141
5142 IEngineTextRender *pEngineTextRender = CreateEngineTextRender();
5143 pKernel->RegisterInterface(pInterface: pEngineTextRender); // IEngineTextRender
5144 pKernel->RegisterInterface(pInterface: static_cast<ITextRender *>(pEngineTextRender), Destroy: false);
5145
5146 IEngineHttp *pEngineHttp = CreateEngineHttp();
5147 pKernel->RegisterInterface(pInterface: pEngineHttp); // IEngineHttp
5148 pKernel->RegisterInterface(pInterface: static_cast<IHttp *>(pEngineHttp), Destroy: false);
5149
5150 IDiscord *pDiscord = CreateDiscord();
5151 pKernel->RegisterInterface(pInterface: pDiscord);
5152
5153 ISteam *pSteam = CreateSteam();
5154 pKernel->RegisterInterface(pInterface: pSteam);
5155
5156 INotifications *pNotifications = CreateNotifications();
5157 pKernel->RegisterInterface(pInterface: pNotifications);
5158
5159 pKernel->RegisterInterface(pInterface: CreateEditor(), Destroy: false);
5160 pKernel->RegisterInterface(pInterface: CreateFavorites().release());
5161 pKernel->RegisterInterface(pInterface: CreateGameClient());
5162
5163 pEngine->Init();
5164 pConsole->Init();
5165 pConfigManager->Init();
5166 pNotifications->Init(GAME_NAME " Client");
5167
5168 // register all console commands
5169 pClient->RegisterCommands();
5170
5171 pKernel->RequestInterface<IGameClient>()->OnConsoleInit();
5172
5173 // init client's interfaces
5174 pClient->InitInterfaces();
5175
5176 // execute config file
5177 if(pStorage->FileExists(CONFIG_FILE, Type: IStorage::TYPE_ALL))
5178 {
5179 pConsole->SetUnknownCommandCallback(pfnCallback: SaveUnknownCommandCallback, pUser: pClient);
5180 if(!pConsole->ExecuteFile(CONFIG_FILE, ClientId: IConsole::CLIENT_ID_UNSPECIFIED))
5181 {
5182 const char *pError = "Failed to load config from '" CONFIG_FILE "'.";
5183 log_error("client", "%s", pError);
5184 pClient->ShowMessageBox(MessageBox: {.m_pTitle = "Config File Error", .m_pMessage = pError});
5185 PerformAllCleanup();
5186 return -1;
5187 }
5188 pConsole->SetUnknownCommandCallback(pfnCallback: IConsole::EmptyUnknownCommandCallback, pUser: nullptr);
5189 }
5190
5191 // execute autoexec file
5192 if(pStorage->FileExists(AUTOEXEC_CLIENT_FILE, Type: IStorage::TYPE_ALL))
5193 {
5194 pConsole->ExecuteFile(AUTOEXEC_CLIENT_FILE, ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
5195 }
5196 else // fallback
5197 {
5198 pConsole->ExecuteFile(AUTOEXEC_FILE, ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
5199 }
5200
5201 if(g_Config.m_ClConfigVersion < 1)
5202 {
5203 if(g_Config.m_ClAntiPing == 0)
5204 {
5205 g_Config.m_ClAntiPingPlayers = 1;
5206 g_Config.m_ClAntiPingGrenade = 1;
5207 g_Config.m_ClAntiPingWeapons = 1;
5208 }
5209 }
5210 g_Config.m_ClConfigVersion = 1;
5211
5212 // parse the command line arguments
5213 pConsole->SetUnknownCommandCallback(pfnCallback: UnknownArgumentCallback, pUser: pClient);
5214 pConsole->ParseArguments(NumArgs: argc - 1, ppArguments: &argv[1]);
5215 pConsole->SetUnknownCommandCallback(pfnCallback: IConsole::EmptyUnknownCommandCallback, pUser: nullptr);
5216
5217 if(pSteam->GetConnectAddress())
5218 {
5219 pClient->HandleConnectAddress(pAddr: pSteam->GetConnectAddress());
5220 pSteam->ClearConnectAddress();
5221 }
5222
5223 if(g_Config.m_Logfile[0])
5224 {
5225 const int Mode = g_Config.m_Logappend ? IOFLAG_APPEND : IOFLAG_WRITE;
5226 IOHANDLE Logfile = pStorage->OpenFile(pFilename: g_Config.m_Logfile, Flags: Mode, Type: IStorage::TYPE_SAVE_OR_ABSOLUTE);
5227 if(Logfile)
5228 {
5229 auto pFileLogger = log_logger_file(file: Logfile);
5230 pFileLogger->SetFilter(CLogFilter{.m_MaxLevel: IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_Loglevel)});
5231 pFutureFileLogger->Set(std::move(pFileLogger));
5232 }
5233 else
5234 {
5235 log_error("client", "failed to open '%s' for logging", g_Config.m_Logfile);
5236 pFutureFileLogger->Set(log_logger_noop());
5237 }
5238 }
5239 else
5240 {
5241 pFutureFileLogger->Set(log_logger_noop());
5242 }
5243
5244 // Register protocol and file extensions
5245#if defined(CONF_FAMILY_WINDOWS)
5246 pClient->ShellRegister();
5247#endif
5248
5249 // Do not automatically translate touch events to mouse events and vice versa.
5250 SDL_SetHint(name: "SDL_TOUCH_MOUSE_EVENTS", value: "0");
5251 SDL_SetHint(name: "SDL_MOUSE_TOUCH_EVENTS", value: "0");
5252
5253 // Support longer IME composition strings (enables SDL_TEXTEDITING_EXT).
5254#if SDL_VERSION_ATLEAST(2, 0, 22)
5255 SDL_SetHint(SDL_HINT_IME_SUPPORT_EXTENDED_TEXT, value: "1");
5256#endif
5257
5258#if defined(CONF_FAMILY_WINDOWS)
5259 SDL_SetHint("SDL_IME_SHOW_UI", g_Config.m_InpImeNativeUi ? "1" : "0");
5260#else
5261 SDL_SetHint(name: "SDL_IME_SHOW_UI", value: "1");
5262#endif
5263
5264#if defined(CONF_PLATFORM_ANDROID)
5265 // Trap the Android back button so it can be handled in our code reliably
5266 // instead of letting the system handle it.
5267 SDL_SetHint("SDL_ANDROID_TRAP_BACK_BUTTON", "1");
5268#endif
5269#if defined(CONF_PLATFORM_ANDROID) || defined(CONF_PLATFORM_IOS)
5270 // Force landscape screen orientation.
5271 SDL_SetHint("SDL_IOS_ORIENTATIONS", "LandscapeLeft LandscapeRight");
5272#endif
5273
5274 // init SDL
5275 if(SDL_Init(flags: 0) < 0)
5276 {
5277 char aError[256];
5278 str_format(buffer: aError, buffer_size: sizeof(aError), format: "Unable to initialize SDL base: %s", SDL_GetError());
5279 log_error("client", "%s", aError);
5280 pClient->ShowMessageBox(MessageBox: {.m_pTitle = "SDL Error", .m_pMessage = aError});
5281 PerformAllCleanup();
5282 return -1;
5283 }
5284
5285 // SDL raises the timer resolution on Windows while initializing, the other platforms need this.
5286 thread_request_precise_wakeups();
5287
5288 // run the client
5289 log_trace("client", "initialization finished after %.2fms, starting...", (time_get() - MainStart) * 1000.0f / (float)time_freq());
5290 pClient->Run();
5291
5292 const bool Restarting = pClient->State() == CClient::STATE_RESTARTING;
5293#if !defined(CONF_PLATFORM_ANDROID)
5294 char aRestartBinaryPath[IO_MAX_PATH_LENGTH];
5295 if(Restarting)
5296 {
5297 pStorage->GetBinaryPath(PLAT_CLIENT_EXEC, pBuffer: aRestartBinaryPath, BufferSize: sizeof(aRestartBinaryPath));
5298 }
5299#endif
5300
5301 std::vector<SWarning> vQuittingWarnings = pClient->QuittingWarnings();
5302
5303 PerformCleanup();
5304
5305 for(const SWarning &Warning : vQuittingWarnings)
5306 {
5307 ShowMessageBoxWithoutGraphics(MessageBox: {.m_pTitle = Warning.m_aWarningTitle, .m_pMessage = Warning.m_aWarningMsg});
5308 }
5309
5310 if(Restarting)
5311 {
5312#if defined(CONF_PLATFORM_ANDROID)
5313 RestartAndroidApp();
5314#else
5315 process_execute(file: aRestartBinaryPath, window_state: EShellExecuteWindowState::FOREGROUND);
5316#endif
5317 }
5318
5319 PerformFinalCleanup();
5320
5321 return 0;
5322}
5323
5324// DDRace
5325
5326void CClient::RaceRecord_Start(const char *pFilename)
5327{
5328 dbg_assert(State() == IClient::STATE_ONLINE, "Client must be online to record demo");
5329
5330 DemoRecorders()[RECORDER_RACE].Start(
5331 pStorage: Storage(),
5332 pFilename,
5333 pNetversion: IsSixup() ? GameClient()->NetVersion7() : GameClient()->NetVersion(),
5334 pMap: GameClient()->Map()->BaseName(),
5335 Sha256: GameClient()->Map()->Sha256(),
5336 MapCrc: GameClient()->Map()->Crc(),
5337 pType: "client",
5338 MapSize: GameClient()->Map()->Size(),
5339 pMapData: nullptr,
5340 MapFile: GameClient()->Map()->File(),
5341 pfnFilter: nullptr,
5342 pUser: nullptr);
5343}
5344
5345void CClient::RaceRecord_Stop()
5346{
5347 if(DemoRecorder(Recorder: RECORDER_RACE)->IsRecording())
5348 {
5349 DemoRecorder(Recorder: RECORDER_RACE)->Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
5350 }
5351}
5352
5353bool CClient::RaceRecord_IsRecording()
5354{
5355 return DemoRecorder(Recorder: RECORDER_RACE)->IsRecording();
5356}
5357
5358void CClient::RequestDDNetInfo()
5359{
5360 if(m_pDDNetInfoTask && !m_pDDNetInfoTask->Done())
5361 return;
5362
5363 char aUrl[256];
5364 str_copy(dst&: aUrl, src: DDNET_INFO_URL);
5365
5366 if(g_Config.m_BrIndicateFinished)
5367 {
5368 char aEscaped[128];
5369 EscapeUrl(aBuf&: aEscaped, pStr: PlayerName());
5370 str_append(dst&: aUrl, src: "?name=");
5371 str_append(dst&: aUrl, src: aEscaped);
5372 }
5373
5374 m_pDDNetInfoTask = HttpGetFile(pUrl: aUrl, pStorage: Storage(), pOutputFile: DDNET_INFO_FILE, StorageType: IStorage::TYPE_SAVE);
5375 m_pDDNetInfoTask->Timeout(Timeout: CTimeout{.m_ConnectTimeoutMs: 10000, .m_TimeoutMs: 0, .m_LowSpeedLimit: 500, .m_LowSpeedTime: 10});
5376 m_pDDNetInfoTask->SkipByFileTime(SkipByFileTime: false); // Always re-download.
5377 // Use ipv4 so we can know the ingame ip addresses of players before they join game servers
5378 m_pDDNetInfoTask->IpResolve(IpResolve: IPRESOLVE::V4);
5379 Http()->Run(pRequest: m_pDDNetInfoTask);
5380 m_InfoState = EInfoState::LOADING;
5381}
5382
5383int CClient::GetPredictionTime()
5384{
5385 int64_t Now = time_get();
5386 return (int)((m_PredictedTime.Get(Now) - m_aGameTime[g_Config.m_ClDummy].Get(Now)) * 1000 / (float)time_freq());
5387}
5388
5389int CClient::GetPredictionTick()
5390{
5391 int PredictionTick = GetPredictionTime() * GameTickSpeed() / 1000.0f;
5392
5393 int PredictionMin = g_Config.m_ClAntiPingLimit * GameTickSpeed() / 1000.0f;
5394
5395 if(g_Config.m_ClAntiPingLimit == 0)
5396 {
5397 float PredictionPercentage = 1 - g_Config.m_ClAntiPingPercent / 100.0f;
5398 PredictionMin = std::floor(x: PredictionTick * PredictionPercentage);
5399 }
5400
5401 if(PredictionMin > PredictionTick - 1)
5402 {
5403 PredictionMin = PredictionTick - 1;
5404 }
5405
5406 if(PredictionMin <= 0)
5407 return PredGameTick(Conn: g_Config.m_ClDummy);
5408
5409 PredictionTick = PredGameTick(Conn: g_Config.m_ClDummy) - PredictionMin;
5410
5411 if(PredictionTick < GameTick(Conn: g_Config.m_ClDummy) + 1)
5412 {
5413 PredictionTick = GameTick(Conn: g_Config.m_ClDummy) + 1;
5414 }
5415 return PredictionTick;
5416}
5417
5418void CClient::GetSmoothTick(int *pSmoothTick, float *pSmoothIntraTick, float MixAmount)
5419{
5420 int64_t GameTime = m_aGameTime[g_Config.m_ClDummy].Get(Now: time_get());
5421 int64_t PredTime = m_PredictedTime.Get(Now: time_get());
5422 int64_t SmoothTime = std::clamp(val: GameTime + (int64_t)(MixAmount * (PredTime - GameTime)), lo: GameTime, hi: PredTime);
5423
5424 *pSmoothTick = (int)(SmoothTime * GameTickSpeed() / time_freq()) + 1;
5425 *pSmoothIntraTick = (SmoothTime - (*pSmoothTick - 1) * time_freq() / GameTickSpeed()) / (float)(time_freq() / GameTickSpeed());
5426}
5427
5428void CClient::AddWarning(const SWarning &Warning)
5429{
5430 const std::unique_lock<std::mutex> Lock(m_WarningsMutex);
5431 m_vWarnings.emplace_back(args: Warning);
5432}
5433
5434std::optional<SWarning> CClient::CurrentWarning()
5435{
5436 const std::unique_lock<std::mutex> Lock(m_WarningsMutex);
5437 if(m_vWarnings.empty())
5438 {
5439 return std::nullopt;
5440 }
5441 else
5442 {
5443 std::optional<SWarning> Result = std::make_optional(t&: m_vWarnings[0]);
5444 m_vWarnings.erase(position: m_vWarnings.begin());
5445 return Result;
5446 }
5447}
5448
5449int CClient::MaxLatencyTicks() const
5450{
5451 return GameTickSpeed() + (PredictionMargin() * GameTickSpeed()) / 1000;
5452}
5453
5454int CClient::PredictionMargin() const
5455{
5456 return m_ServerCapabilities.m_SyncWeaponInput ? g_Config.m_ClPredictionMargin : 10;
5457}
5458
5459IClient::EConnectivity CClient::UdpConnectivity(int NetType)
5460{
5461 static const int NETTYPES[2] = {NETTYPE_IPV6, NETTYPE_IPV4};
5462 EConnectivity Connectivity = EConnectivity::UNKNOWN;
5463 for(int PossibleNetType : NETTYPES)
5464 {
5465 if((NetType & PossibleNetType) == 0)
5466 {
5467 continue;
5468 }
5469 NETADDR GlobalUdpAddr;
5470 EConnectivity NewConnectivity;
5471 const CONNECTIVITY NetworkConnectivity = m_aNetClient[CONN_MAIN].GetConnectivity(NetType: PossibleNetType, pGlobalAddr: &GlobalUdpAddr);
5472 switch(NetworkConnectivity)
5473 {
5474 case CONNECTIVITY::UNKNOWN:
5475 NewConnectivity = EConnectivity::UNKNOWN;
5476 break;
5477 case CONNECTIVITY::CHECKING:
5478 NewConnectivity = EConnectivity::CHECKING;
5479 break;
5480 case CONNECTIVITY::UNREACHABLE:
5481 NewConnectivity = EConnectivity::UNREACHABLE;
5482 break;
5483 case CONNECTIVITY::REACHABLE:
5484 NewConnectivity = EConnectivity::REACHABLE;
5485 break;
5486 case CONNECTIVITY::ADDRESS_KNOWN:
5487 GlobalUdpAddr.port = 0;
5488 if(m_HaveGlobalTcpAddr && NetType == (int)m_GlobalTcpAddr.type && net_addr_comp(a: &m_GlobalTcpAddr, b: &GlobalUdpAddr) != 0)
5489 {
5490 NewConnectivity = EConnectivity::DIFFERING_UDP_TCP_IP_ADDRESSES;
5491 break;
5492 }
5493 NewConnectivity = EConnectivity::REACHABLE;
5494 break;
5495 default:
5496 dbg_assert_failed("Invalid connectivity value: %d", (int)NetworkConnectivity);
5497 }
5498 Connectivity = std::max(a: Connectivity, b: NewConnectivity);
5499 }
5500 return Connectivity;
5501}
5502
5503static bool ViewLinkImpl(const char *pLink)
5504{
5505#if defined(CONF_PLATFORM_ANDROID) || defined(CONF_PLATFORM_IOS)
5506 if(SDL_OpenURL(pLink) == 0)
5507 {
5508 return true;
5509 }
5510 log_error("client", "Failed to open link '%s' (%s)", pLink, SDL_GetError());
5511 return false;
5512#else
5513 if(os_open_link(link: pLink))
5514 {
5515 return true;
5516 }
5517 log_error("client", "Failed to open link '%s'", pLink);
5518 return false;
5519#endif
5520}
5521
5522bool CClient::ViewLink(const char *pLink)
5523{
5524 if(!str_startswith(str: pLink, prefix: "https://"))
5525 {
5526 log_error("client", "Failed to open link '%s': only https-links are allowed", pLink);
5527 return false;
5528 }
5529 return ViewLinkImpl(pLink);
5530}
5531
5532bool CClient::ViewFile(const char *pFilename)
5533{
5534#if defined(CONF_PLATFORM_MACOS)
5535 return ViewLinkImpl(pFilename);
5536#else
5537 // Create a file link so the path can contain forward and
5538 // backward slashes. But the file link must be absolute.
5539 char aWorkingDir[IO_MAX_PATH_LENGTH];
5540 if(fs_is_relative_path(path: pFilename))
5541 {
5542 if(!fs_getcwd(buffer: aWorkingDir, buffer_size: sizeof(aWorkingDir)))
5543 {
5544 log_error("client", "Failed to open file '%s' (failed to get working directory)", pFilename);
5545 return false;
5546 }
5547 str_append(dst&: aWorkingDir, src: "/");
5548 }
5549 else
5550 {
5551 aWorkingDir[0] = '\0';
5552 }
5553
5554 char aFileLink[IO_MAX_PATH_LENGTH];
5555#if defined(CONF_PLATFORM_IOS)
5556 str_format(aFileLink, sizeof(aFileLink), "shareddocuments://%s%s", aWorkingDir, pFilename);
5557#else
5558 str_format(buffer: aFileLink, buffer_size: sizeof(aFileLink), format: "file://%s%s", aWorkingDir, pFilename);
5559#endif
5560 return ViewLinkImpl(pLink: aFileLink);
5561#endif
5562}
5563
5564#if defined(CONF_FAMILY_WINDOWS)
5565void CClient::ShellRegister()
5566{
5567 char aFullPath[IO_MAX_PATH_LENGTH];
5568 Storage()->GetBinaryPathAbsolute(PLAT_CLIENT_EXEC, aFullPath, sizeof(aFullPath));
5569 if(!aFullPath[0])
5570 {
5571 log_error("client", "Failed to register protocol and file extensions: could not determine absolute path");
5572 return;
5573 }
5574
5575 bool Updated = false;
5576 if(!windows_shell_register_protocol("ddnet", aFullPath, &Updated))
5577 log_error("client", "Failed to register ddnet protocol");
5578 if(!windows_shell_register_extension(".map", "Map File", GAME_NAME, aFullPath, &Updated))
5579 log_error("client", "Failed to register .map file extension");
5580 if(!windows_shell_register_extension(".demo", "Demo File", GAME_NAME, aFullPath, &Updated))
5581 log_error("client", "Failed to register .demo file extension");
5582 if(!windows_shell_register_application(GAME_NAME, aFullPath, &Updated))
5583 log_error("client", "Failed to register application");
5584 if(Updated)
5585 windows_shell_update();
5586}
5587
5588void CClient::ShellUnregister()
5589{
5590 char aFullPath[IO_MAX_PATH_LENGTH];
5591 Storage()->GetBinaryPathAbsolute(PLAT_CLIENT_EXEC, aFullPath, sizeof(aFullPath));
5592 if(!aFullPath[0])
5593 {
5594 log_error("client", "Failed to unregister protocol and file extensions: could not determine absolute path");
5595 return;
5596 }
5597
5598 bool Updated = false;
5599 if(!windows_shell_unregister_class("ddnet", &Updated))
5600 log_error("client", "Failed to unregister ddnet protocol");
5601 if(!windows_shell_unregister_class(GAME_NAME ".map", &Updated))
5602 log_error("client", "Failed to unregister .map file extension");
5603 if(!windows_shell_unregister_class(GAME_NAME ".demo", &Updated))
5604 log_error("client", "Failed to unregister .demo file extension");
5605 if(!windows_shell_unregister_application(aFullPath, &Updated))
5606 log_error("client", "Failed to unregister application");
5607 if(Updated)
5608 windows_shell_update();
5609}
5610#endif
5611
5612std::optional<int> CClient::ShowMessageBox(const IGraphics::CMessageBox &MessageBox)
5613{
5614 std::optional<int> Result = m_pGraphics == nullptr ? std::nullopt : m_pGraphics->ShowMessageBox(MessageBox);
5615 if(!Result)
5616 {
5617 Result = ShowMessageBoxWithoutGraphics(MessageBox);
5618 }
5619 return Result;
5620}
5621
5622void CClient::GetGpuInfoString(char (&aGpuInfo)[512])
5623{
5624#if defined(CONF_HEADLESS_CLIENT)
5625 if(m_pGraphics == nullptr || !m_pGraphics->IsBackendInitialized())
5626 {
5627 str_format(aGpuInfo, std::size(aGpuInfo),
5628 "Configured graphics backend: headless\n"
5629 "Graphics %s not yet initialized.",
5630 m_pGraphics == nullptr ? "were" : "backend was");
5631 }
5632 else
5633 {
5634 str_copy(aGpuInfo, "Configured graphics backend: headless");
5635 }
5636#else
5637 if(m_pGraphics == nullptr || !m_pGraphics->IsBackendInitialized())
5638 {
5639 str_format(buffer: aGpuInfo, buffer_size: std::size(aGpuInfo),
5640 format: "Configured graphics backend: %s %d.%d.%d\n"
5641 "Graphics %s not yet initialized.",
5642 g_Config.m_GfxBackend, g_Config.m_GfxGLMajor, g_Config.m_GfxGLMinor, g_Config.m_GfxGLPatch,
5643 m_pGraphics == nullptr ? "were" : "backend was");
5644 }
5645 else
5646 {
5647 str_format(buffer: aGpuInfo, buffer_size: std::size(aGpuInfo),
5648 format: "Configured graphics backend: %s %d.%d.%d\n"
5649 "GPU: %s - %s - %s\n"
5650 "Texture: %.2f MiB, "
5651 "Buffer: %.2f MiB, "
5652 "Streamed: %.2f MiB, "
5653 "Staging: %.2f MiB",
5654 g_Config.m_GfxBackend, g_Config.m_GfxGLMajor, g_Config.m_GfxGLMinor, g_Config.m_GfxGLPatch,
5655 m_pGraphics->GetVendorString(), m_pGraphics->GetRendererString(), m_pGraphics->GetVersionString(),
5656 m_pGraphics->TextureMemoryUsage() / 1024.0 / 1024.0,
5657 m_pGraphics->BufferMemoryUsage() / 1024.0 / 1024.0,
5658 m_pGraphics->StreamedMemoryUsage() / 1024.0 / 1024.0,
5659 m_pGraphics->StagingMemoryUsage() / 1024.0 / 1024.0);
5660 }
5661#endif
5662}
5663
5664void CClient::SetLoggers(std::shared_ptr<ILogger> &&pFileLogger, std::shared_ptr<ILogger> &&pStdoutLogger)
5665{
5666 m_pFileLogger = pFileLogger;
5667 m_pStdoutLogger = pStdoutLogger;
5668}
5669