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 "chat.h"
5
6#include <base/color.h>
7#include <base/io.h>
8#include <base/log.h>
9#include <base/log_color.h>
10#include <base/time.h>
11
12#include <engine/editor.h>
13#include <engine/graphics.h>
14#include <engine/keys.h>
15#include <engine/shared/config.h>
16#include <engine/shared/csv.h>
17#include <engine/textrender.h>
18
19#include <generated/protocol.h>
20#include <generated/protocol7.h>
21
22#include <game/client/animstate.h>
23#include <game/client/components/censor.h>
24#include <game/client/components/scoreboard.h>
25#include <game/client/components/skins.h>
26#include <game/client/components/sounds.h>
27#include <game/client/gameclient.h>
28#include <game/localization.h>
29
30char CChat::ms_aDisplayText[MAX_CHAT_LENGTH] = "";
31
32CChat::CLine::CLine()
33{
34 m_TextContainerIndex.Reset();
35 m_QuadContainerIndex = -1;
36}
37
38void CChat::CLine::Reset(CChat &This)
39{
40 This.TextRender()->DeleteTextContainer(TextContainerIndex&: m_TextContainerIndex);
41 This.Graphics()->DeleteQuadContainer(ContainerIndex&: m_QuadContainerIndex);
42 m_Initialized = false;
43 m_Time = 0;
44 m_aText[0] = '\0';
45 m_aName[0] = '\0';
46 m_Friend = false;
47 m_TimesRepeated = 0;
48 m_pManagedTeeRenderInfo = nullptr;
49}
50
51CChat::CChat()
52{
53 m_Mode = MODE_NONE;
54
55 m_Input.SetCalculateOffsetCallback([this]() { return m_IsInputCensored; });
56 m_Input.SetDisplayTextCallback([this](char *pStr, size_t NumChars) {
57 m_IsInputCensored = false;
58 if(
59 g_Config.m_ClStreamerMode &&
60 (str_startswith(str: pStr, prefix: "/login ") ||
61 str_startswith(str: pStr, prefix: "/register ") ||
62 str_startswith(str: pStr, prefix: "/code ") ||
63 str_startswith(str: pStr, prefix: "/timeout ") ||
64 str_startswith(str: pStr, prefix: "/save ") ||
65 str_startswith(str: pStr, prefix: "/load ")))
66 {
67 bool Censor = false;
68 const size_t NumLetters = std::min(a: NumChars, b: sizeof(ms_aDisplayText) - 1);
69 for(size_t i = 0; i < NumLetters; ++i)
70 {
71 if(Censor)
72 ms_aDisplayText[i] = '*';
73 else
74 ms_aDisplayText[i] = pStr[i];
75 if(pStr[i] == ' ')
76 {
77 Censor = true;
78 m_IsInputCensored = true;
79 }
80 }
81 ms_aDisplayText[NumLetters] = '\0';
82 return ms_aDisplayText;
83 }
84 return pStr;
85 });
86}
87
88void CChat::RegisterCommand(const char *pName, const char *pParams, const char *pHelpText)
89{
90 // Don't allow duplicate commands.
91 for(const auto &Command : m_vServerCommands)
92 if(str_comp(a: Command.m_aName, b: pName) == 0)
93 return;
94
95 m_vServerCommands.emplace_back(args&: pName, args&: pParams, args&: pHelpText);
96 m_ServerCommandsNeedSorting = true;
97}
98
99void CChat::UnregisterCommand(const char *pName)
100{
101 m_vServerCommands.erase(first: std::remove_if(first: m_vServerCommands.begin(), last: m_vServerCommands.end(), pred: [pName](const CCommand &Command) { return str_comp(a: Command.m_aName, b: pName) == 0; }), last: m_vServerCommands.end());
102}
103
104void CChat::RebuildChat()
105{
106 for(auto &Line : m_aLines)
107 {
108 if(!Line.m_Initialized)
109 continue;
110 TextRender()->DeleteTextContainer(TextContainerIndex&: Line.m_TextContainerIndex);
111 Graphics()->DeleteQuadContainer(ContainerIndex&: Line.m_QuadContainerIndex);
112 // recalculate sizes
113 Line.m_aYOffset[0] = -1.0f;
114 Line.m_aYOffset[1] = -1.0f;
115 }
116}
117
118void CChat::ClearLines()
119{
120 for(auto &Line : m_aLines)
121 Line.Reset(This&: *this);
122 m_PrevScoreBoardShowed = false;
123 m_PrevShowChat = false;
124}
125
126void CChat::OnWindowResize()
127{
128 RebuildChat();
129}
130
131void CChat::Reset()
132{
133 ClearLines();
134
135 m_Show = false;
136 m_CompletionUsed = false;
137 m_CompletionChosen = -1;
138 m_aCompletionBuffer[0] = 0;
139 m_PlaceholderOffset = 0;
140 m_PlaceholderLength = 0;
141 m_pHistoryEntry = nullptr;
142 m_PendingChatCounter = 0;
143 m_LastChatSend = 0;
144 m_CurrentLine = 0;
145 m_IsInputCensored = false;
146 m_EditingNewLine = true;
147 m_ServerSupportsCommandInfo = false;
148 m_ServerCommandsNeedSorting = false;
149 m_aCurrentInputText[0] = '\0';
150 DisableMode();
151 m_vServerCommands.clear();
152 std::fill(first: std::begin(arr&: m_aLastSoundPlayed), last: std::end(arr&: m_aLastSoundPlayed), value: 0);
153}
154
155void CChat::OnRelease()
156{
157 m_Show = false;
158}
159
160void CChat::OnStateChange(int NewState, int OldState)
161{
162 if(OldState <= IClient::STATE_CONNECTING)
163 Reset();
164}
165
166void CChat::ConSay(IConsole::IResult *pResult, void *pUserData)
167{
168 ((CChat *)pUserData)->SendChat(Team: 0, pLine: pResult->GetString(Index: 0));
169}
170
171void CChat::ConSayTeam(IConsole::IResult *pResult, void *pUserData)
172{
173 ((CChat *)pUserData)->SendChat(Team: 1, pLine: pResult->GetString(Index: 0));
174}
175
176void CChat::ConChat(IConsole::IResult *pResult, void *pUserData)
177{
178 const char *pMode = pResult->GetString(Index: 0);
179 if(str_comp(a: pMode, b: "all") == 0)
180 ((CChat *)pUserData)->EnableMode(Team: 0);
181 else if(str_comp(a: pMode, b: "team") == 0)
182 ((CChat *)pUserData)->EnableMode(Team: 1);
183 else
184 log_error("chat", "expected all or team as mode");
185
186 if(pResult->GetString(Index: 1)[0] || g_Config.m_ClChatReset)
187 ((CChat *)pUserData)->m_Input.Set(pResult->GetString(Index: 1));
188}
189
190void CChat::ConShowChat(IConsole::IResult *pResult, void *pUserData)
191{
192 ((CChat *)pUserData)->m_Show = pResult->GetInteger(Index: 0) != 0;
193}
194
195void CChat::ConEcho(IConsole::IResult *pResult, void *pUserData)
196{
197 ((CChat *)pUserData)->Echo(pString: pResult->GetString(Index: 0));
198}
199
200void CChat::ConEchoConfig(IConsole::IResult *pResult, void *pUserData)
201{
202 ((CChat *)pUserData)->EchoConfig(pName: pResult->GetString(Index: 0));
203}
204
205void CChat::ConClearChat(IConsole::IResult *pResult, void *pUserData)
206{
207 ((CChat *)pUserData)->ClearLines();
208}
209
210void CChat::ConchainChatOld(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
211{
212 pfnCallback(pResult, pCallbackUserData);
213 ((CChat *)pUserData)->RebuildChat();
214}
215
216void CChat::ConchainChatFontSize(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
217{
218 pfnCallback(pResult, pCallbackUserData);
219 CChat *pChat = (CChat *)pUserData;
220 pChat->EnsureCoherentWidth();
221 pChat->RebuildChat();
222}
223
224void CChat::ConchainChatWidth(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
225{
226 pfnCallback(pResult, pCallbackUserData);
227 CChat *pChat = (CChat *)pUserData;
228 pChat->EnsureCoherentFontSize();
229 pChat->RebuildChat();
230}
231
232void CChat::Echo(const char *pString)
233{
234 AddLine(ClientId: CLIENT_MSG, Team: 0, pLine: pString);
235}
236
237void CChat::EchoConfig(const char *pName)
238{
239 char aBuf[2048];
240 const SConfigVariable *pVariable = GameClient()->ConfigManager()->FindVariable(pScriptName: pName);
241 if(pVariable == nullptr)
242 {
243 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Invalid config variable: %s", pName);
244 }
245 else
246 {
247 pVariable->SerializeHumanReadable(pOut: aBuf, Size: sizeof(aBuf));
248 }
249 Echo(pString: aBuf);
250}
251
252void CChat::OnConsoleInit()
253{
254 Console()->Register(pName: "say", pParams: "r[message]", Flags: CFGFLAG_CLIENT, pfnFunc: ConSay, pUser: this, pHelp: "Say in chat");
255 Console()->Register(pName: "say_team", pParams: "r[message]", Flags: CFGFLAG_CLIENT, pfnFunc: ConSayTeam, pUser: this, pHelp: "Say in team chat");
256 Console()->Register(pName: "chat", pParams: "s['team'|'all'] ?r[message]", Flags: CFGFLAG_CLIENT, pfnFunc: ConChat, pUser: this, pHelp: "Enable chat with all/team mode");
257 Console()->Register(pName: "+show_chat", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConShowChat, pUser: this, pHelp: "Show chat");
258 Console()->Register(pName: "echo", pParams: "r[message]", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: ConEcho, pUser: this, pHelp: "Echo the text in chat window");
259 Console()->Register(pName: "echo_config", pParams: "r[config]", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: ConEchoConfig, pUser: this, pHelp: "Echo the config value in chat window");
260 Console()->Register(pName: "clear_chat", pParams: "", Flags: CFGFLAG_CLIENT | CFGFLAG_STORE, pfnFunc: ConClearChat, pUser: this, pHelp: "Clear chat messages");
261}
262
263void CChat::OnInit()
264{
265 Reset();
266 Console()->Chain(pName: "cl_chat_old", pfnChainFunc: ConchainChatOld, pUser: this);
267 Console()->Chain(pName: "cl_chat_size", pfnChainFunc: ConchainChatFontSize, pUser: this);
268 Console()->Chain(pName: "cl_chat_width", pfnChainFunc: ConchainChatWidth, pUser: this);
269}
270
271bool CChat::OnInput(const IInput::CEvent &Event)
272{
273 if(m_Mode == MODE_NONE)
274 return false;
275
276 if(Event.m_Flags & IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE)
277 {
278 DisableMode();
279 GameClient()->OnRelease();
280 if(g_Config.m_ClChatReset)
281 {
282 m_Input.Clear();
283 m_pHistoryEntry = nullptr;
284 m_EditingNewLine = true;
285 }
286 }
287 else if(Event.m_Flags & IInput::FLAG_PRESS && (Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER))
288 {
289 if(m_ServerCommandsNeedSorting)
290 {
291 std::sort(first: m_vServerCommands.begin(), last: m_vServerCommands.end());
292 m_ServerCommandsNeedSorting = false;
293 }
294
295 SendChatQueued(pLine: m_Input.GetString());
296 m_pHistoryEntry = nullptr;
297 m_EditingNewLine = true;
298 DisableMode();
299 GameClient()->OnRelease();
300 m_Input.Clear();
301 }
302 if(Event.m_Flags & IInput::FLAG_PRESS && Event.m_Key == KEY_TAB)
303 {
304 const bool ShiftPressed = Input()->ShiftIsPressed();
305
306 // fill the completion buffer
307 if(!m_CompletionUsed)
308 {
309 const char *pCursor = m_Input.GetString() + m_Input.GetCursorOffset();
310 for(size_t Count = 0; Count < m_Input.GetCursorOffset() && *(pCursor - 1) != ' '; --pCursor, ++Count)
311 ;
312 m_PlaceholderOffset = pCursor - m_Input.GetString();
313
314 for(m_PlaceholderLength = 0; *pCursor && *pCursor != ' '; ++pCursor)
315 ++m_PlaceholderLength;
316
317 str_truncate(dst: m_aCompletionBuffer, dst_size: sizeof(m_aCompletionBuffer), src: m_Input.GetString() + m_PlaceholderOffset, truncation_len: m_PlaceholderLength);
318 }
319
320 if(!m_CompletionUsed && m_aCompletionBuffer[0] != '/')
321 {
322 // Create the completion list of player names through which the player can iterate
323 const char *PlayerName, *FoundInput;
324 m_PlayerCompletionListLength = 0;
325 for(auto &PlayerInfo : GameClient()->m_Snap.m_apInfoByName)
326 {
327 if(PlayerInfo)
328 {
329 PlayerName = GameClient()->m_aClients[PlayerInfo->m_ClientId].m_aName;
330 FoundInput = str_utf8_find_nocase(haystack: PlayerName, needle: m_aCompletionBuffer);
331 if(FoundInput != nullptr)
332 {
333 m_aPlayerCompletionList[m_PlayerCompletionListLength].m_ClientId = PlayerInfo->m_ClientId;
334 // The score for suggesting a player name is determined by the distance of the search input to the beginning of the player name
335 m_aPlayerCompletionList[m_PlayerCompletionListLength].m_Score = (int)(FoundInput - PlayerName);
336 m_PlayerCompletionListLength++;
337 }
338 }
339 }
340 std::stable_sort(first: m_aPlayerCompletionList, last: m_aPlayerCompletionList + m_PlayerCompletionListLength,
341 comp: [](const CRateablePlayer &Player1, const CRateablePlayer &Player2) -> bool {
342 return Player1.m_Score < Player2.m_Score;
343 });
344 }
345
346 if(m_aCompletionBuffer[0] == '/' && !m_vServerCommands.empty())
347 {
348 CCommand *pCompletionCommand = nullptr;
349
350 const size_t NumCommands = m_vServerCommands.size();
351
352 if(ShiftPressed && m_CompletionUsed)
353 m_CompletionChosen--;
354 else if(!ShiftPressed)
355 m_CompletionChosen++;
356 m_CompletionChosen = (m_CompletionChosen + 2 * NumCommands) % (2 * NumCommands);
357
358 m_CompletionUsed = true;
359
360 const char *pCommandStart = m_aCompletionBuffer + 1;
361 for(size_t i = 0; i < 2 * NumCommands; ++i)
362 {
363 int SearchType;
364 int Index;
365
366 if(ShiftPressed)
367 {
368 SearchType = ((m_CompletionChosen - i + 2 * NumCommands) % (2 * NumCommands)) / NumCommands;
369 Index = (m_CompletionChosen - i + NumCommands) % NumCommands;
370 }
371 else
372 {
373 SearchType = ((m_CompletionChosen + i) % (2 * NumCommands)) / NumCommands;
374 Index = (m_CompletionChosen + i) % NumCommands;
375 }
376
377 auto &Command = m_vServerCommands[Index];
378
379 if(str_startswith_nocase(str: Command.m_aName, prefix: pCommandStart))
380 {
381 pCompletionCommand = &Command;
382 m_CompletionChosen = Index + SearchType * NumCommands;
383 break;
384 }
385 }
386
387 // insert the command
388 if(pCompletionCommand)
389 {
390 char aBuf[MAX_CHAT_LENGTH];
391 // add part before the name
392 str_truncate(dst: aBuf, dst_size: sizeof(aBuf), src: m_Input.GetString(), truncation_len: m_PlaceholderOffset);
393
394 // add the command
395 str_append(dst&: aBuf, src: "/");
396 str_append(dst&: aBuf, src: pCompletionCommand->m_aName);
397
398 // add separator
399 const char *pSeparator = pCompletionCommand->m_aParams[0] == '\0' ? "" : " ";
400 str_append(dst&: aBuf, src: pSeparator);
401
402 // add part after the name
403 str_append(dst&: aBuf, src: m_Input.GetString() + m_PlaceholderOffset + m_PlaceholderLength);
404
405 m_PlaceholderLength = str_length(str: pSeparator) + str_length(str: pCompletionCommand->m_aName) + 1;
406 m_Input.Set(aBuf);
407 m_Input.SetCursorOffset(m_PlaceholderOffset + m_PlaceholderLength);
408 }
409 }
410 else
411 {
412 // find next possible name
413 const char *pCompletionString = nullptr;
414 if(m_PlayerCompletionListLength > 0)
415 {
416 // We do this in a loop, if a player left the game during the repeated pressing of Tab, they are skipped
417 CGameClient::CClientData *pCompletionClientData;
418 for(int i = 0; i < m_PlayerCompletionListLength; ++i)
419 {
420 if(ShiftPressed && m_CompletionUsed)
421 {
422 m_CompletionChosen--;
423 }
424 else if(!ShiftPressed)
425 {
426 m_CompletionChosen++;
427 }
428 if(m_CompletionChosen < 0)
429 {
430 m_CompletionChosen += m_PlayerCompletionListLength;
431 }
432 m_CompletionChosen %= m_PlayerCompletionListLength;
433 m_CompletionUsed = true;
434
435 pCompletionClientData = &GameClient()->m_aClients[m_aPlayerCompletionList[m_CompletionChosen].m_ClientId];
436 if(!pCompletionClientData->m_Active)
437 {
438 continue;
439 }
440
441 pCompletionString = pCompletionClientData->m_aName;
442 break;
443 }
444 }
445
446 // insert the name
447 if(pCompletionString)
448 {
449 char aBuf[MAX_CHAT_LENGTH];
450 // add part before the name
451 str_truncate(dst: aBuf, dst_size: sizeof(aBuf), src: m_Input.GetString(), truncation_len: m_PlaceholderOffset);
452
453 // quote the name
454 char aQuoted[128];
455 if(m_Input.GetString()[0] == '/' && (str_find(haystack: pCompletionString, needle: " ") || str_find(haystack: pCompletionString, needle: "\"")))
456 {
457 // escape the name
458 str_copy(dst&: aQuoted, src: "\"");
459 char *pDst = aQuoted + str_length(str: aQuoted);
460 str_escape(dst: &pDst, src: pCompletionString, end: aQuoted + sizeof(aQuoted));
461 str_append(dst&: aQuoted, src: "\"");
462
463 pCompletionString = aQuoted;
464 }
465
466 // add the name
467 str_append(dst&: aBuf, src: pCompletionString);
468
469 // add separator
470 const char *pSeparator = "";
471 if(*(m_Input.GetString() + m_PlaceholderOffset + m_PlaceholderLength) != ' ')
472 pSeparator = m_PlaceholderOffset == 0 ? ": " : " ";
473 else if(m_PlaceholderOffset == 0)
474 pSeparator = ":";
475 if(*pSeparator)
476 str_append(dst&: aBuf, src: pSeparator);
477
478 // add part after the name
479 str_append(dst&: aBuf, src: m_Input.GetString() + m_PlaceholderOffset + m_PlaceholderLength);
480
481 m_PlaceholderLength = str_length(str: pSeparator) + str_length(str: pCompletionString);
482 m_Input.Set(aBuf);
483 m_Input.SetCursorOffset(m_PlaceholderOffset + m_PlaceholderLength);
484 }
485 }
486 }
487 else
488 {
489 // reset name completion process
490 if(Event.m_Flags & IInput::FLAG_PRESS && Event.m_Key != KEY_TAB && Event.m_Key != KEY_LSHIFT && Event.m_Key != KEY_RSHIFT)
491 {
492 m_CompletionChosen = -1;
493 m_CompletionUsed = false;
494 }
495
496 m_Input.ProcessInput(Event);
497 }
498
499 if(Event.m_Flags & IInput::FLAG_PRESS && Event.m_Key == KEY_UP)
500 {
501 if(m_EditingNewLine)
502 {
503 str_copy(dst&: m_aCurrentInputText, src: m_Input.GetString());
504 m_EditingNewLine = false;
505 }
506
507 if(m_pHistoryEntry)
508 {
509 CHistoryEntry *pTest = m_History.Prev(pCurrent: m_pHistoryEntry);
510
511 if(pTest)
512 m_pHistoryEntry = pTest;
513 }
514 else
515 {
516 m_pHistoryEntry = m_History.Last();
517 }
518
519 if(m_pHistoryEntry)
520 m_Input.Set(m_pHistoryEntry->m_aText);
521 }
522 else if(Event.m_Flags & IInput::FLAG_PRESS && Event.m_Key == KEY_DOWN)
523 {
524 if(m_pHistoryEntry)
525 m_pHistoryEntry = m_History.Next(pCurrent: m_pHistoryEntry);
526
527 if(m_pHistoryEntry)
528 {
529 m_Input.Set(m_pHistoryEntry->m_aText);
530 }
531 else if(!m_EditingNewLine)
532 {
533 m_Input.Set(m_aCurrentInputText);
534 m_EditingNewLine = true;
535 }
536 }
537
538 return true;
539}
540
541void CChat::EnableMode(int Team)
542{
543 if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
544 return;
545
546 if(m_Mode == MODE_NONE)
547 {
548 if(Team)
549 m_Mode = MODE_TEAM;
550 else
551 m_Mode = MODE_ALL;
552
553 m_CompletionChosen = -1;
554 m_CompletionUsed = false;
555 m_Input.Activate(Priority: EInputPriority::CHAT);
556 }
557}
558
559void CChat::DisableMode()
560{
561 if(m_Mode != MODE_NONE)
562 {
563 m_Mode = MODE_NONE;
564 m_Input.Deactivate();
565 }
566}
567
568void CChat::OnMessage(int MsgType, void *pRawMsg)
569{
570 if(GameClient()->m_SuppressEvents)
571 return;
572
573 if(MsgType == NETMSGTYPE_SV_CHAT)
574 {
575 CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg;
576
577 /*
578 if(g_Config.m_ClCensorChat)
579 {
580 char aMessage[MAX_CHAT_LENGTH];
581 str_copy(aMessage, pMsg->m_pMessage);
582 GameClient()->m_Censor.CensorMessage(aMessage);
583 AddLine(pMsg->m_ClientId, pMsg->m_Team, aMessage);
584 }
585 else
586 AddLine(pMsg->m_ClientId, pMsg->m_Team, pMsg->m_pMessage);
587 */
588
589 AddLine(ClientId: pMsg->m_ClientId, Team: pMsg->m_Team, pLine: pMsg->m_pMessage);
590
591 if(Client()->State() != IClient::STATE_DEMOPLAYBACK &&
592 pMsg->m_ClientId == SERVER_MSG)
593 {
594 StoreSave(pText: pMsg->m_pMessage);
595 }
596 }
597 else if(MsgType == NETMSGTYPE_SV_COMMANDINFO)
598 {
599 CNetMsg_Sv_CommandInfo *pMsg = (CNetMsg_Sv_CommandInfo *)pRawMsg;
600 if(!m_ServerSupportsCommandInfo)
601 {
602 m_vServerCommands.clear();
603 m_ServerSupportsCommandInfo = true;
604 }
605 RegisterCommand(pName: pMsg->m_pName, pParams: pMsg->m_pArgsFormat, pHelpText: pMsg->m_pHelpText);
606 }
607 else if(MsgType == NETMSGTYPE_SV_COMMANDINFOREMOVE)
608 {
609 CNetMsg_Sv_CommandInfoRemove *pMsg = (CNetMsg_Sv_CommandInfoRemove *)pRawMsg;
610 UnregisterCommand(pName: pMsg->m_pName);
611 }
612}
613
614bool CChat::LineShouldHighlight(const char *pLine, const char *pName)
615{
616 const char *pHit = str_utf8_find_nocase(haystack: pLine, needle: pName);
617
618 while(pHit)
619 {
620 int Length = str_length(str: pName);
621
622 if(Length > 0 && (pLine == pHit || pHit[-1] == ' ') && (pHit[Length] == 0 || pHit[Length] == ' ' || pHit[Length] == '.' || pHit[Length] == '!' || pHit[Length] == ',' || pHit[Length] == '?' || pHit[Length] == ':'))
623 return true;
624
625 pHit = str_utf8_find_nocase(haystack: pHit + 1, needle: pName);
626 }
627
628 return false;
629}
630
631static constexpr const char *SAVES_HEADER[] = {
632 "Time",
633 "Player",
634 "Map",
635 "Code",
636};
637
638// TODO: remove this in a few releases (in 2027 or later)
639// it got deprecated by CGameClient::StoreSave
640void CChat::StoreSave(const char *pText)
641{
642 const char *pStart = str_find(haystack: pText, needle: "Team successfully saved by ");
643 const char *pMid = str_find(haystack: pText, needle: ". Use '/load ");
644 const char *pOn = str_find(haystack: pText, needle: "' on ");
645 const char *pEnd = str_find(haystack: pText, needle: pOn ? " to continue" : "' to continue");
646
647 if(!pStart || !pMid || !pEnd || pMid < pStart || pEnd < pMid || (pOn && (pOn < pMid || pEnd < pOn)))
648 return;
649
650 char aName[16];
651 str_truncate(dst: aName, dst_size: sizeof(aName), src: pStart + 27, truncation_len: pMid - pStart - 27);
652
653 char aSaveCode[64];
654
655 str_truncate(dst: aSaveCode, dst_size: sizeof(aSaveCode), src: pMid + 13, truncation_len: (pOn ? pOn : pEnd) - pMid - 13);
656
657 char aTimestamp[20];
658 str_timestamp_format(buffer: aTimestamp, buffer_size: sizeof(aTimestamp), format: TimestampFormat::SPACE);
659
660 const bool SavesFileExists = Storage()->FileExists(pFilename: SAVES_FILE, Type: IStorage::TYPE_SAVE);
661 IOHANDLE File = Storage()->OpenFile(pFilename: SAVES_FILE, Flags: IOFLAG_APPEND, Type: IStorage::TYPE_SAVE);
662 if(!File)
663 return;
664
665 const char *apColumns[4] = {
666 aTimestamp,
667 aName,
668 GameClient()->Map()->BaseName(),
669 aSaveCode,
670 };
671
672 if(!SavesFileExists)
673 {
674 CsvWrite(File, NumColumns: 4, ppColumns: SAVES_HEADER);
675 }
676 CsvWrite(File, NumColumns: 4, ppColumns: apColumns);
677 io_close(io: File);
678}
679
680void CChat::AddLine(int ClientId, int Team, const char *pLine)
681{
682 if(*pLine == 0 ||
683 (ClientId == SERVER_MSG && !g_Config.m_ClShowChatSystem) ||
684 (ClientId >= 0 && (GameClient()->m_aClients[ClientId].m_aName[0] == '\0' || // unknown client
685 GameClient()->m_aClients[ClientId].m_ChatIgnore ||
686 (GameClient()->m_Snap.m_LocalClientId != ClientId && g_Config.m_ClShowChatFriends && !GameClient()->m_aClients[ClientId].m_Friend) ||
687 (GameClient()->m_Snap.m_LocalClientId != ClientId && g_Config.m_ClShowChatTeamMembersOnly && GameClient()->IsOtherTeam(ClientId) && GameClient()->m_Teams.Team(ClientId: GameClient()->m_Snap.m_LocalClientId) != TEAM_FLOCK) ||
688 (GameClient()->m_Snap.m_LocalClientId != ClientId && GameClient()->m_aClients[ClientId].m_Foe))))
689 return;
690
691 // trim right and set maximum length to 256 utf8-characters
692 int Length = 0;
693 const char *pStr = pLine;
694 const char *pEnd = nullptr;
695 while(*pStr)
696 {
697 const char *pStrOld = pStr;
698 int Code = str_utf8_decode(ptr: &pStr);
699
700 // check if unicode is not empty
701 if(!str_utf8_isspace(code: Code))
702 {
703 pEnd = nullptr;
704 }
705 else if(pEnd == nullptr)
706 {
707 pEnd = pStrOld;
708 }
709
710 if(++Length >= MAX_CHAT_LENGTH)
711 {
712 *(const_cast<char *>(pStr)) = '\0';
713 break;
714 }
715 }
716 if(pEnd != nullptr)
717 *(const_cast<char *>(pEnd)) = '\0';
718
719 if(*pLine == 0)
720 return;
721
722 bool Highlighted = false;
723
724 auto &&FChatMsgCheckAndPrint = [](const CLine &Line) {
725 ColorRGBA ChatLogColor = ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f);
726 if(Line.m_Highlighted)
727 {
728 ChatLogColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageHighlightColor));
729 }
730 else
731 {
732 if(Line.m_Friend && g_Config.m_ClMessageFriend)
733 ChatLogColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageFriendColor));
734 else if(Line.m_Team)
735 ChatLogColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageTeamColor));
736 else if(Line.m_ClientId == SERVER_MSG)
737 ChatLogColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageSystemColor));
738 else if(Line.m_ClientId == CLIENT_MSG)
739 ChatLogColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageClientColor));
740 else // regular message
741 ChatLogColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageColor));
742 }
743
744 const char *pFrom;
745 if(Line.m_Whisper)
746 pFrom = "chat/whisper";
747 else if(Line.m_Team)
748 pFrom = "chat/team";
749 else if(Line.m_ClientId == SERVER_MSG)
750 pFrom = "chat/server";
751 else if(Line.m_ClientId == CLIENT_MSG)
752 pFrom = "chat/client";
753 else
754 pFrom = "chat/all";
755
756 log_info_color(color_cast<LOG_COLOR>(ChatLogColor), pFrom, "%s%s%s", Line.m_aName, Line.m_ClientId >= 0 ? ": " : "", Line.m_aText);
757 };
758
759 // Custom color for new line
760 std::optional<ColorRGBA> CustomColor = std::nullopt;
761 if(ClientId == CLIENT_MSG)
762 CustomColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageClientColor));
763
764 CLine &PreviousLine = m_aLines[m_CurrentLine];
765
766 // Team Number:
767 // 0 = global; 1 = team; 2 = sending whisper; 3 = receiving whisper
768
769 // If it's a client message, m_aText will have ": " prepended so we have to work around it.
770 if(PreviousLine.m_Initialized &&
771 PreviousLine.m_TeamNumber == Team &&
772 PreviousLine.m_ClientId == ClientId &&
773 str_comp(a: PreviousLine.m_aText, b: pLine) == 0 &&
774 PreviousLine.m_CustomColor == CustomColor)
775 {
776 PreviousLine.m_TimesRepeated++;
777 TextRender()->DeleteTextContainer(TextContainerIndex&: PreviousLine.m_TextContainerIndex);
778 Graphics()->DeleteQuadContainer(ContainerIndex&: PreviousLine.m_QuadContainerIndex);
779 PreviousLine.m_Time = time();
780 PreviousLine.m_aYOffset[0] = -1.0f;
781 PreviousLine.m_aYOffset[1] = -1.0f;
782
783 FChatMsgCheckAndPrint(PreviousLine);
784 return;
785 }
786
787 m_CurrentLine = (m_CurrentLine + 1) % MAX_LINES;
788
789 CLine &CurrentLine = m_aLines[m_CurrentLine];
790 CurrentLine.Reset(This&: *this);
791 CurrentLine.m_Initialized = true;
792 CurrentLine.m_Time = time();
793 CurrentLine.m_aYOffset[0] = -1.0f;
794 CurrentLine.m_aYOffset[1] = -1.0f;
795 CurrentLine.m_ClientId = ClientId;
796 CurrentLine.m_TeamNumber = Team;
797 CurrentLine.m_Team = Team == 1;
798 CurrentLine.m_Whisper = Team >= 2;
799 CurrentLine.m_NameColor = -2;
800 CurrentLine.m_CustomColor = CustomColor;
801
802 // check for highlighted name
803 if(Client()->State() != IClient::STATE_DEMOPLAYBACK)
804 {
805 if(ClientId >= 0 && ClientId != GameClient()->m_aLocalIds[0] && ClientId != GameClient()->m_aLocalIds[1])
806 {
807 for(int LocalId : GameClient()->m_aLocalIds)
808 {
809 Highlighted |= LocalId >= 0 && LineShouldHighlight(pLine, pName: GameClient()->m_aClients[LocalId].m_aName);
810 }
811 }
812 }
813 else
814 {
815 // on demo playback use local id from snap directly,
816 // since m_aLocalIds isn't valid there
817 Highlighted |= GameClient()->m_Snap.m_LocalClientId >= 0 && LineShouldHighlight(pLine, pName: GameClient()->m_aClients[GameClient()->m_Snap.m_LocalClientId].m_aName);
818 }
819 CurrentLine.m_Highlighted = Highlighted;
820
821 str_copy(dst&: CurrentLine.m_aText, src: pLine);
822
823 if(CurrentLine.m_ClientId == SERVER_MSG)
824 {
825 str_copy(dst&: CurrentLine.m_aName, src: "*** ");
826 }
827 else if(CurrentLine.m_ClientId == CLIENT_MSG)
828 {
829 str_copy(dst&: CurrentLine.m_aName, src: "— ");
830 }
831 else
832 {
833 const auto &LineAuthor = GameClient()->m_aClients[CurrentLine.m_ClientId];
834
835 if(LineAuthor.m_Active)
836 {
837 if(LineAuthor.m_Team == TEAM_SPECTATORS)
838 CurrentLine.m_NameColor = TEAM_SPECTATORS;
839
840 if(GameClient()->IsTeamPlay())
841 {
842 if(LineAuthor.m_Team == TEAM_RED)
843 CurrentLine.m_NameColor = TEAM_RED;
844 else if(LineAuthor.m_Team == TEAM_BLUE)
845 CurrentLine.m_NameColor = TEAM_BLUE;
846 }
847 }
848
849 if(Team == TEAM_WHISPER_SEND)
850 {
851 str_copy(dst&: CurrentLine.m_aName, src: "→");
852 if(LineAuthor.m_Active)
853 {
854 str_append(dst&: CurrentLine.m_aName, src: " ");
855 str_append(dst&: CurrentLine.m_aName, src: LineAuthor.m_aName);
856 }
857 CurrentLine.m_NameColor = TEAM_BLUE;
858 CurrentLine.m_Highlighted = false;
859 Highlighted = false;
860 }
861 else if(Team == TEAM_WHISPER_RECV)
862 {
863 str_copy(dst&: CurrentLine.m_aName, src: "←");
864 if(LineAuthor.m_Active)
865 {
866 str_append(dst&: CurrentLine.m_aName, src: " ");
867 str_append(dst&: CurrentLine.m_aName, src: LineAuthor.m_aName);
868 }
869 CurrentLine.m_NameColor = TEAM_RED;
870 CurrentLine.m_Highlighted = true;
871 Highlighted = true;
872 }
873 else
874 {
875 str_copy(dst&: CurrentLine.m_aName, src: LineAuthor.m_aName);
876 }
877
878 if(LineAuthor.m_Active)
879 {
880 CurrentLine.m_Friend = LineAuthor.m_Friend;
881 CurrentLine.m_pManagedTeeRenderInfo = GameClient()->CreateManagedTeeRenderInfo(Client: LineAuthor);
882 }
883 }
884
885 FChatMsgCheckAndPrint(CurrentLine);
886
887 // play sound
888 int64_t Now = time();
889 if(ClientId == SERVER_MSG)
890 {
891 if(Now - m_aLastSoundPlayed[CHAT_SERVER] >= time_freq() * 3 / 10)
892 {
893 if(g_Config.m_SndServerMessage)
894 {
895 GameClient()->m_Sounds.Play(Channel: CSounds::CHN_GUI, SetId: SOUND_CHAT_SERVER, Volume: 1.0f);
896 m_aLastSoundPlayed[CHAT_SERVER] = Now;
897 }
898 }
899 }
900 else if(ClientId == CLIENT_MSG)
901 {
902 // No sound yet
903 }
904 else if(Highlighted && Client()->State() != IClient::STATE_DEMOPLAYBACK)
905 {
906 if(Now - m_aLastSoundPlayed[CHAT_HIGHLIGHT] >= time_freq() * 3 / 10)
907 {
908 char aBuf[1024];
909 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s: %s", CurrentLine.m_aName, CurrentLine.m_aText);
910 Client()->Notify(pTitle: "DDNet Chat", pMessage: aBuf);
911 if(g_Config.m_SndHighlight)
912 {
913 GameClient()->m_Sounds.Play(Channel: CSounds::CHN_GUI, SetId: SOUND_CHAT_HIGHLIGHT, Volume: 1.0f);
914 m_aLastSoundPlayed[CHAT_HIGHLIGHT] = Now;
915 }
916
917 if(g_Config.m_ClEditor)
918 {
919 GameClient()->Editor()->UpdateMentions();
920 }
921 }
922 }
923 else if(Team != TEAM_WHISPER_SEND)
924 {
925 if(Now - m_aLastSoundPlayed[CHAT_CLIENT] >= time_freq() * 3 / 10)
926 {
927 bool PlaySound = CurrentLine.m_Team ? g_Config.m_SndTeamChat : g_Config.m_SndChat;
928#if defined(CONF_VIDEORECORDER)
929 if(IVideo::Current())
930 {
931 PlaySound &= (bool)g_Config.m_ClVideoShowChat;
932 }
933#endif
934 if(PlaySound)
935 {
936 GameClient()->m_Sounds.Play(Channel: CSounds::CHN_GUI, SetId: SOUND_CHAT_CLIENT, Volume: 1.0f);
937 m_aLastSoundPlayed[CHAT_CLIENT] = Now;
938 }
939 }
940 }
941}
942
943void CChat::OnPrepareLines(float y)
944{
945 float x = 5.0f;
946 float FontSize = this->FontSize();
947
948 const bool IsScoreBoardOpen = GameClient()->m_Scoreboard.IsActive() && (Graphics()->ScreenAspect() > 1.7f); // only assume scoreboard when screen ratio is widescreen(something around 16:9)
949 const bool ShowLargeArea = m_Show || (m_Mode != MODE_NONE && g_Config.m_ClShowChat == 1) || g_Config.m_ClShowChat == 2;
950 const bool ForceRecreate = IsScoreBoardOpen != m_PrevScoreBoardShowed || ShowLargeArea != m_PrevShowChat;
951 m_PrevScoreBoardShowed = IsScoreBoardOpen;
952 m_PrevShowChat = ShowLargeArea;
953
954 const int TeeSize = MessageTeeSize();
955 float RealMsgPaddingX = MessagePaddingX();
956 float RealMsgPaddingY = MessagePaddingY();
957 float RealMsgPaddingTee = TeeSize + MESSAGE_TEE_PADDING_RIGHT;
958
959 if(g_Config.m_ClChatOld)
960 {
961 RealMsgPaddingX = 0;
962 RealMsgPaddingY = 0;
963 RealMsgPaddingTee = 0;
964 }
965
966 int64_t Now = time();
967 float LineWidth = (IsScoreBoardOpen ? std::max(a: 85.0f, b: FontSize * 85.0f / 6.0f) : g_Config.m_ClChatWidth) - (RealMsgPaddingX * 1.5f) - RealMsgPaddingTee;
968
969 float HeightLimit = IsScoreBoardOpen ? 180.0f : (m_PrevShowChat ? 50.0f : 200.0f);
970 float Begin = x;
971 float TextBegin = Begin + RealMsgPaddingX / 2.0f;
972 int OffsetType = IsScoreBoardOpen ? 1 : 0;
973
974 for(int i = 0; i < MAX_LINES; i++)
975 {
976 CLine &Line = m_aLines[((m_CurrentLine - i) + MAX_LINES) % MAX_LINES];
977 if(!Line.m_Initialized)
978 break;
979 if(Now > Line.m_Time + 16 * time_freq() && !m_PrevShowChat)
980 break;
981
982 if(Line.m_TextContainerIndex.Valid() && !ForceRecreate)
983 continue;
984
985 TextRender()->DeleteTextContainer(TextContainerIndex&: Line.m_TextContainerIndex);
986 Graphics()->DeleteQuadContainer(ContainerIndex&: Line.m_QuadContainerIndex);
987
988 char aClientId[16] = "";
989 if(g_Config.m_ClShowIds && Line.m_ClientId >= 0 && Line.m_aName[0] != '\0')
990 {
991 GameClient()->FormatClientId(ClientId: Line.m_ClientId, aClientId, Format: EClientIdFormat::INDENT_AUTO);
992 }
993
994 char aCount[12];
995 if(Line.m_ClientId < 0)
996 str_format(buffer: aCount, buffer_size: sizeof(aCount), format: "[%d] ", Line.m_TimesRepeated + 1);
997 else
998 str_format(buffer: aCount, buffer_size: sizeof(aCount), format: " [%d]", Line.m_TimesRepeated + 1);
999
1000 const char *pText = Line.m_aText;
1001 if(Config()->m_ClStreamerMode && Line.m_ClientId == SERVER_MSG)
1002 {
1003 if(str_startswith(str: Line.m_aText, prefix: "Team save in progress. You'll be able to load with '/load ") && str_endswith(str: Line.m_aText, suffix: "'"))
1004 {
1005 pText = "Team save in progress. You'll be able to load with '/load *** *** ***'";
1006 }
1007 else if(str_startswith(str: Line.m_aText, prefix: "Team save in progress. You'll be able to load with '/load") && str_endswith(str: Line.m_aText, suffix: "if it fails"))
1008 {
1009 pText = "Team save in progress. You'll be able to load with '/load *** *** ***' if save is successful or with '/load *** *** ***' if it fails";
1010 }
1011 else if(str_startswith(str: Line.m_aText, prefix: "Team successfully saved by ") && str_endswith(str: Line.m_aText, suffix: " to continue"))
1012 {
1013 pText = "Team successfully saved by ***. Use '/load *** *** ***' to continue";
1014 }
1015 }
1016
1017 // get the y offset (calculate it if we haven't done that yet)
1018 if(Line.m_aYOffset[OffsetType] < 0.0f)
1019 {
1020 CTextCursor MeasureCursor;
1021 MeasureCursor.SetPosition(vec2(TextBegin, 0.0f));
1022 MeasureCursor.m_FontSize = FontSize;
1023 MeasureCursor.m_Flags = 0;
1024 MeasureCursor.m_LineWidth = LineWidth;
1025
1026 if(Line.m_ClientId >= 0 && Line.m_aName[0] != '\0')
1027 {
1028 MeasureCursor.m_X += RealMsgPaddingTee;
1029
1030 if(Line.m_Friend && g_Config.m_ClMessageFriend)
1031 {
1032 TextRender()->TextEx(pCursor: &MeasureCursor, pText: "♥ ");
1033 }
1034 }
1035
1036 TextRender()->TextEx(pCursor: &MeasureCursor, pText: aClientId);
1037 TextRender()->TextEx(pCursor: &MeasureCursor, pText: Line.m_aName);
1038 if(Line.m_TimesRepeated > 0)
1039 TextRender()->TextEx(pCursor: &MeasureCursor, pText: aCount);
1040
1041 if(Line.m_ClientId >= 0 && Line.m_aName[0] != '\0')
1042 {
1043 TextRender()->TextEx(pCursor: &MeasureCursor, pText: ": ");
1044 }
1045
1046 CTextCursor AppendCursor = MeasureCursor;
1047 AppendCursor.m_LongestLineWidth = 0.0f;
1048 if(!IsScoreBoardOpen && !g_Config.m_ClChatOld)
1049 {
1050 AppendCursor.m_StartX = MeasureCursor.m_X;
1051 AppendCursor.m_LineWidth -= MeasureCursor.m_LongestLineWidth;
1052 }
1053
1054 TextRender()->TextEx(pCursor: &AppendCursor, pText);
1055
1056 Line.m_aYOffset[OffsetType] = AppendCursor.Height() + RealMsgPaddingY;
1057 }
1058
1059 y -= Line.m_aYOffset[OffsetType];
1060
1061 // cut off if msgs waste too much space
1062 if(y < HeightLimit)
1063 break;
1064
1065 // the position the text was created
1066 Line.m_TextYOffset = y + RealMsgPaddingY / 2.0f;
1067
1068 int CurRenderFlags = TextRender()->GetRenderFlags();
1069 TextRender()->SetRenderFlags(CurRenderFlags | ETextRenderFlags::TEXT_RENDER_FLAG_NO_AUTOMATIC_QUAD_UPLOAD);
1070
1071 // reset the cursor
1072 CTextCursor LineCursor;
1073 LineCursor.SetPosition(vec2(TextBegin, Line.m_TextYOffset));
1074 LineCursor.m_FontSize = FontSize;
1075 LineCursor.m_LineWidth = LineWidth;
1076
1077 // Message is from valid player
1078 if(Line.m_ClientId >= 0 && Line.m_aName[0] != '\0')
1079 {
1080 LineCursor.m_X += RealMsgPaddingTee;
1081
1082 if(Line.m_Friend && g_Config.m_ClMessageFriend)
1083 {
1084 TextRender()->TextColor(Color: color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageFriendColor)).WithAlpha(alpha: 1.0f));
1085 TextRender()->CreateOrAppendTextContainer(TextContainerIndex&: Line.m_TextContainerIndex, pCursor: &LineCursor, pText: "♥ ");
1086 }
1087 }
1088
1089 // render name
1090 ColorRGBA NameColor;
1091 if(Line.m_CustomColor)
1092 NameColor = *Line.m_CustomColor;
1093 else if(Line.m_ClientId == SERVER_MSG)
1094 NameColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageSystemColor));
1095 else if(Line.m_ClientId == CLIENT_MSG)
1096 NameColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageClientColor));
1097 else if(Line.m_Team)
1098 NameColor = CalculateNameColor(TextColorHSL: ColorHSLA(g_Config.m_ClMessageTeamColor));
1099 else if(Line.m_NameColor == TEAM_RED)
1100 NameColor = ColorRGBA(1.0f, 0.5f, 0.5f, 1.0f);
1101 else if(Line.m_NameColor == TEAM_BLUE)
1102 NameColor = ColorRGBA(0.7f, 0.7f, 1.0f, 1.0f);
1103 else if(Line.m_NameColor == TEAM_SPECTATORS)
1104 NameColor = ColorRGBA(0.75f, 0.5f, 0.75f, 1.0f);
1105 else if(Line.m_ClientId >= 0 && g_Config.m_ClChatTeamColors && GameClient()->m_Teams.Team(ClientId: Line.m_ClientId))
1106 NameColor = GameClient()->GetDDTeamColor(DDTeam: GameClient()->m_Teams.Team(ClientId: Line.m_ClientId), Lightness: 0.75f);
1107 else
1108 NameColor = ColorRGBA(0.8f, 0.8f, 0.8f, 1.0f);
1109
1110 TextRender()->TextColor(Color: NameColor);
1111 TextRender()->CreateOrAppendTextContainer(TextContainerIndex&: Line.m_TextContainerIndex, pCursor: &LineCursor, pText: aClientId);
1112 TextRender()->CreateOrAppendTextContainer(TextContainerIndex&: Line.m_TextContainerIndex, pCursor: &LineCursor, pText: Line.m_aName);
1113
1114 if(Line.m_TimesRepeated > 0)
1115 {
1116 TextRender()->TextColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 0.3f);
1117 TextRender()->CreateOrAppendTextContainer(TextContainerIndex&: Line.m_TextContainerIndex, pCursor: &LineCursor, pText: aCount);
1118 }
1119
1120 if(Line.m_ClientId >= 0 && Line.m_aName[0] != '\0')
1121 {
1122 TextRender()->TextColor(Color: NameColor);
1123 TextRender()->CreateOrAppendTextContainer(TextContainerIndex&: Line.m_TextContainerIndex, pCursor: &LineCursor, pText: ": ");
1124 }
1125
1126 ColorRGBA Color;
1127 if(Line.m_CustomColor)
1128 Color = *Line.m_CustomColor;
1129 else if(Line.m_ClientId == SERVER_MSG)
1130 Color = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageSystemColor));
1131 else if(Line.m_ClientId == CLIENT_MSG)
1132 Color = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageClientColor));
1133 else if(Line.m_Highlighted)
1134 Color = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageHighlightColor));
1135 else if(Line.m_Team)
1136 Color = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageTeamColor));
1137 else // regular message
1138 Color = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClMessageColor));
1139 TextRender()->TextColor(Color);
1140
1141 CTextCursor AppendCursor = LineCursor;
1142 AppendCursor.m_LongestLineWidth = 0.0f;
1143 if(!IsScoreBoardOpen && !g_Config.m_ClChatOld)
1144 {
1145 AppendCursor.m_StartX = LineCursor.m_X;
1146 AppendCursor.m_LineWidth -= LineCursor.m_LongestLineWidth;
1147 }
1148
1149 TextRender()->CreateOrAppendTextContainer(TextContainerIndex&: Line.m_TextContainerIndex, pCursor: &AppendCursor, pText);
1150
1151 if(!g_Config.m_ClChatOld && (Line.m_aText[0] != '\0' || Line.m_aName[0] != '\0'))
1152 {
1153 float FullWidth = RealMsgPaddingX * 1.5f;
1154 if(!IsScoreBoardOpen && !g_Config.m_ClChatOld)
1155 {
1156 FullWidth += LineCursor.m_LongestLineWidth + AppendCursor.m_LongestLineWidth;
1157 }
1158 else
1159 {
1160 FullWidth += std::max(a: LineCursor.m_LongestLineWidth, b: AppendCursor.m_LongestLineWidth);
1161 }
1162 Graphics()->SetColor(r: 1, g: 1, b: 1, a: 1);
1163 Line.m_QuadContainerIndex = Graphics()->CreateRectQuadContainer(x: Begin, y, w: FullWidth, h: Line.m_aYOffset[OffsetType], r: MessageRounding(), Corners: IGraphics::CORNER_ALL);
1164 }
1165
1166 TextRender()->SetRenderFlags(CurRenderFlags);
1167 if(Line.m_TextContainerIndex.Valid())
1168 TextRender()->UploadTextContainer(TextContainerIndex: Line.m_TextContainerIndex);
1169 }
1170
1171 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1172}
1173
1174void CChat::OnRender()
1175{
1176 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
1177 return;
1178
1179 // send pending chat messages
1180 if(m_PendingChatCounter > 0 && m_LastChatSend + time_freq() < time())
1181 {
1182 CHistoryEntry *pEntry = m_History.Last();
1183 for(int i = m_PendingChatCounter - 1; pEntry; --i, pEntry = m_History.Prev(pCurrent: pEntry))
1184 {
1185 if(i == 0)
1186 {
1187 SendChat(Team: pEntry->m_Team, pLine: pEntry->m_aText);
1188 break;
1189 }
1190 }
1191 --m_PendingChatCounter;
1192 }
1193
1194 const float Height = 300.0f;
1195 const float Width = Height * Graphics()->ScreenAspect();
1196 Graphics()->MapScreenToSize(Width, Height);
1197
1198 float x = 5.0f;
1199 float y = 300.0f - 20.0f * FontSize() / 6.0f;
1200 float ScaledFontSize = FontSize() * (8.0f / 6.0f);
1201 if(m_Mode != MODE_NONE)
1202 {
1203 // render chat input
1204 CTextCursor InputCursor;
1205 InputCursor.SetPosition(vec2(x, y));
1206 InputCursor.m_FontSize = ScaledFontSize;
1207 InputCursor.m_LineWidth = Width - 190.0f;
1208
1209 if(m_Mode == MODE_ALL)
1210 TextRender()->TextEx(pCursor: &InputCursor, pText: Localize(pStr: "All"));
1211 else if(m_Mode == MODE_TEAM)
1212 TextRender()->TextEx(pCursor: &InputCursor, pText: Localize(pStr: "Team"));
1213 else
1214 TextRender()->TextEx(pCursor: &InputCursor, pText: Localize(pStr: "Chat"));
1215
1216 TextRender()->TextEx(pCursor: &InputCursor, pText: ": ");
1217
1218 const float MessageMaxWidth = InputCursor.m_LineWidth - (InputCursor.m_X - InputCursor.m_StartX);
1219 const CUIRect ClippingRect = {.x: InputCursor.m_X, .y: InputCursor.m_Y, .w: MessageMaxWidth, .h: 2.25f * InputCursor.m_FontSize};
1220 const float XScale = Graphics()->ScreenWidth() / Width;
1221 const float YScale = Graphics()->ScreenHeight() / Height;
1222 Graphics()->ClipEnable(x: (int)(ClippingRect.x * XScale), y: (int)(ClippingRect.y * YScale), w: (int)(ClippingRect.w * XScale), h: (int)(ClippingRect.h * YScale));
1223
1224 float ScrollOffset = m_Input.GetScrollOffset();
1225 float ScrollOffsetChange = m_Input.GetScrollOffsetChange();
1226
1227 m_Input.Activate(Priority: EInputPriority::CHAT); // Ensure that the input is active
1228 const CUIRect InputCursorRect = {.x: InputCursor.m_X, .y: InputCursor.m_Y - ScrollOffset, .w: 0.0f, .h: 0.0f};
1229 const bool WasChanged = m_Input.WasChanged();
1230 const bool WasCursorChanged = m_Input.WasCursorChanged();
1231 const bool Changed = WasChanged || WasCursorChanged;
1232 const STextBoundingBox BoundingBox = m_Input.Render(pRect: &InputCursorRect, FontSize: InputCursor.m_FontSize, Align: TEXTALIGN_TL, Changed, LineWidth: MessageMaxWidth, LineSpacing: 0.0f);
1233
1234 Graphics()->ClipDisable();
1235
1236 // Scroll up or down to keep the caret inside the clipping rect
1237 const float CaretPositionY = m_Input.GetCaretPosition().y - ScrollOffsetChange;
1238 if(CaretPositionY < ClippingRect.y)
1239 ScrollOffsetChange -= ClippingRect.y - CaretPositionY;
1240 else if(CaretPositionY + InputCursor.m_FontSize > ClippingRect.y + ClippingRect.h)
1241 ScrollOffsetChange += CaretPositionY + InputCursor.m_FontSize - (ClippingRect.y + ClippingRect.h);
1242
1243 Ui()->DoSmoothScrollLogic(pScrollOffset: &ScrollOffset, pScrollOffsetChange: &ScrollOffsetChange, ViewPortSize: ClippingRect.h, TotalSize: BoundingBox.m_H);
1244
1245 m_Input.SetScrollOffset(ScrollOffset);
1246 m_Input.SetScrollOffsetChange(ScrollOffsetChange);
1247
1248 // Autocompletion hint
1249 if(m_Input.GetString()[0] == '/' && m_Input.GetString()[1] != '\0' && !m_vServerCommands.empty())
1250 {
1251 for(const auto &Command : m_vServerCommands)
1252 {
1253 if(str_startswith_nocase(str: Command.m_aName, prefix: m_Input.GetString() + 1))
1254 {
1255 InputCursor.m_X = InputCursor.m_X + TextRender()->TextWidth(Size: InputCursor.m_FontSize, pText: m_Input.GetString(), StrLength: -1, LineWidth: InputCursor.m_LineWidth);
1256 InputCursor.m_Y = m_Input.GetCaretPosition().y;
1257 TextRender()->TextColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 0.5f);
1258 TextRender()->TextEx(pCursor: &InputCursor, pText: Command.m_aName + str_length(str: m_Input.GetString() + 1));
1259 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1260 break;
1261 }
1262 }
1263 }
1264 }
1265
1266#if defined(CONF_VIDEORECORDER)
1267 if(!((g_Config.m_ClShowChat && !IVideo::Current()) || (g_Config.m_ClVideoShowChat && IVideo::Current())))
1268#else
1269 if(!g_Config.m_ClShowChat)
1270#endif
1271 return;
1272
1273 y -= ScaledFontSize;
1274
1275 OnPrepareLines(y);
1276
1277 bool IsScoreBoardOpen = GameClient()->m_Scoreboard.IsActive() && (Graphics()->ScreenAspect() > 1.7f); // only assume scoreboard when screen ratio is widescreen(something around 16:9)
1278
1279 int64_t Now = time();
1280 float HeightLimit = IsScoreBoardOpen ? 180.0f : (m_PrevShowChat ? 50.0f : 200.0f);
1281 int OffsetType = IsScoreBoardOpen ? 1 : 0;
1282
1283 float RealMsgPaddingX = MessagePaddingX();
1284 float RealMsgPaddingY = MessagePaddingY();
1285
1286 if(g_Config.m_ClChatOld)
1287 {
1288 RealMsgPaddingX = 0;
1289 RealMsgPaddingY = 0;
1290 }
1291
1292 for(int i = 0; i < MAX_LINES; i++)
1293 {
1294 CLine &Line = m_aLines[((m_CurrentLine - i) + MAX_LINES) % MAX_LINES];
1295 if(!Line.m_Initialized)
1296 break;
1297 if(Now > Line.m_Time + 16 * time_freq() && !m_PrevShowChat)
1298 break;
1299
1300 y -= Line.m_aYOffset[OffsetType];
1301
1302 // cut off if msgs waste too much space
1303 if(y < HeightLimit)
1304 break;
1305
1306 float Blend = Now > Line.m_Time + 14 * time_freq() && !m_PrevShowChat ? 1.0f - (Now - Line.m_Time - 14 * time_freq()) / (2.0f * time_freq()) : 1.0f;
1307
1308 // Draw backgrounds for messages in one batch
1309 if(!g_Config.m_ClChatOld)
1310 {
1311 Graphics()->TextureClear();
1312 if(Line.m_QuadContainerIndex != -1)
1313 {
1314 Graphics()->SetColor(color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClChatBackgroundColor, true)).WithMultipliedAlpha(alpha: Blend));
1315 Graphics()->RenderQuadContainerEx(ContainerIndex: Line.m_QuadContainerIndex, QuadOffset: 0, QuadDrawNum: -1, X: 0, Y: ((y + RealMsgPaddingY / 2.0f) - Line.m_TextYOffset));
1316 }
1317 }
1318
1319 if(Line.m_TextContainerIndex.Valid())
1320 {
1321 if(!g_Config.m_ClChatOld && Line.m_pManagedTeeRenderInfo != nullptr)
1322 {
1323 CTeeRenderInfo &TeeRenderInfo = Line.m_pManagedTeeRenderInfo->TeeRenderInfo();
1324 const int TeeSize = MessageTeeSize();
1325 TeeRenderInfo.m_Size = TeeSize;
1326
1327 float RowHeight = FontSize() + RealMsgPaddingY;
1328 float OffsetTeeY = TeeSize / 2.0f;
1329 float FullHeightMinusTee = RowHeight - TeeSize;
1330
1331 RenderTools()->RenderIdleTeeAtCenter(pInfo: &TeeRenderInfo, Center: vec2(x + (RealMsgPaddingX + TeeSize) / 2.0f, y + OffsetTeeY + FullHeightMinusTee / 2.0f), Emote: EMOTE_NORMAL, Dir: vec2(1, 0.1f), Alpha: Blend);
1332 }
1333
1334 const ColorRGBA TextColor = TextRender()->DefaultTextColor().WithMultipliedAlpha(alpha: Blend);
1335 const ColorRGBA TextOutlineColor = TextRender()->DefaultTextOutlineColor().WithMultipliedAlpha(alpha: Blend);
1336 TextRender()->RenderTextContainer(TextContainerIndex: Line.m_TextContainerIndex, TextColor, TextOutlineColor, X: 0, Y: (y + RealMsgPaddingY / 2.0f) - Line.m_TextYOffset);
1337 }
1338 }
1339}
1340
1341void CChat::EnsureCoherentFontSize() const
1342{
1343 // Adjust font size based on width
1344 if(g_Config.m_ClChatWidth / (float)g_Config.m_ClChatFontSize >= CHAT_FONTSIZE_WIDTH_RATIO)
1345 return;
1346
1347 // We want to keep a ration between font size and font width so that we don't have a weird rendering
1348 g_Config.m_ClChatFontSize = g_Config.m_ClChatWidth / CHAT_FONTSIZE_WIDTH_RATIO;
1349}
1350
1351void CChat::EnsureCoherentWidth() const
1352{
1353 // Adjust width based on font size
1354 if(g_Config.m_ClChatWidth / (float)g_Config.m_ClChatFontSize >= CHAT_FONTSIZE_WIDTH_RATIO)
1355 return;
1356
1357 // We want to keep a ration between font size and font width so that we don't have a weird rendering
1358 g_Config.m_ClChatWidth = CHAT_FONTSIZE_WIDTH_RATIO * g_Config.m_ClChatFontSize;
1359}
1360
1361// ----- send functions -----
1362
1363void CChat::SendChat(int Team, const char *pLine)
1364{
1365 // don't send empty messages
1366 if(*str_utf8_skip_whitespaces(str: pLine) == '\0')
1367 return;
1368
1369 m_LastChatSend = time();
1370
1371 if(GameClient()->Client()->IsSixup())
1372 {
1373 protocol7::CNetMsg_Cl_Say Msg7;
1374 Msg7.m_Mode = Team == 1 ? protocol7::CHAT_TEAM : protocol7::CHAT_ALL;
1375 Msg7.m_Target = -1;
1376 Msg7.m_pMessage = pLine;
1377 Client()->SendPackMsgActive(pMsg: &Msg7, Flags: MSGFLAG_VITAL, NoTranslate: true);
1378 return;
1379 }
1380
1381 // send chat message
1382 CNetMsg_Cl_Say Msg;
1383 Msg.m_Team = Team;
1384 Msg.m_pMessage = pLine;
1385 Client()->SendPackMsgActive(pMsg: &Msg, Flags: MSGFLAG_VITAL);
1386}
1387
1388void CChat::SendChatQueued(const char *pLine)
1389{
1390 if(!pLine || str_length(str: pLine) < 1)
1391 return;
1392
1393 bool AddEntry = false;
1394
1395 if(m_LastChatSend + time_freq() < time())
1396 {
1397 SendChat(Team: m_Mode == MODE_ALL ? 0 : 1, pLine);
1398 AddEntry = true;
1399 }
1400 else if(m_PendingChatCounter < 3)
1401 {
1402 ++m_PendingChatCounter;
1403 AddEntry = true;
1404 }
1405
1406 if(AddEntry)
1407 {
1408 const int Length = str_length(str: pLine);
1409 CHistoryEntry *pEntry = m_History.Allocate(Size: sizeof(CHistoryEntry) + Length);
1410 pEntry->m_Team = m_Mode == MODE_ALL ? 0 : 1;
1411 str_copy(dst: pEntry->m_aText, src: pLine, dst_size: Length + 1);
1412 }
1413}
1414