Files
sm-plugins/OverheadChat/scripting/OverheadChat.sp
T
marisa 3a52b1dfd1 Add ChatFilter2, OverheadChat, EventGreeting and update several plugins
New plugins: ChatFilter2, OverheadChat, EventGreeting.

Updated: HostnameManager, Leader3 (chat and markers), NameFilter2 (plugin
and config), PlayerRankings_nohlstats (rank display modes), custom-chatcolors
(plugin and ccc.inc), Extend (sm_settimeleft).

Add shared includes the plugins build against: Break, ChatFilter2, Couch,
EventNotifier, TransmitManager, leader, ripext, unloze_playtime.
2026-11-23 13:20:15 +00:00

1047 lines
33 KiB
SourcePawn

#pragma semicolon 1
#include <sourcemod>
#include <sdktools>
#include <sdkhooks>
#include <clientprefs>
#undef REQUIRE_PLUGIN
#include <ChatFilter2>
#define REQUIRE_PLUGIN
#undef REQUIRE_EXTENSIONS
#include <TransmitManager>
#define REQUIRE_EXTENSIONS
#pragma newdecls required
#define PLUGIN_VERSION "1.0"
#define PREFIX "\x04[OverheadChat]\x01 "
#define MAX_TEXT_LENGTH 256
#define MAX_TOKENS 128
#define MAX_LINES 8
#define MAX_LINE_LENGTH 72 // sm_overheadchat_line_chars max plus room for "..."
// Skip bubbles rather than push a busy map towards the 2048 edict limit.
#define EDICT_HEADROOM 1900
#define OBS_MODE_IN_EYE 4
// Stock model on every client; its "forward" attachment sits on ValveBiped.forward, a child of
// Bip01_Head1, so it follows the head of any ValveBiped skeleton it bone-merges onto.
#define HELPER_MODEL "models/player/ct_urban.mdl"
#define HELPER_ATTACHMENT "forward"
#define HELPER_CLASS "prop_dynamic" // created as prop_dynamic_override, which spawns as prop_dynamic
#define EF_BONEMERGE (1 << 0)
#define EF_NOSHADOW (1 << 4)
#define EF_NORECEIVESHADOW (1 << 6)
#define EF_BONEMERGE_FASTCULL (1 << 7)
#define EF_PARENT_ANIMATES (1 << 9)
// SelfMute has no include on the shared path and registers no library; checked with GetFeatureStatus.
native bool SelfMute_IsIgnoring(int client, int target);
enum
{
TEXT_RAW = 0, // the only copy, shown to everyone
TEXT_RAW_PAIRED, // has a censored sibling, hidden from safe chat players
TEXT_CENSORED // shown to safe chat players only
}
enum
{
HIDDEN_NOT = 0,
HIDDEN_AUTHOR,
HIDDEN_SETTING_OFF,
HIDDEN_TEAM_CHAT,
HIDDEN_HIDE,
HIDDEN_SELFMUTE,
HIDDEN_SAFE_CHAT_COPY,
HIDDEN_FIRST_PERSON,
HIDDEN_RANGE
}
ConVar g_cvFont;
ConVar g_cvSize;
ConVar g_cvHeight;
ConVar g_cvLineSpacing;
ConVar g_cvRange;
ConVar g_cvLineChars;
ConVar g_cvMaxLines;
ConVar g_cvMinAlnum;
ConVar g_cvDuration;
ConVar g_cvDurationPerChar;
ConVar g_cvDurationMax;
ConVar g_cvTypeTime;
Cookie g_hCookie;
bool g_bEnabled[MAXPLAYERS + 1];
bool g_bChatFilter2;
// ChatFilter2 safe chat per client, kept by ChatFilter2_OnSafeChatChanged so the transmit hook needs no native call
bool g_bSafeChat[MAXPLAYERS + 1];
bool g_bWorldTextBroken;
// TransmitManager extension, used by Hide_TransmitManager (sm_hide) to hide players from a viewer
bool g_bTransmitManager;
// One bubble per author
int g_iTextRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...};
int g_iCensoredRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...};
int g_iHelperRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...};
int g_iLineCount[MAXPLAYERS + 1];
float g_flExpireAt[MAXPLAYERS + 1];
float g_flShownAt[MAXPLAYERS + 1];
char g_sBubbleText[MAXPLAYERS + 1][MAX_TEXT_LENGTH]; // full wrapped text, typed out by the animation
char g_sBubbleCensored[MAXPLAYERS + 1][MAX_TEXT_LENGTH];
int g_iTypedChars[MAXPLAYERS + 1]; // what the text entities show now, see TypedChars()
float g_vecBubblePos[MAXPLAYERS + 1][3]; // server-side estimate, for the range check
int g_iBubbleTeam[MAXPLAYERS + 1]; // say_team team, -1 for all chat
bool g_bIgnored[MAXPLAYERS + 1][MAXPLAYERS + 1]; // [author][viewer], SelfMute snapshot at send time
// Per text entity, read by the transmit hook
int g_iEntAuthor[2049];
int g_iEntKind[2049];
public Plugin myinfo =
{
name = "OverheadChat",
author = "marisakirisame.net",
description = "Shows chat messages briefly above the author's head",
version = PLUGIN_VERSION,
url = ""
};
public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max)
{
MarkNativeAsOptional("SelfMute_IsIgnoring");
MarkNativeAsOptional("TransmitManager_GetEntityState");
return APLRes_Success;
}
public void OnPluginStart()
{
g_cvFont = CreateConVar("sm_overheadchat_font", "4", "point_worldtext font (4 = Liberation Sans, 8 = Roboto Mono with outline)", 0, true, 0.0, true, 12.0);
g_cvSize = CreateConVar("sm_overheadchat_size", "4.0", "Text size", 0, true, 0.5);
g_cvHeight = CreateConVar("sm_overheadchat_height", "16.0", "Height of the text above the author's head");
g_cvLineSpacing = CreateConVar("sm_overheadchat_line_spacing", "4.5", "Extra height per line after the first, so longer messages clear the head", 0, true, 0.0);
g_cvRange = CreateConVar("sm_overheadchat_range", "350.0", "Maximum distance at which the text is shown", 0, true, 0.0);
g_cvLineChars = CreateConVar("sm_overheadchat_line_chars", "24", "Maximum characters per line", 0, true, 8.0, true, 64.0);
g_cvMaxLines = CreateConVar("sm_overheadchat_max_lines", "2", "Maximum lines; longer messages end in ...", 0, true, 1.0, true, float(MAX_LINES));
g_cvMinAlnum = CreateConVar("sm_overheadchat_min_alnum", "2", "Letters/digits that must remain after removing lennies", 0, true, 1.0);
g_cvDuration = CreateConVar("sm_overheadchat_duration", "4.0", "Base seconds a message is shown", 0, true, 0.5);
g_cvDurationPerChar = CreateConVar("sm_overheadchat_duration_per_char", "0.05", "Extra seconds per character", 0, true, 0.0);
g_cvDurationMax = CreateConVar("sm_overheadchat_duration_max", "10.0", "Maximum seconds a message is shown", 0, true, 0.5);
g_cvTypeTime = CreateConVar("sm_overheadchat_type_time", "0.3", "Seconds to type a message out when shown and to backspace it before removal; 0 for no animation", 0, true, 0.0, true, 2.0);
AutoExecConfig(true, "OverheadChat");
// On by default. The setting was opt-in under "overheadchat_enabled"; a new cookie means a "0"
// saved under that one doesn't keep anyone off.
g_hCookie = new Cookie("overheadchat", "Show other players' chat above their heads (0 = off)", CookieAccess_Protected);
SetCookieMenuItem(CookieMenu_OverheadChat, 0, "Overhead Chat");
RegConsoleCmd("sm_overheadchat", Cmd_Toggle, "Toggle seeing chat above players' heads");
RegAdminCmd("sm_overheadchat_say", Cmd_Say, ADMFLAG_RCON, "sm_overheadchat_say <target> <text> - show a bubble as if the target said it");
RegAdminCmd("sm_overheadchat_test", Cmd_Test, ADMFLAG_RCON, "sm_overheadchat_test <text> - print the text a bubble would show");
RegAdminCmd("sm_overheadchat_debug", Cmd_Debug, ADMFLAG_RCON, "sm_overheadchat_debug - list live bubbles and who can see them");
HookEvent("player_death", Event_KillBubble);
HookEvent("player_spawn", Event_KillBubble);
HookEvent("player_team", Event_KillBubble);
// Late load: clients may already be in game with cached cookies.
for (int i = 1; i <= MaxClients; i++)
{
if (IsClientConnected(i) && AreClientCookiesCached(i))
OnClientCookiesCached(i);
}
}
public void OnPluginEnd()
{
for (int i = 1; i <= MaxClients; i++)
KillBubble(i);
}
public void OnAllPluginsLoaded()
{
CheckTransmitManager();
if (LibraryExists("ChatFilter2"))
OnChatFilter2Added();
}
public void OnLibraryAdded(const char[] name)
{
if (StrEqual(name, "ChatFilter2"))
OnChatFilter2Added();
}
public void OnLibraryRemoved(const char[] name)
{
if (StrEqual(name, "ChatFilter2"))
{
// Censored copies stay up but nobody counts as safe chat any more, so everyone sees the raw text.
g_bChatFilter2 = false;
for (int i = 1; i <= MaxClients; i++)
g_bSafeChat[i] = false;
}
}
void OnChatFilter2Added()
{
g_bChatFilter2 = true;
for (int i = 1; i <= MaxClients; i++)
g_bSafeChat[i] = IsClientInGame(i) && ChatFilter2_IsSafeChatEnabled(i);
}
public void ChatFilter2_OnSafeChatChanged(int client, bool enabled)
{
g_bSafeChat[client] = enabled;
}
void CheckTransmitManager()
{
g_bTransmitManager = GetFeatureStatus(FeatureType_Native, "TransmitManager_GetEntityState") == FeatureStatus_Available;
}
public void OnMapStart()
{
g_bWorldTextBroken = false;
PrecacheModel(HELPER_MODEL);
CheckTransmitManager();
}
public void OnClientConnected(int client)
{
g_bEnabled[client] = true;
g_bSafeChat[client] = false;
}
public void OnClientDisconnect(int client)
{
KillBubble(client);
}
//----------------------------------------------------------------------------------------------------
// Setting: viewer-side, on unless turned off, a toggle in the Client Preferences menu (sm_settings / !settings).
//----------------------------------------------------------------------------------------------------
public void OnClientCookiesCached(int client)
{
char val[4];
g_hCookie.Get(client, val, sizeof(val));
g_bEnabled[client] = !StrEqual(val, "0");
}
void ToggleSetting(int client)
{
g_bEnabled[client] = !g_bEnabled[client];
g_hCookie.Set(client, g_bEnabled[client] ? "1" : "0");
PrintToChat(client, "%sOverhead chat is now %s.", PREFIX, g_bEnabled[client] ? "enabled" : "disabled");
}
public void CookieMenu_OverheadChat(int client, CookieMenuAction action, any info, char[] buffer, int maxlen)
{
switch (action)
{
case CookieMenuAction_DisplayOption:
{
FormatEx(buffer, maxlen, "Overhead Chat: %s", g_bEnabled[client] ? "On" : "Off");
}
case CookieMenuAction_SelectOption:
{
ToggleSetting(client);
ShowCookieMenu(client); // re-show with the new state
}
}
}
public Action Cmd_Toggle(int client, int args)
{
if (!client)
{
ReplyToCommand(client, "[OverheadChat] This command can only be used in game.");
return Plugin_Handled;
}
if (!AreClientCookiesCached(client))
{
ReplyToCommand(client, "[OverheadChat] Your settings have not loaded yet, try again in a moment.");
return Plugin_Handled;
}
ToggleSetting(client);
return Plugin_Handled;
}
public Action Cmd_Say(int client, int args)
{
if (args < 2)
{
ReplyToCommand(client, "[OverheadChat] Usage: sm_overheadchat_say <target> <text>");
return Plugin_Handled;
}
char argString[MAX_TEXT_LENGTH], targetArg[MAX_TARGET_LENGTH];
GetCmdArgString(argString, sizeof(argString));
int textStart = BreakString(argString, targetArg, sizeof(targetArg));
int target = FindTarget(client, targetArg, false, false);
if (target == -1)
return Plugin_Handled;
if (!IsPlayerAlive(target))
{
ReplyToCommand(client, "[OverheadChat] %N is not alive.", target);
return Plugin_Handled;
}
char text[MAX_TEXT_LENGTH];
strcopy(text, sizeof(text), argString[textStart]);
StripQuotes(text);
if (!ShowBubble(target, text, -1))
ReplyToCommand(client, "[OverheadChat] Nothing to show after removing lennies, or no free edicts.");
return Plugin_Handled;
}
public Action Cmd_Test(int client, int args)
{
char text[MAX_TEXT_LENGTH], stripped[MAX_TEXT_LENGTH], joined[MAX_TEXT_LENGTH];
GetCmdArgString(text, sizeof(text));
StripQuotes(text);
if (!StripLennies(text, stripped, sizeof(stripped)))
{
ReplyToCommand(client, "[OverheadChat] No bubble (kept: \"%s\")", stripped);
return Plugin_Handled;
}
// lines between bars so the centring padding is visible
char wrapped[MAX_TEXT_LENGTH];
WrapBubbleText(stripped, wrapped, sizeof(wrapped));
BuildTypedText(wrapped, -1, joined, sizeof(joined));
ReplaceString(joined, sizeof(joined), "\n", "|\n|");
ReplyToCommand(client, "[OverheadChat]\n|%s|", joined);
return Plugin_Handled;
}
//----------------------------------------------------------------------------------------------------
// Chat capture. _Post never fires for messages another plugin blocked (gags, Leader3 titles).
//----------------------------------------------------------------------------------------------------
public void OnClientSayCommand_Post(int client, const char[] command, const char[] sArgs)
{
if (client <= 0 || !IsClientInGame(client) || !IsPlayerAlive(client))
return;
bool teamChat = StrEqual(command, "say_team");
if (!teamChat && !StrEqual(command, "say"))
return;
// commands and admin chat
if (sArgs[0] == '!' || sArgs[0] == '/' || sArgs[0] == '@')
return;
ShowBubble(client, sArgs, teamChat ? GetClientTeam(client) : -1);
}
public void Event_KillBubble(Event event, const char[] name, bool dontBroadcast)
{
int client = GetClientOfUserId(event.GetInt("userid"));
if (client)
KillBubble(client);
}
//----------------------------------------------------------------------------------------------------
// Bubbles: point_worldtext attached to the head of an invisible helper model that bone-merges onto
// the author, so every client places the text on the head it draws itself. The server never moves
// the text. A message ChatFilter2 censors gets a second text entity; SetTransmit shows the censored
// one to safe chat players and the raw one to everyone else (same split as Leader3 markers).
//----------------------------------------------------------------------------------------------------
// Returns false if nothing was shown. team is the say_team team, or -1 for all chat.
bool ShowBubble(int author, const char[] message, int team)
{
if (g_bWorldTextBroken)
return false;
char text[MAX_TEXT_LENGTH];
if (!StripLennies(message, text, sizeof(text)))
return false;
char censored[MAX_TEXT_LENGTH];
strcopy(censored, sizeof(censored), text);
bool hasCensored = g_bChatFilter2 && ChatFilter2_CensorText(censored, sizeof(censored)) && !StrEqual(censored, text);
// censoring keeps the length, so both copies wrap to the same lines
g_iLineCount[author] = WrapBubbleText(text, g_sBubbleText[author], sizeof(g_sBubbleText[]));
if (hasCensored)
WrapBubbleText(censored, g_sBubbleCensored[author], sizeof(g_sBubbleCensored[]));
// the entities start blank and OnGameFrame types the text out
float now = GetGameTime();
g_flShownAt[author] = now;
g_iTypedChars[author] = g_cvTypeTime.FloatValue > 0.0 ? 0 : -1;
char wrapped[MAX_TEXT_LENGTH], wrappedCensored[MAX_TEXT_LENGTH];
BuildTypedText(g_sBubbleText[author], g_iTypedChars[author], wrapped, sizeof(wrapped));
if (hasCensored)
BuildTypedText(g_sBubbleCensored[author], g_iTypedChars[author], wrappedCensored, sizeof(wrappedCensored));
int helper = LiveEntRef(g_iHelperRef[author], HELPER_CLASS);
int ent = LiveEntRef(g_iTextRef[author]);
int censoredEnt = LiveEntRef(g_iCensoredRef[author]);
// Replace in place; respawn only when the bubble gains or loses its censored copy,
// which keeps the entity kinds in step with the transmit hook.
if (helper != -1 && ent != -1 && hasCensored == (censoredEnt != -1))
{
SetVariantString(wrapped);
AcceptEntityInput(ent, "SetText");
SetTextOffset(ent, author); // the line count may have changed
if (censoredEnt != -1)
{
SetVariantString(wrappedCensored);
AcceptEntityInput(censoredEnt, "SetText");
SetTextOffset(censoredEnt, author);
}
}
else
{
KillBubble(author);
if (GetEntityCount() >= EDICT_HEADROOM)
return false;
UpdateBubblePos(author);
helper = SpawnHelper(author);
if (helper == -1)
return false;
g_iHelperRef[author] = EntIndexToEntRef(helper);
ent = SpawnWorldText(author, helper, wrapped, hasCensored ? TEXT_RAW_PAIRED : TEXT_RAW);
if (ent == -1)
{
KillBubble(author);
return false;
}
g_iTextRef[author] = EntIndexToEntRef(ent);
// The raw text stays hidden from safe chat players even if the censored copy fails to spawn.
if (hasCensored)
{
censoredEnt = SpawnWorldText(author, helper, wrappedCensored, TEXT_CENSORED);
if (censoredEnt != -1)
g_iCensoredRef[author] = EntIndexToEntRef(censoredEnt);
}
}
// team is checked live in the transmit hook, since ZR infection switches teams mid-bubble
g_iBubbleTeam[author] = team;
bool selfMute = GetFeatureStatus(FeatureType_Native, "SelfMute_IsIgnoring") == FeatureStatus_Available;
for (int viewer = 1; viewer <= MaxClients; viewer++)
g_bIgnored[author][viewer] = IsClientInGame(viewer) && selfMute && SelfMute_IsIgnoring(viewer, author);
// the duration is time fully shown; typing out and backspacing come on top
float duration = g_cvDuration.FloatValue + g_cvDurationPerChar.FloatValue * strlen(text);
if (duration > g_cvDurationMax.FloatValue)
duration = g_cvDurationMax.FloatValue;
g_flExpireAt[author] = now + duration + 2.0 * g_cvTypeTime.FloatValue;
UpdateBubblePos(author); // the range check uses it
return true;
}
// Invisible copy of the author's skeleton; the text hangs off its head attachment.
int SpawnHelper(int author)
{
int ent = CreateEntityByName("prop_dynamic_override");
if (ent == -1)
return -1;
DispatchKeyValue(ent, "model", HELPER_MODEL);
DispatchKeyValue(ent, "solid", "0");
DispatchKeyValue(ent, "DisableBoneFollowers", "1");
DispatchKeyValue(ent, "disableshadows", "1");
DispatchKeyValue(ent, "disablereceiveshadows", "1");
if (!DispatchSpawn(ent))
{
AcceptEntityInput(ent, "Kill");
return -1;
}
// RENDER_NONE rather than EF_NODRAW: EF_NODRAW stops the entity being sent at all, and the
// client needs it to place the text.
SetEntityRenderMode(ent, RENDER_NONE);
// CBaseEntity::FollowEntity() recipe (see Leader3's glow shell): the client only bone-merges
// with EF_BONEMERGE, a move parent and MOVETYPE_NONE.
float origin[3], angles[3];
GetClientAbsOrigin(author, origin);
GetClientAbsAngles(author, angles);
TeleportEntity(ent, origin, angles, NULL_VECTOR);
SetVariantString("!activator");
AcceptEntityInput(ent, "SetParent", author, ent);
SetEntityMoveType(ent, MOVETYPE_NONE);
SetEntProp(ent, Prop_Send, "m_fEffects",
EF_BONEMERGE|EF_BONEMERGE_FASTCULL|EF_NOSHADOW|EF_NORECEIVESHADOW|EF_PARENT_ANIMATES);
g_iEntAuthor[ent] = author;
SDKHook(ent, SDKHook_SetTransmit, Hook_HelperTransmit);
return ent;
}
int SpawnWorldText(int author, int helper, const char[] text, int kind)
{
int ent = CreateEntityByName("point_worldtext");
if (ent == -1)
{
g_bWorldTextBroken = true;
LogMessage("point_worldtext could not be created; overhead chat is off for this map.");
return -1;
}
char font[4], size[16];
g_cvFont.GetString(font, sizeof(font));
g_cvSize.GetString(size, sizeof(size));
DispatchKeyValue(ent, "message", text);
DispatchKeyValue(ent, "font", font);
DispatchKeyValue(ent, "textsize", size);
DispatchKeyValue(ent, "color", "255 255 255 255");
DispatchKeyValue(ent, "orientation", "1");
DispatchSpawn(ent);
TeleportEntity(ent, g_vecBubblePos[author], NULL_VECTOR, NULL_VECTOR);
SetVariantString("!activator");
AcceptEntityInput(ent, "SetParent", helper, ent);
SetVariantString(HELPER_ATTACHMENT);
AcceptEntityInput(ent, "SetParentAttachment", ent, ent);
SetTextOffset(ent, author);
g_iEntAuthor[ent] = author;
g_iEntKind[ent] = kind;
SDKHook(ent, SDKHook_SetTransmit, Hook_BubbleTransmit);
return ent;
}
// Offset from the head attachment. Its z axis is within 4 degrees of world up when the head is
// level (ct_urban reference pose), so a z offset puts the text straight above the head.
void SetTextOffset(int ent, int author)
{
float local[3];
local[2] = BubbleHeight(author);
TeleportEntity(ent, local, NULL_VECTOR, NULL_VECTOR); // parented: sets the local origin
}
// Each extra line lifts the text so the bottom line keeps clear of the head.
float BubbleHeight(int author)
{
return g_cvHeight.FloatValue + g_cvLineSpacing.FloatValue * (g_iLineCount[author] - 1);
}
void KillBubble(int author)
{
KillEntRef(g_iTextRef[author]);
KillEntRef(g_iCensoredRef[author]);
KillEntRef(g_iHelperRef[author], HELPER_CLASS);
g_iTextRef[author] = INVALID_ENT_REFERENCE;
g_iCensoredRef[author] = INVALID_ENT_REFERENCE;
g_iHelperRef[author] = INVALID_ENT_REFERENCE;
}
// Server-side estimate of where the text is, used only for the range check: the eyes are within
// a few units of the head attachment the client places the text on.
void UpdateBubblePos(int author)
{
GetClientEyePosition(author, g_vecBubblePos[author]);
g_vecBubblePos[author][2] += BubbleHeight(author);
}
public void OnGameFrame()
{
float now = GetGameTime();
for (int author = 1; author <= MaxClients; author++)
{
if (g_iTextRef[author] == INVALID_ENT_REFERENCE)
continue;
if (LiveEntRef(g_iTextRef[author]) == -1 || LiveEntRef(g_iHelperRef[author], HELPER_CLASS) == -1
|| now >= g_flExpireAt[author] || !IsClientInGame(author) || !IsPlayerAlive(author))
{
// also catches entities the round restart removed
KillBubble(author);
continue;
}
UpdateBubblePos(author);
AnimateBubble(author, now);
}
}
// Typing out and backspacing: sets the shown text whenever the typed character count changes.
void AnimateBubble(int author, float now)
{
int typed = TypedChars(author, now);
if (typed == g_iTypedChars[author])
return;
g_iTypedChars[author] = typed;
char text[MAX_TEXT_LENGTH];
int ents[2];
ents[0] = LiveEntRef(g_iTextRef[author]);
ents[1] = LiveEntRef(g_iCensoredRef[author]);
for (int e = 0; e < 2; e++)
{
if (ents[e] == -1)
continue;
BuildTypedText(e == 0 ? g_sBubbleText[author] : g_sBubbleCensored[author], typed, text, sizeof(text));
SetVariantString(text);
AcceptEntityInput(ents[e], "SetText");
}
}
// Non-space characters to show, or -1 for all of them. The text types out over
// sm_overheadchat_type_time after it is shown and backspaces over the same time before it expires.
int TypedChars(int author, float now)
{
float typeTime = g_cvTypeTime.FloatValue;
float t = now - g_flShownAt[author];
float left = g_flExpireAt[author] - now;
if (left < t)
t = left;
if (typeTime <= 0.0 || t >= typeTime)
return -1;
int total = 0;
for (int i = 0; g_sBubbleText[author][i]; i++)
{
if (g_sBubbleText[author][i] > ' ')
total++;
}
return RoundToFloor(total * t / typeTime);
}
// The helper only matters to viewers who can get the text (a subset of these), so skip the rest.
public Action Hook_HelperTransmit(int ent, int client)
{
int author = g_iEntAuthor[ent];
return (client == author || !g_bEnabled[client]) ? Plugin_Handled : Plugin_Continue;
}
public Action Hook_BubbleTransmit(int ent, int client)
{
return BubbleHiddenReason(ent, client) == HIDDEN_NOT ? Plugin_Continue : Plugin_Handled;
}
// Why a viewer doesn't get a text entity; shared by the transmit hook and sm_overheadchat_debug,
// which skips the setting check so bots (no cookies) can stand in as viewers.
int BubbleHiddenReason(int ent, int client, bool ignoreSetting = false)
{
int author = g_iEntAuthor[ent];
if (client == author)
return HIDDEN_AUTHOR;
if (!g_bEnabled[client] && !ignoreSetting)
return HIDDEN_SETTING_OFF;
if (g_iBubbleTeam[author] != -1 && GetClientTeam(client) != g_iBubbleTeam[author])
return HIDDEN_TEAM_CHAT;
// the viewer can't see the author (sm_hide), so the text would float on its own
if (g_bTransmitManager && !TransmitManager_GetEntityState(author, client))
return HIDDEN_HIDE;
if (g_bIgnored[author][client])
return HIDDEN_SELFMUTE;
int kind = g_iEntKind[ent];
if ((kind == TEXT_RAW_PAIRED && g_bSafeChat[client]) || (kind == TEXT_CENSORED && !g_bSafeChat[client]))
return HIDDEN_SAFE_CHAT_COPY;
// spectating the author in first person: the text would sit in their view
if (!IsPlayerAlive(client)
&& GetEntProp(client, Prop_Send, "m_iObserverMode") == OBS_MODE_IN_EYE
&& GetEntPropEnt(client, Prop_Send, "m_hObserverTarget") == author)
return HIDDEN_FIRST_PERSON;
float eye[3];
GetClientEyePosition(client, eye);
float range = g_cvRange.FloatValue;
if (GetVectorDistance(eye, g_vecBubblePos[author], true) > range * range)
return HIDDEN_RANGE;
return HIDDEN_NOT;
}
public Action Cmd_Debug(int client, int args)
{
static const char reasons[][] = {"visible", "author", "setting off", "team chat", "author hidden (sm_hide)", "selfmute", "other safe chat copy", "first person", "out of range"};
static const char kinds[][] = {"raw", "raw (has censored copy)", "censored"};
int shown = 0;
for (int author = 1; author <= MaxClients; author++)
{
int ents[2];
ents[0] = LiveEntRef(g_iTextRef[author]);
ents[1] = LiveEntRef(g_iCensoredRef[author]);
for (int e = 0; e < 2; e++)
{
int ent = ents[e];
if (ent == -1)
continue;
char text[MAX_TEXT_LENGTH];
GetEntPropString(ent, Prop_Send, "m_szText", text, sizeof(text));
ReplaceString(text, sizeof(text), "\n", "|");
ReplyToCommand(client, "[OverheadChat] %N (team %d), %s, %s, %.1fs left: \"%s\"", author, GetClientTeam(author),
g_iBubbleTeam[author] == -1 ? "all chat" : "team chat", kinds[g_iEntKind[ent]], g_flExpireAt[author] - GetGameTime(), text);
for (int viewer = 1; viewer <= MaxClients; viewer++)
{
if (IsClientInGame(viewer))
ReplyToCommand(client, " %N (team %d): %s%s", viewer, GetClientTeam(viewer),
reasons[BubbleHiddenReason(ent, viewer, true)], g_bEnabled[viewer] ? "" : " [setting off]");
}
shown++;
}
}
if (!shown)
ReplyToCommand(client, "[OverheadChat] No live bubbles.");
return Plugin_Handled;
}
void KillEntRef(int ref, const char[] expectedClass = "point_worldtext")
{
int ent = LiveEntRef(ref, expectedClass);
if (ent != -1)
AcceptEntityInput(ent, "Kill");
}
// Resolves an entity reference, returning -1 unless it is still a live edict of the expected class.
int LiveEntRef(int ref, const char[] expectedClass = "point_worldtext")
{
if (ref == INVALID_ENT_REFERENCE)
return -1;
int ent = EntRefToEntIndex(ref);
if (ent == INVALID_ENT_REFERENCE || !IsValidEdict(ent))
return -1;
char classname[32];
GetEdictClassname(ent, classname, sizeof(classname));
return StrEqual(classname, expectedClass) ? ent : -1;
}
//----------------------------------------------------------------------------------------------------
// Text: point_worldtext only draws printable ASCII, so lennies and other unsupported text are
// removed as whole space-separated tokens, along with symbol-only tokens next to them (the
// brackets around "( ͡° ͜ʖ ͡°)"). Returns false unless enough letters/digits remain.
//----------------------------------------------------------------------------------------------------
bool StripLennies(const char[] input, char[] output, int maxlen)
{
int starts[MAX_TOKENS], ends[MAX_TOKENS];
bool dropped[MAX_TOKENS], hasAlnum[MAX_TOKENS];
int count = 0;
int len = strlen(input);
int i = 0;
while (i < len && count < MAX_TOKENS)
{
// spaces and control bytes (typed colour codes) separate tokens
if (input[i] <= ' ')
{
i++;
continue;
}
starts[count] = i;
dropped[count] = false;
hasAlnum[count] = false;
while (i < len && input[i] > ' ')
{
if (input[i] > '~') // DEL or any UTF-8 byte
dropped[count] = true;
else if (IsCharAlpha(input[i]) || IsCharNumeric(input[i]))
hasAlnum[count] = true;
i++;
}
ends[count++] = i;
}
// symbol-only neighbours of dropped tokens are lenny residue; repeat so chains collapse
bool changed = true;
while (changed)
{
changed = false;
for (int t = 0; t < count; t++)
{
if (dropped[t] || hasAlnum[t])
continue;
if ((t > 0 && dropped[t - 1]) || (t + 1 < count && dropped[t + 1]))
{
dropped[t] = true;
changed = true;
}
}
}
output[0] = '\0';
int pos = 0;
int alnum = 0;
for (int t = 0; t < count; t++)
{
if (dropped[t])
continue;
int tokenLen = ends[t] - starts[t];
if (pos + tokenLen + 2 > maxlen)
break;
if (pos > 0)
output[pos++] = ' ';
for (int c = starts[t]; c < ends[t]; c++)
{
if (IsCharAlpha(input[c]) || IsCharNumeric(input[c]))
alnum++;
output[pos++] = input[c];
}
}
output[pos] = '\0';
return alnum >= g_cvMinAlnum.IntValue;
}
// Word-wraps single-spaced ASCII text into at most sm_overheadchat_max_lines lines of
// sm_overheadchat_line_chars. Overflow cuts the last line and ends it in "...". Returns the line count.
int WrapText(const char[] text, char lines[MAX_LINES][MAX_LINE_LENGTH])
{
int width = g_cvLineChars.IntValue;
int maxLines = g_cvMaxLines.IntValue;
int len = strlen(text);
int pos = 0;
int count = 0;
while (pos < len && count < maxLines)
{
int remaining = len - pos;
int take, next;
if (remaining <= width)
{
take = remaining;
next = len;
}
else if (count == maxLines - 1)
{
// leave room for "...", cutting at a word boundary when there is one
take = width - 3;
for (int c = pos + width - 3; c > pos; c--)
{
if (text[c] == ' ')
{
take = c - pos;
break;
}
}
next = len;
}
else
{
// last space that still lets the line fit; the space itself is dropped
int brk = -1;
for (int c = pos + width; c > pos; c--)
{
if (text[c] == ' ')
{
brk = c;
break;
}
}
if (brk != -1)
{
take = brk - pos;
next = brk + 1;
}
else
{
// a word longer than a line
take = width;
next = pos + width;
}
}
strcopy(lines[count], take + 1, text[pos]);
if (next == len && take < remaining)
{
TrimString(lines[count]);
StrCat(lines[count], MAX_LINE_LENGTH, "...");
}
pos = next;
count++;
}
return count;
}
// Lays out the bubble text showing only its first `typed` non-space characters (-1 for all).
// The renderer centres the block on its widest line but starts every line at the block's left
// edge, so each line gets left padding of half the width it lacks, in spaces (to within half a
// space). Widths come from the font's glyph advances, so this works in proportional fonts and
// keeps a partly typed message centred as it grows.
void BuildTypedText(const char[] text, int typed, char[] output, int maxlen)
{
int font = g_iFontTable[g_cvFont.IntValue];
char lines[MAX_LINES][MAX_LINE_LENGTH];
int widths[MAX_LINES];
int count = 0;
int widest = 0;
int start = 0;
while (count < MAX_LINES)
{
int end = start;
while (text[end] && text[end] != '\n')
end++;
// typed part of the line, ending on its last typed character
int partEnd = start;
for (int i = start; i < end && typed != 0; i++)
{
if (text[i] > ' ')
{
typed--;
partEnd = i + 1;
}
}
int len = partEnd - start;
if (len > MAX_LINE_LENGTH - 1)
len = MAX_LINE_LENGTH - 1;
strcopy(lines[count], len + 1, text[start]);
widths[count] = TextWidth(font, lines[count]);
if (widths[count] > widest)
widest = widths[count];
count++;
if (!text[end])
break;
start = end + 1;
}
int space = g_iFontAdvance[font][0];
output[0] = '\0';
for (int i = 0; i < count; i++)
{
if (i > 0)
StrCat(output, maxlen, "\n");
int left = RoundToNearest(float(widest - widths[i]) / (2.0 * space));
for (int c = 0; c < left; c++)
StrCat(output, maxlen, " ");
StrCat(output, maxlen, lines[i]);
}
}
// Wraps text and joins the lines with \n, unpadded; BuildTypedText lays them out. Returns the line count.
int WrapBubbleText(const char[] text, char[] output, int maxlen)
{
char lines[MAX_LINES][MAX_LINE_LENGTH];
int count = WrapText(text, lines);
output[0] = '\0';
for (int i = 0; i < count; i++)
{
if (i > 0)
StrCat(output, maxlen, "\n");
StrCat(output, maxlen, lines[i]);
}
return count;
}
// Width in font units, as C_PointWorldText::CalcTextTotalSize adds it up (text spacing 0).
int TextWidth(int font, const char[] text)
{
int width = 0;
for (int i = 0; text[i]; i++)
{
int idx = text[i] - ' ';
if (idx < 0)
idx = 0;
else if (idx > 94)
idx = 94;
width += g_iFontAdvance[font][idx];
}
return width;
}
//----------------------------------------------------------------------------------------------------
// Font metrics: glyph advances for printable ASCII (' ' to '~') from the client's point_worldtext
// font tables (hl2sdk c_point_worldtext.cpp, identical in the CS:S client.dll).
//----------------------------------------------------------------------------------------------------
// sm_overheadchat_font -> table below, as the client's g_mapfonts maps fonts to glyph sets
int g_iFontTable[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 0};
int g_iFontAdvance[5][95] =
{
// TF2 Build
{
25, 16, 15, 42, 25, 36, 39, 10, 25, 25, 25, 27, 12, 23, 14, 27, 43, 25, 37, 37, 41, 34, 30, 36,
36, 32, 14, 13, 30, 29, 30, 38, 44, 45, 38, 42, 46, 39, 39, 43, 48, 18, 30, 37, 32, 49, 42, 50,
38, 50, 38, 38, 43, 48, 49, 61, 46, 47, 38, 16, 27, 16, 34, 35, 10, 45, 38, 42, 46, 39, 39, 43,
48, 21, 30, 37, 30, 49, 42, 50, 38, 50, 38, 38, 43, 48, 49, 61, 46, 47, 38, 18, 16, 18, 34
},
// TF2
{
22, 11, 8, 20, 49, 24, 30, 8, 19, 18, 17, 19, 8, 18, 9, 22, 34, 16, 32, 30, 31, 26, 27, 27,
31, 24, 10, 9, 12, 19, 13, 34, 30, 32, 31, 33, 36, 32, 32, 35, 33, 14, 23, 32, 31, 39, 34, 41,
31, 40, 38, 24, 35, 34, 34, 43, 36, 35, 32, 11, 18, 12, 14, 23, 9, 32, 31, 33, 36, 32, 32, 35,
33, 14, 23, 32, 31, 39, 34, 41, 31, 40, 38, 24, 35, 34, 34, 43, 36, 35, 32, 16, 9, 16, 17
},
// Liberation Sans
{
18, 18, 22, 35, 35, 57, 42, 12, 21, 21, 25, 37, 18, 21, 18, 18, 35, 35, 35, 35, 35, 35, 35, 35,
35, 35, 18, 18, 37, 37, 37, 35, 65, 42, 42, 46, 46, 42, 39, 50, 46, 18, 32, 42, 35, 53, 46, 50,
42, 50, 46, 42, 39, 46, 42, 60, 42, 42, 39, 18, 18, 18, 30, 35, 21, 35, 35, 32, 35, 35, 18, 35,
35, 14, 14, 32, 14, 53, 35, 35, 35, 35, 21, 32, 18, 35, 32, 46, 32, 32, 32, 21, 16, 21, 37
},
// TF2 Professor
{
27, 14, 24, 58, 40, 66, 46, 20, 32, 34, 32, 56, 22, 34, 16, 30, 50, 38, 46, 32, 40, 42, 34, 44,
34, 38, 18, 24, 34, 42, 38, 40, 54, 43, 44, 40, 44, 42, 36, 42, 50, 18, 38, 48, 44, 58, 48, 44,
36, 54, 51, 34, 56, 41, 44, 64, 44, 46, 52, 30, 56, 40, 24, 72, 22, 34, 31, 26, 32, 32, 28, 33,
37, 14, 26, 39, 34, 46, 40, 35, 31, 35, 33, 24, 38, 27, 26, 45, 35, 38, 32, 44, 18, 34, 36
},
// Roboto Mono
{
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77
}
};