diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..4c5c3574 --- /dev/null +++ b/.clang-format @@ -0,0 +1,148 @@ +# for more, see: https://clang.llvm.org/docs/ClangFormatStyleOptions.html + +Language: Cpp + +AccessModifierOffset: -4 + +AlignAfterOpenBracket: Align + +AlignArrayOfStructures: Left + +AlignConsecutiveAssignments: false + +AlignConsecutiveDeclarations: false + +AlignEscapedNewlines: Right + +AlignOperands: true + +AlignTrailingComments: true + +AllowAllParametersOfDeclarationOnNextLine: false + +AllowShortBlocksOnASingleLine: true + +AllowShortCaseLabelsOnASingleLine: true + +AllowShortFunctionsOnASingleLine: InlineOnly + +AllowShortIfStatementsOnASingleLine: true + +AllowShortLoopsOnASingleLine: true + +AlwaysBreakAfterReturnType: None + +AlwaysBreakBeforeMultilineStrings: false + +AlwaysBreakTemplateDeclarations: true + +BinPackArguments: true + +BinPackParameters: true + +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + AfterCaseLabel: true + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false + +BreakBeforeBinaryOperators: NonAssignment + +BreakBeforeBraces: Custom + +BreakBeforeTernaryOperators: false + +BreakConstructorInitializers: AfterColon + +#BreakInheritanceList: AfterColon + +BreakStringLiterals: false + +ColumnLimit: 0 + +CompactNamespaces: true + +ConstructorInitializerAllOnOneLineOrOnePerLine: false + +ConstructorInitializerIndentWidth: 4 + +ContinuationIndentWidth: 4 + +Cpp11BracedListStyle: true + +DerivePointerAlignment: false + +FixNamespaceComments: true + +IndentCaseLabels: true + +IndentWidth: 4 + +IndentWrappedFunctionNames: false + +KeepEmptyLinesAtTheStartOfBlocks: false + +MaxEmptyLinesToKeep: 1 + +NamespaceIndentation: All + +PointerAlignment: Left + +ReflowComments: true + +SortUsingDeclarations: false + +SpaceAfterCStyleCast: false + +SpaceAfterTemplateKeyword: true + +SpaceBeforeAssignmentOperators: true + +# SpaceBeforeCpp11BracedList: true + +# SpaceBeforeCtorInitializerColon: true + +# SpaceBeforeInheritanceColon: true + +SpaceBeforeParens: ControlStatements + +# SpaceBeforeRangeBasedForLoopColon: true + +SpaceInEmptyParentheses: false + +SpacesBeforeTrailingComments: 1 + +SpacesInAngles: false + +SpacesInCStyleCastParentheses: false + +SpacesInContainerLiterals: true + +SpacesInParentheses: false + +SpacesInSquareBrackets: false + +Standard: Auto + +TabWidth: 4 + +UseTab: Always + +SortIncludes: true + +IndentPPDirectives: BeforeHash + +PPIndentWidth: -1 + +RemoveBracesLLVM: true \ No newline at end of file diff --git a/clang-format.sh b/clang-format.sh new file mode 100644 index 00000000..df4d0397 --- /dev/null +++ b/clang-format.sh @@ -0,0 +1 @@ +find src/ -iname '*.h' -o -iname '*.cpp' | xargs clang-format -i \ No newline at end of file diff --git a/src/addresses.cpp b/src/addresses.cpp index 7cd60f7c..d7ed939f 100644 --- a/src/addresses.cpp +++ b/src/addresses.cpp @@ -18,20 +18,20 @@ */ #include "addresses.h" -#include "utils/module.h" #include "gameconfig.h" +#include "utils/module.h" #include "tier0/memdbgon.h" -extern CGameConfig *g_GameConfig; +extern CGameConfig* g_GameConfig; -#define RESOLVE_SIG(gameConfig, name, variable) \ - variable = (decltype(variable))gameConfig->ResolveSignature(name); \ - if (!variable) \ - return false; \ +#define RESOLVE_SIG(gameConfig, name, variable) \ + variable = (decltype(variable))gameConfig->ResolveSignature(name); \ + if (!variable) \ + return false; \ Message("Found %s at 0x%p\n", name, variable); -bool addresses::Initialize(CGameConfig *g_GameConfig) +bool addresses::Initialize(CGameConfig* g_GameConfig) { modules::engine = new CModule(ROOTBIN, "engine2"); modules::tier0 = new CModule(ROOTBIN, "tier0"); diff --git a/src/addresses.h b/src/addresses.h index f752fc1f..b848e01c 100644 --- a/src/addresses.h +++ b/src/addresses.h @@ -26,17 +26,17 @@ namespace modules { - inline CModule *engine; - inline CModule *tier0; - inline CModule *server; - inline CModule *schemasystem; - inline CModule *vscript; - inline CModule *client; + inline CModule* engine; + inline CModule* tier0; + inline CModule* server; + inline CModule* schemasystem; + inline CModule* vscript; + inline CModule* client; inline CModule* networksystem; inline CModule* vphysics2; inline CModule* matchmaking; #ifdef _WIN32 - inline CModule *hammer; + inline CModule* hammer; #endif } // namespace modules @@ -61,36 +61,36 @@ struct SndOpEventGuid_t; namespace addresses { - bool Initialize(CGameConfig *g_GameConfig); + bool Initialize(CGameConfig* g_GameConfig); - inline void(FASTCALL *SetGroundEntity)(CBaseEntity *ent, CBaseEntity *ground, CBaseEntity* unk3); - inline void(FASTCALL *CCSPlayerController_SwitchTeam)(CCSPlayerController *pController, uint32 team); - inline void(FASTCALL *CBasePlayerController_SetPawn)(CBasePlayerController *pController, CCSPlayerPawn *pPawn, bool a3, bool a4, bool a5); - inline void(FASTCALL *CBaseModelEntity_SetModel)(CBaseModelEntity *pModel, const char *szModel); - inline void(FASTCALL *UTIL_Remove)(CEntityInstance*); + inline void(FASTCALL* SetGroundEntity)(CBaseEntity* ent, CBaseEntity* ground, CBaseEntity* unk3); + inline void(FASTCALL* CCSPlayerController_SwitchTeam)(CCSPlayerController* pController, uint32 team); + inline void(FASTCALL* CBasePlayerController_SetPawn)(CBasePlayerController* pController, CCSPlayerPawn* pPawn, bool a3, bool a4, bool a5); + inline void(FASTCALL* CBaseModelEntity_SetModel)(CBaseModelEntity* pModel, const char* szModel); + inline void(FASTCALL* UTIL_Remove)(CEntityInstance*); - inline void(FASTCALL *CEntitySystem_AddEntityIOEvent)(CEntitySystem *pEntitySystem, CEntityInstance *pTarget, const char *pszInput, - CEntityInstance *pActivator, CEntityInstance *pCaller, variant_t *value, float flDelay, int outputID); + inline void(FASTCALL* CEntitySystem_AddEntityIOEvent)(CEntitySystem* pEntitySystem, CEntityInstance* pTarget, const char* pszInput, + CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, float flDelay, int outputID); - inline void(FASTCALL *CEntityInstance_AcceptInput)(CEntityInstance *pThis, const char *pInputName, - CEntityInstance *pActivator, CEntityInstance *pCaller, variant_t *value, int nOutputID); + inline void(FASTCALL* CEntityInstance_AcceptInput)(CEntityInstance* pThis, const char* pInputName, + CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID); - inline CBaseEntity *(FASTCALL *CGameEntitySystem_FindEntityByClassName)(CEntitySystem *pEntitySystem, CEntityInstance *pStartEntity, const char *szName); + inline CBaseEntity*(FASTCALL* CGameEntitySystem_FindEntityByClassName)(CEntitySystem* pEntitySystem, CEntityInstance* pStartEntity, const char* szName); - inline CBaseEntity *(FASTCALL *CGameEntitySystem_FindEntityByName)(CEntitySystem *pEntitySystem, CEntityInstance *pStartEntity, const char *szName, - CEntityInstance *pSearchingEntity, CEntityInstance *pActivator, CEntityInstance *pCaller, - IEntityFindFilter *pFilter); - inline void(FASTCALL *CGameRules_TerminateRound)(CGameRules* pGameRules, float delay, unsigned int reason, int64 a4, unsigned int a5); - inline CBaseEntity *(FASTCALL* CreateEntityByName)(const char* className, int iForceEdictIndex); - inline void(FASTCALL *DispatchSpawn)(CBaseEntity* pEntity, CEntityKeyValues *pEntityKeyValues); - inline void(FASTCALL *CEntityIdentity_SetEntityName)(CEntityIdentity *pEntity, const char *pName); - inline void(FASTCALL *CBaseEntity_EmitSoundParams)(CBaseEntity *pEntity, const char *pszSound, int nPitch, float flVolume, float flDelay); - inline void(FASTCALL *CBaseEntity_SetParent)(CBaseEntity *pEntity, CBaseEntity *pNewParent, CUtlStringToken nBoneOrAttachName, matrix3x4a_t *pOffsetTransform); - inline int(FASTCALL *DispatchParticleEffect)(const char *pszParticleName, int iAttachType, CBaseEntity *pEntity, - char iAttachmentPoint, CUtlSymbolLarge iAttachmentName, bool bResetAllParticlesOnEntity, int nSplitScreenPlayerSlot, IRecipientFilter *a7, byte *a8); - inline SndOpEventGuid_t(FASTCALL *CBaseEntity_EmitSoundFilter)(IRecipientFilter &filter, CEntityIndex ent, const EmitSound_t ¶ms); - inline void(FASTCALL *CBaseEntity_SetMoveType)(CBaseEntity *pThis, MoveType_t nMoveType, MoveCollide_t nMoveCollide); - inline void(FASTCALL *CTakeDamageInfo_Constructor)(CTakeDamageInfo *pThis, CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pAbility, - const Vector *vecDamageForce, const Vector *vecDamagePosition, float flDamage, int bitsDamageType, int iCustomDamage, void *a10); - inline void(FASTCALL *CNetworkStringTable_DeleteAllStrings)(INetworkStringTable *pThis); -} \ No newline at end of file + inline CBaseEntity*(FASTCALL* CGameEntitySystem_FindEntityByName)(CEntitySystem* pEntitySystem, CEntityInstance* pStartEntity, const char* szName, + CEntityInstance* pSearchingEntity, CEntityInstance* pActivator, CEntityInstance* pCaller, + IEntityFindFilter* pFilter); + inline void(FASTCALL* CGameRules_TerminateRound)(CGameRules* pGameRules, float delay, unsigned int reason, int64 a4, unsigned int a5); + inline CBaseEntity*(FASTCALL* CreateEntityByName)(const char* className, int iForceEdictIndex); + inline void(FASTCALL* DispatchSpawn)(CBaseEntity* pEntity, CEntityKeyValues* pEntityKeyValues); + inline void(FASTCALL* CEntityIdentity_SetEntityName)(CEntityIdentity* pEntity, const char* pName); + inline void(FASTCALL* CBaseEntity_EmitSoundParams)(CBaseEntity* pEntity, const char* pszSound, int nPitch, float flVolume, float flDelay); + inline void(FASTCALL* CBaseEntity_SetParent)(CBaseEntity* pEntity, CBaseEntity* pNewParent, CUtlStringToken nBoneOrAttachName, matrix3x4a_t* pOffsetTransform); + inline int(FASTCALL* DispatchParticleEffect)(const char* pszParticleName, int iAttachType, CBaseEntity* pEntity, + char iAttachmentPoint, CUtlSymbolLarge iAttachmentName, bool bResetAllParticlesOnEntity, int nSplitScreenPlayerSlot, IRecipientFilter* a7, byte* a8); + inline SndOpEventGuid_t(FASTCALL* CBaseEntity_EmitSoundFilter)(IRecipientFilter& filter, CEntityIndex ent, const EmitSound_t& params); + inline void(FASTCALL* CBaseEntity_SetMoveType)(CBaseEntity* pThis, MoveType_t nMoveType, MoveCollide_t nMoveCollide); + inline void(FASTCALL* CTakeDamageInfo_Constructor)(CTakeDamageInfo* pThis, CBaseEntity* pInflictor, CBaseEntity* pAttacker, CBaseEntity* pAbility, + const Vector* vecDamageForce, const Vector* vecDamagePosition, float flDamage, int bitsDamageType, int iCustomDamage, void* a10); + inline void(FASTCALL* CNetworkStringTable_DeleteAllStrings)(INetworkStringTable* pThis); +} // namespace addresses \ No newline at end of file diff --git a/src/adminsystem.cpp b/src/adminsystem.cpp index 96c02d04..982c5568 100644 --- a/src/adminsystem.cpp +++ b/src/adminsystem.cpp @@ -17,36 +17,35 @@ * this program. If not, see . */ - #include "adminsystem.h" #include "KeyValues.h" -#include "interfaces/interfaces.h" -#include "filesystem.h" -#include "icvar.h" -#include "playermanager.h" #include "commands.h" #include "ctimer.h" #include "detours.h" #include "discord.h" -#include "utils/entity.h" #include "entity/cbaseentity.h" -#include "entity/cparticlesystem.h" #include "entity/cgamerules.h" +#include "entity/cparticlesystem.h" +#include "filesystem.h" #include "gamesystem.h" -#include "votemanager.h" +#include "icvar.h" +#include "interfaces/interfaces.h" #include "map_votes.h" +#include "playermanager.h" +#include "utils/entity.h" +#include "votemanager.h" #include -extern IVEngineServer2 *g_pEngineServer2; -extern CGameEntitySystem *g_pEntitySystem; -extern CGlobalVars *gpGlobals; -extern CCSGameRules *g_pGameRules; +extern IVEngineServer2* g_pEngineServer2; +extern CGameEntitySystem* g_pEntitySystem; +extern CGlobalVars* gpGlobals; +extern CCSGameRules* g_pGameRules; CAdminSystem* g_pAdminSystem = nullptr; -CUtlMap g_CommandList(0, 0, DefLessFunc(uint32)); +CUtlMap g_CommandList(0, 0, DefLessFunc(uint32)); -void ParseInfraction(const CCommand &args, CCSPlayerController* pAdmin, bool bAdding, CInfractionBase::EInfractionType infType); +void ParseInfraction(const CCommand& args, CCSPlayerController* pAdmin, bool bAdding, CInfractionBase::EInfractionType infType); const char* GetActionPhrase(CInfractionBase::EInfractionType infType, GrammarTense iTense, bool bAdding); void PrintSingleAdminAction(const char* pszAdminName, const char* pszTargetName, const char* pszAction, const char* pszAction2 = "", const char* prefix = CHAT_PREFIX) @@ -58,57 +57,57 @@ void PrintMultiAdminAction(ETargetType nType, const char* pszAdminName, const ch { switch (nType) { - case ETargetType::ALL: - PrintSingleAdminAction(pszAdminName, "everyone", pszAction, pszAction2, prefix); - break; - case ETargetType::SPECTATOR: - PrintSingleAdminAction(pszAdminName, "spectators", pszAction, pszAction2, prefix); - break; - case ETargetType::T: - PrintSingleAdminAction(pszAdminName, "terrorists", pszAction, pszAction2, prefix); - break; - case ETargetType::CT: - PrintSingleAdminAction(pszAdminName, "counter-terrorists", pszAction, pszAction2, prefix); - break; - case ETargetType::DEAD: - PrintSingleAdminAction(pszAdminName, "dead players", pszAction, pszAction2, prefix); - break; - case ETargetType::ALIVE: - PrintSingleAdminAction(pszAdminName, "alive players", pszAction, pszAction2, prefix); - break; - case ETargetType::BOT: - PrintSingleAdminAction(pszAdminName, "bots", pszAction, pszAction2, prefix); - break; - case ETargetType::HUMAN: - PrintSingleAdminAction(pszAdminName, "humans", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_SELF: - ClientPrintAll(HUD_PRINTTALK, "%s" ADMIN_PREFIX "%s everyone except %s%s.", prefix, pszAdminName, pszAction, pszAdminName, pszAction2); - break; - case ETargetType::ALL_BUT_RANDOM: - PrintSingleAdminAction(pszAdminName, "everyone except a random player", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_RANDOM_T: - PrintSingleAdminAction(pszAdminName, "everyone except a random terrorist", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_RANDOM_CT: - PrintSingleAdminAction(pszAdminName, "everyone except a random counter-terrorist", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_RANDOM_SPEC: - PrintSingleAdminAction(pszAdminName, "everyone except a random spectator", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_AIM: - PrintSingleAdminAction(pszAdminName, "everyone except a targetted player", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_SPECTATOR: - PrintSingleAdminAction(pszAdminName, "non-spectators", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_T: - PrintSingleAdminAction(pszAdminName, "non-terrorists", pszAction, pszAction2, prefix); - break; - case ETargetType::ALL_BUT_CT: - PrintSingleAdminAction(pszAdminName, "non-counter-terrorists", pszAction, pszAction2, prefix); - break; + case ETargetType::ALL: + PrintSingleAdminAction(pszAdminName, "everyone", pszAction, pszAction2, prefix); + break; + case ETargetType::SPECTATOR: + PrintSingleAdminAction(pszAdminName, "spectators", pszAction, pszAction2, prefix); + break; + case ETargetType::T: + PrintSingleAdminAction(pszAdminName, "terrorists", pszAction, pszAction2, prefix); + break; + case ETargetType::CT: + PrintSingleAdminAction(pszAdminName, "counter-terrorists", pszAction, pszAction2, prefix); + break; + case ETargetType::DEAD: + PrintSingleAdminAction(pszAdminName, "dead players", pszAction, pszAction2, prefix); + break; + case ETargetType::ALIVE: + PrintSingleAdminAction(pszAdminName, "alive players", pszAction, pszAction2, prefix); + break; + case ETargetType::BOT: + PrintSingleAdminAction(pszAdminName, "bots", pszAction, pszAction2, prefix); + break; + case ETargetType::HUMAN: + PrintSingleAdminAction(pszAdminName, "humans", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_SELF: + ClientPrintAll(HUD_PRINTTALK, "%s" ADMIN_PREFIX "%s everyone except %s%s.", prefix, pszAdminName, pszAction, pszAdminName, pszAction2); + break; + case ETargetType::ALL_BUT_RANDOM: + PrintSingleAdminAction(pszAdminName, "everyone except a random player", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_RANDOM_T: + PrintSingleAdminAction(pszAdminName, "everyone except a random terrorist", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_RANDOM_CT: + PrintSingleAdminAction(pszAdminName, "everyone except a random counter-terrorist", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_RANDOM_SPEC: + PrintSingleAdminAction(pszAdminName, "everyone except a random spectator", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_AIM: + PrintSingleAdminAction(pszAdminName, "everyone except a targetted player", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_SPECTATOR: + PrintSingleAdminAction(pszAdminName, "non-spectators", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_T: + PrintSingleAdminAction(pszAdminName, "non-terrorists", pszAction, pszAction2, prefix); + break; + case ETargetType::ALL_BUT_CT: + PrintSingleAdminAction(pszAdminName, "non-counter-terrorists", pszAction, pszAction2, prefix); + break; } } @@ -168,7 +167,7 @@ CON_COMMAND_CHAT_FLAGS(unban, " - Unban a player. Takes decimal STEAM if (!bResult) { ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Couldn't find user with STEAMID64 <%llu> in ban infractions.", iTargetSteamId64); - return; + return; } g_pAdminSystem->SaveInfractions(); @@ -212,13 +211,13 @@ CON_COMMAND_CHAT_FLAGS(kick, " - Kick a player", ADMFLAG_KICK) if (!g_playerManager->CanTargetPlayers(player, args[1], iNumClients, pSlots, NO_TARGET_BLOCKS, nType)) return; - const char *pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; + const char* pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; for (int i = 0; i < iNumClients; i++) { CCSPlayerController* pTarget = CCSPlayerController::FromSlot(pSlots[i]); ZEPlayer* pTargetPlayer = pTarget->GetZEPlayer(); - + g_pEngineServer2->DisconnectClient(pTargetPlayer->GetPlayerSlot(), NETWORK_DISCONNECT_KICKED); if (iNumClients == 1) @@ -243,7 +242,7 @@ CON_COMMAND_CHAT_FLAGS(slay, " - Slay a player", ADMFLAG_SLAY) if (!g_playerManager->CanTargetPlayers(player, args[1], iNumClients, pSlots, NO_DEAD, nType)) return; - const char *pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; + const char* pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; for (int i = 0; i < iNumClients; i++) { @@ -273,12 +272,12 @@ CON_COMMAND_CHAT_FLAGS(slap, " [damage] - Slap a player", ADMFLAG_SLAY) if (!g_playerManager->CanTargetPlayers(player, args[1], iNumClients, pSlots, NO_DEAD, nType)) return; - const char *pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; + const char* pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; for (int i = 0; i < iNumClients; i++) { - CBasePlayerController *pTarget = (CBasePlayerController *)g_pEntitySystem->GetEntityInstance((CEntityIndex)(pSlots[i] + 1)); - CBasePlayerPawn *pPawn = pTarget->m_hPawn(); + CBasePlayerController* pTarget = (CBasePlayerController*)g_pEntitySystem->GetEntityInstance((CEntityIndex)(pSlots[i] + 1)); + CBasePlayerPawn* pPawn = pTarget->m_hPawn(); if (!pPawn) continue; @@ -290,12 +289,12 @@ CON_COMMAND_CHAT_FLAGS(slap, " [damage] - Slap a player", ADMFLAG_SLAY) velocity.z += rand() % 200 + 100; pPawn->SetAbsVelocity(velocity); - float flDamage = V_StringToFloat32 (args[2], 0); - + float flDamage = V_StringToFloat32(args[2], 0); + if (flDamage > 0) { // Default to the world - CBaseEntity *pAttacker = (CBaseEntity*)g_pEntitySystem->GetEntityInstance(CEntityIndex(0)); + CBaseEntity* pAttacker = (CBaseEntity*)g_pEntitySystem->GetEntityInstance(CEntityIndex(0)); if (player) pAttacker = player->GetPlayerPawn(); @@ -402,9 +401,9 @@ CON_COMMAND_CHAT_FLAGS(setteam, " - Set a player's team", ADM if (!g_playerManager->CanTargetPlayers(player, args[1], iNumClients, pSlots, NO_TARGET_BLOCKS, nType)) return; - const char *pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; + const char* pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; - constexpr const char *teams[] = {"none", "spectators", "terrorists", "counter-terrorists"}; + constexpr const char* teams[] = {"none", "spectators", "terrorists", "counter-terrorists"}; char szAction[64]; V_snprintf(szAction, sizeof(szAction), " to %s", teams[iTeam]); @@ -435,7 +434,7 @@ CON_COMMAND_CHAT_FLAGS(noclip, "[name] - Toggle noclip on a player", ADMFLAG_CHE return; CCSPlayerController* pTarget = CCSPlayerController::FromSlot(pSlots[0]); - CBasePlayerPawn *pPawn = pTarget->m_hPawn(); + CBasePlayerPawn* pPawn = pTarget->m_hPawn(); const char* pszCommandPlayerName = player ? player->GetPlayerName() : CONSOLE_NAME; if (!pPawn) @@ -469,7 +468,7 @@ CON_COMMAND_CHAT_FLAGS(entfire, " [parameter] - Fire outputs at en int iFoundEnts = 0; - CBaseEntity *pTarget = nullptr; + CBaseEntity* pTarget = nullptr; // The idea here is to only use one of the targeting modes at once, prioritizing !picker then targetname/!self then classname // Try picker first, FindEntityByName can also take !picker but it always uses player 0 so we have to do this ourselves @@ -495,7 +494,7 @@ CON_COMMAND_CHAT_FLAGS(entfire, " [parameter] - Fire outputs at en iFoundEnts++; } } - + if (!iFoundEnts) { while ((pTarget = UTIL_FindEntityByName(pTarget, args[1], player))) @@ -539,7 +538,7 @@ CON_COMMAND_CHAT_FLAGS(entfirepawn, " [parameter] - Fire outputs at for (int i = 0; i < iNumClients; i++) { - CCSPlayerController *pTarget = CCSPlayerController::FromSlot(pSlots[i]); + CCSPlayerController* pTarget = CCSPlayerController::FromSlot(pSlots[i]); if (!pTarget->GetPawn()) continue; @@ -570,7 +569,7 @@ CON_COMMAND_CHAT_FLAGS(entfirecontroller, " [parameter] - Fire out for (int i = 0; i < iNumClients; i++) { - CCSPlayerController *pTarget = CCSPlayerController::FromSlot(pSlots[i]); + CCSPlayerController* pTarget = CCSPlayerController::FromSlot(pSlots[i]); pTarget->AcceptInput(args[2], args[3], player, player); iFoundEnts++; } @@ -632,8 +631,7 @@ CON_COMMAND_CHAT_FLAGS(map, " - Change map", ADMFLAG_CHANGEMAP) ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Changing map to %s...", pszMapName); - new CTimer(5.0f, false, true, [sCommand]() - { + new CTimer(5.0f, false, true, [sCommand]() { g_pEngineServer2->ServerCommand(sCommand.c_str()); return -1.0f; }); @@ -643,8 +641,7 @@ CON_COMMAND_CHAT_FLAGS(map, " - Change map", ADMFLAG_CHANGEMAP) ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Changing map to %s...", pszMapName); - new CTimer(5.0f, false, true, [sMapName]() - { + new CTimer(5.0f, false, true, [sMapName]() { g_pEngineServer2->ChangeLevel(sMapName.c_str(), nullptr); return -1.0f; }); @@ -735,7 +732,7 @@ CON_COMMAND_CHAT_FLAGS(pm, " - Private message a player. This wi if (player == pTarget) { - //Player is PMing themselves (bind to display message in chat probably), so no need to echo to all admins + // Player is PMing themselves (bind to display message in chat probably), so no need to echo to all admins ClientPrint(player, HUD_PRINTTALK, "\x0A[SELF]\x0C %s\1: \x0B%s", pszName, strMessage.c_str()); return; } @@ -865,7 +862,6 @@ CON_COMMAND_CHAT_FLAGS(who, "- List the flags of all online players", ADMFLAG_GE ClientPrint(player, HUD_PRINTCONSOLE, "|----------------------|----------------------------------------------------|-------------------|"); for (auto [strPlayerName, strFlags, iSteamID] : rgNameSlotID) { - if (strPlayerName.length() % 2 == 1) strPlayerName = strPlayerName + ' '; if (strPlayerName.length() < 20) @@ -936,7 +932,7 @@ CON_COMMAND_CHAT(status, " - Checks a player's active punishments. Non-adm CCSPlayerController* pTarget = CCSPlayerController::FromSlot(pSlots[0]); pTargetPlayer = pTarget->GetZEPlayer(); - + if (!pTargetPlayer->IsMuted() && !pTargetPlayer->IsGagged()) { if (pTarget == player) @@ -1134,7 +1130,7 @@ bool CAdminSystem::LoadAdmins() KeyValues* pKV = new KeyValues("admins"); KeyValues::AutoDelete autoDelete(pKV); - const char *pszPath = "addons/cs2fixes/configs/admins.cfg"; + const char* pszPath = "addons/cs2fixes/configs/admins.cfg"; if (!pKV->LoadFromFile(g_pFullFileSystem, pszPath)) { @@ -1143,9 +1139,9 @@ bool CAdminSystem::LoadAdmins() } for (KeyValues* pKey = pKV->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey()) { - const char *pszName = pKey->GetName(); - const char *pszSteamID = pKey->GetString("steamid", nullptr); - const char *pszFlags = pKey->GetString("flags", nullptr); + const char* pszName = pKey->GetName(); + const char* pszSteamID = pKey->GetString("steamid", nullptr); + const char* pszFlags = pKey->GetString("flags", nullptr); int iImmunityLevel = pKey->GetInt("immunity", -1); if (!pszSteamID) @@ -1186,7 +1182,7 @@ bool CAdminSystem::LoadInfractions() KeyValues* pKV = new KeyValues("infractions"); KeyValues::AutoDelete autoDelete(pKV); - const char *pszPath = "addons/cs2fixes/data/infractions.txt"; + const char* pszPath = "addons/cs2fixes/data/infractions.txt"; if (!pKV->LoadFromFile(g_pFullFileSystem, pszPath)) { @@ -1220,17 +1216,17 @@ bool CAdminSystem::LoadInfractions() switch (iType) { - case CInfractionBase::Ban: - AddInfraction(new CBanInfraction(iEndTime, iSteamId, true)); - break; - case CInfractionBase::Mute: - AddInfraction(new CMuteInfraction(iEndTime, iSteamId, true)); - break; - case CInfractionBase::Gag: - AddInfraction(new CGagInfraction(iEndTime, iSteamId, true)); - break; - default: - Warning("Invalid infraction type %d\n", iType); + case CInfractionBase::Ban: + AddInfraction(new CBanInfraction(iEndTime, iSteamId, true)); + break; + case CInfractionBase::Mute: + AddInfraction(new CMuteInfraction(iEndTime, iSteamId, true)); + break; + case CInfractionBase::Gag: + AddInfraction(new CGagInfraction(iEndTime, iSteamId, true)); + break; + default: + Warning("Invalid infraction type %d\n", iType); } } @@ -1274,11 +1270,10 @@ void CAdminSystem::AddInfraction(CInfractionBase* infraction) m_vecInfractions.AddToTail(infraction); } - // This function can run at least twice when a player connects: Immediately upon client connection, and also upon getting authenticated by steam. // It's also run when we're periodically checking for infraction expiry in the case of mutes/gags. // This returns false only when called from ClientConnect and the player is banned in order to reject them. -bool CAdminSystem::ApplyInfractions(ZEPlayer *player) +bool CAdminSystem::ApplyInfractions(ZEPlayer* player) { FOR_EACH_VEC(m_vecInfractions, i) { @@ -1303,14 +1298,14 @@ bool CAdminSystem::ApplyInfractions(ZEPlayer *player) // We are called from ClientConnect and the player is banned, immediately reject them if (!player->IsConnected() && m_vecInfractions[i]->GetType() == CInfractionBase::EInfractionType::Ban) return false; - + m_vecInfractions[i]->ApplyInfraction(player); } return true; } -bool CAdminSystem::FindAndRemoveInfraction(ZEPlayer *player, CInfractionBase::EInfractionType type) +bool CAdminSystem::FindAndRemoveInfraction(ZEPlayer* player, CInfractionBase::EInfractionType type) { FOR_EACH_VEC_BACK(m_vecInfractions, i) { @@ -1318,7 +1313,7 @@ bool CAdminSystem::FindAndRemoveInfraction(ZEPlayer *player, CInfractionBase::EI { m_vecInfractions[i]->UndoInfraction(player); m_vecInfractions.Remove(i); - + return true; } } @@ -1333,7 +1328,7 @@ bool CAdminSystem::FindAndRemoveInfractionSteamId64(uint64 steamid64, CInfractio if (m_vecInfractions[i]->GetSteamId64() == steamid64 && m_vecInfractions[i]->GetType() == type) { m_vecInfractions.Remove(i); - + return true; } } @@ -1341,7 +1336,7 @@ bool CAdminSystem::FindAndRemoveInfractionSteamId64(uint64 steamid64, CInfractio return false; } -CAdmin *CAdminSystem::FindAdmin(uint64 iSteamID) +CAdmin* CAdminSystem::FindAdmin(uint64 iSteamID) { FOR_EACH_VEC(m_vecAdmins, i) { @@ -1376,10 +1371,8 @@ void CAdminSystem::AddDisconnectedPlayer(const char* pszName, uint64 xuid, const { auto plyInfo = std::make_tuple(pszName, xuid, pszIP); for (auto& dcPlyInfo : m_rgDCPly) - { if (std::get<1>(dcPlyInfo) == std::get<1>(plyInfo)) return; - } m_rgDCPly[m_iDCPlyIndex] = plyInfo; m_iDCPlyIndex = (m_iDCPlyIndex + 1) % 20; } @@ -1411,7 +1404,7 @@ void CAdminSystem::ShowDisconnectedPlayers(CCSPlayerController* const pAdmin) ClientPrint(pAdmin, HUD_PRINTTALK, CHAT_PREFIX "No players have disconnected yet."); } -void CBanInfraction::ApplyInfraction(ZEPlayer *player) +void CBanInfraction::ApplyInfraction(ZEPlayer* player) { g_pEngineServer2->DisconnectClient(player->GetPlayerSlot(), NETWORK_DISCONNECT_KICKBANADDED); // "Kicked and banned" } @@ -1421,17 +1414,17 @@ void CMuteInfraction::ApplyInfraction(ZEPlayer* player) player->SetMuted(true); } -void CMuteInfraction::UndoInfraction(ZEPlayer *player) +void CMuteInfraction::UndoInfraction(ZEPlayer* player) { player->SetMuted(false); } -void CGagInfraction::ApplyInfraction(ZEPlayer *player) +void CGagInfraction::ApplyInfraction(ZEPlayer* player) { player->SetGagged(true); } -void CGagInfraction::UndoInfraction(ZEPlayer *player) +void CGagInfraction::UndoInfraction(ZEPlayer* player) { player->SetGagged(false); } @@ -1475,7 +1468,7 @@ int ParseTimeInput(std::string strTime) if (strNumbers.length() == 0) return -1; else if (strNumbers.length() > 9) - // Really high number, just return perma + // Really high number, just return perma return 0; // stoi should be exception safe here due to above checks @@ -1524,7 +1517,7 @@ std::string GetReason(const CCommand& args, int iArgsBefore, bool bStripUnicode) std::string strOutput = ""; if (bStripUnicode) - std::copy_if(strReason.cbegin(), strReason.cend(), std::back_inserter(strOutput), [](unsigned char c) {return c < 128; }); + std::copy_if(strReason.cbegin(), strReason.cend(), std::back_inserter(strOutput), [](unsigned char c) { return c < 128; }); else strOutput = strReason; @@ -1537,7 +1530,7 @@ std::string GetReason(const CCommand& args, int iArgsBefore, bool bStripUnicode) return strOutput; } -void ParseInfraction(const CCommand &args, CCSPlayerController* pAdmin, bool bAdding, CInfractionBase::EInfractionType infType) +void ParseInfraction(const CCommand& args, CCSPlayerController* pAdmin, bool bAdding, CInfractionBase::EInfractionType infType) { if (args.ArgC() < 2 || (bAdding && args.ArgC() < 3)) { @@ -1547,7 +1540,8 @@ void ParseInfraction(const CCommand &args, CCSPlayerController* pAdmin, bool bAd } int iDuration = bAdding ? ParseTimeInput(args[2]) : 0; - if (bAdding && iDuration < 0) { + if (bAdding && iDuration < 0) + { ClientPrint(pAdmin, HUD_PRINTTALK, CHAT_PREFIX "Invalid duration."); return; } @@ -1576,7 +1570,7 @@ void ParseInfraction(const CCommand &args, CCSPlayerController* pAdmin, bool bAd return; } - const char *pszCommandPlayerName = pAdmin ? pAdmin->GetPlayerName() : CONSOLE_NAME; + const char* pszCommandPlayerName = pAdmin ? pAdmin->GetPlayerName() : CONSOLE_NAME; for (int i = 0; i < iNumClients; i++) { @@ -1627,10 +1621,8 @@ void ParseInfraction(const CCommand &args, CCSPlayerController* pAdmin, bool bAd } if (iNumClients > 1) - { PrintMultiAdminAction(nType, pszCommandPlayerName, GetActionPhrase(infType, GrammarTense::Past, bAdding), bAdding ? (" for " + FormatTime(iDuration, false)).c_str() : ""); - } g_pAdminSystem->SaveInfractions(); } diff --git a/src/adminsystem.h b/src/adminsystem.h index 481d5a2f..abbc2389 100644 --- a/src/adminsystem.h +++ b/src/adminsystem.h @@ -19,10 +19,11 @@ #pragma once #include "platform.h" -#include "utlvector.h" #include "playermanager.h" +#include "utlvector.h" #include +// clang-format off #define ADMFLAG_NONE (0) #define ADMFLAG_RESERVATION (1 << 0) // a #define ADMFLAG_GENERIC (1 << 1) // b @@ -50,6 +51,7 @@ #define ADMFLAG_CUSTOM10 (1 << 23) // x #define ADMFLAG_CUSTOM11 (1 << 24) // y #define ADMFLAG_ROOT (1 << 25) // z +// clang-format on #define ADMIN_PREFIX "Admin %s has " #define CONSOLE_NAME "\2CONSOLE\1" // color it to indicate that it isnt a regular player using the command @@ -67,7 +69,8 @@ enum GrammarTense class CInfractionBase { public: - CInfractionBase(time_t duration, uint64 steamId, bool bEndTime = false) : m_iSteamID(steamId) + CInfractionBase(time_t duration, uint64 steamId, bool bEndTime = false) : + m_iSteamID(steamId) { // The duration is in minutes here if (!bEndTime) @@ -84,7 +87,7 @@ class CInfractionBase virtual EInfractionType GetType() = 0; virtual void ApplyInfraction(ZEPlayer*) = 0; - virtual void UndoInfraction(ZEPlayer *) = 0; + virtual void UndoInfraction(ZEPlayer*) = 0; time_t GetTimestamp() { return m_iTimestamp; } uint64 GetSteamId64() { return m_iSteamID; } @@ -97,22 +100,22 @@ class CBanInfraction : public CInfractionBase { public: using CInfractionBase::CInfractionBase; - + EInfractionType GetType() override { return Ban; } void ApplyInfraction(ZEPlayer*) override; // This isn't needed as we'll just not kick the player when checking infractions upon joining - void UndoInfraction(ZEPlayer *) override {} + void UndoInfraction(ZEPlayer*) override {} }; -class CMuteInfraction :public CInfractionBase +class CMuteInfraction : public CInfractionBase { public: using CInfractionBase::CInfractionBase; - + EInfractionType GetType() override { return Mute; } void ApplyInfraction(ZEPlayer*) override; - void UndoInfraction(ZEPlayer *) override; + void UndoInfraction(ZEPlayer*) override; }; class CGagInfraction : public CInfractionBase @@ -121,14 +124,14 @@ class CGagInfraction : public CInfractionBase using CInfractionBase::CInfractionBase; EInfractionType GetType() override { return Gag; } - void ApplyInfraction(ZEPlayer *) override; - void UndoInfraction(ZEPlayer *) override; + void ApplyInfraction(ZEPlayer*) override; + void UndoInfraction(ZEPlayer*) override; }; class CAdmin { public: - CAdmin(const char* pszName, uint64 iSteamID, uint64 iFlags, int iAdminImmunity) : + CAdmin(const char* pszName, uint64 iSteamID, uint64 iFlags, int iAdminImmunity) : m_pszName(pszName), m_iSteamID(iSteamID), m_iFlags(iFlags), m_iAdminImmunity(iAdminImmunity) {} @@ -152,10 +155,10 @@ class CAdminSystem bool LoadInfractions(); void AddInfraction(CInfractionBase*); void SaveInfractions(); - bool ApplyInfractions(ZEPlayer *player); - bool FindAndRemoveInfraction(ZEPlayer *player, CInfractionBase::EInfractionType type); + bool ApplyInfractions(ZEPlayer* player); + bool FindAndRemoveInfraction(ZEPlayer* player, CInfractionBase::EInfractionType type); bool FindAndRemoveInfractionSteamId64(uint64 steamid64, CInfractionBase::EInfractionType type); - CAdmin *FindAdmin(uint64 iSteamID); + CAdmin* FindAdmin(uint64 iSteamID); uint64 ParseFlags(const char* pszFlags); void AddDisconnectedPlayer(const char* pszName, uint64 xuid, const char* pszIP); void ShowDisconnectedPlayers(CCSPlayerController* const pAdmin); @@ -163,13 +166,13 @@ class CAdminSystem private: CUtlVector m_vecAdmins; CUtlVector m_vecInfractions; - + // Implemented as a circular buffer. std::tuple m_rgDCPly[20]; int m_iDCPlyIndex; }; -extern CAdminSystem *g_pAdminSystem; +extern CAdminSystem* g_pAdminSystem; // Given a formatted time entered by an admin, return the minutes int ParseTimeInput(std::string strTime); diff --git a/src/buttonwatch.cpp b/src/buttonwatch.cpp index 922d16ce..7c98c9a6 100644 --- a/src/buttonwatch.cpp +++ b/src/buttonwatch.cpp @@ -1,25 +1,28 @@ /** -* ============================================================================= -* CS2Fixes -* Copyright (C) 2023-2024 Source2ZE -* ============================================================================= -* -* This program is free software; you can redistribute it and/or modify it under -* the terms of the GNU General Public License, version 3.0, as published by the -* Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, but WITHOUT -* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -* details. -* -* You should have received a copy of the GNU General Public License along with -* this program. If not, see . -*/ + * ============================================================================= + * CS2Fixes + * Copyright (C) 2023-2024 Source2ZE + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ #include "buttonwatch.h" +#include "commands.h" +#include "cs2fixes.h" #include "ctimer.h" +#include "detours.h" #include "entity.h" #include "entity/cbaseplayercontroller.h" #include "entity/ccsplayercontroller.h" @@ -28,120 +31,113 @@ #include "entity/cgamerules.h" #include "entity/clogiccase.h" #include "entity/cpointviewcontrol.h" -#include "detours.h" -#include "cs2fixes.h" -#include "commands.h" CON_COMMAND_F(cs2f_enable_button_watch, "INCOMPATIBLE WITH CS#. Whether to enable button watch or not.", FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | FCVAR_PROTECTED) { - if (args.ArgC() < 2) - { - Msg("%s %i\n", args[0], IsButtonWatchEnabled()); - return; - } - - if (!V_StringToBool(args[1], false) || !SetupFireOutputInternalDetour()) - mapIOFunctions.erase("buttonwatch"); - else if (!IsButtonWatchEnabled()) - mapIOFunctions["buttonwatch"] = ButtonWatch; + if (args.ArgC() < 2) + { + Msg("%s %i\n", args[0], IsButtonWatchEnabled()); + return; + } + + if (!V_StringToBool(args[1], false) || !SetupFireOutputInternalDetour()) + mapIOFunctions.erase("buttonwatch"); + else if (!IsButtonWatchEnabled()) + mapIOFunctions["buttonwatch"] = ButtonWatch; } CON_COMMAND_CHAT_FLAGS(bw, "- Toggle button watch display", ADMFLAG_GENERIC) { - if (!IsButtonWatchEnabled()) - { - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Button watch is disabled on this server."); - return; - } - - if (!player) - { - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You cannot use this command from the server console."); - return; - } - - ZEPlayer* zpPlayer = player->GetZEPlayer(); - if (!zpPlayer) - { - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Something went wrong, please wait a moment before trying this command again."); - return; - } - - zpPlayer->CycleButtonWatch(); - - switch (zpPlayer->GetButtonWatchMode()) - { - case 0: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x02 disabled\1 button watch."); - break; - case 1: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x04 enabled\1 button watch in chat."); - break; - case 2: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x04 enabled\1 button watch in console."); - break; - case 3: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x04 enabled\1 button watch in chat and console."); - break; - } + if (!IsButtonWatchEnabled()) + { + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Button watch is disabled on this server."); + return; + } + + if (!player) + { + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You cannot use this command from the server console."); + return; + } + + ZEPlayer* zpPlayer = player->GetZEPlayer(); + if (!zpPlayer) + { + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Something went wrong, please wait a moment before trying this command again."); + return; + } + + zpPlayer->CycleButtonWatch(); + + switch (zpPlayer->GetButtonWatchMode()) + { + case 0: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x02 disabled\1 button watch."); + break; + case 1: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x04 enabled\1 button watch in chat."); + break; + case 2: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x04 enabled\1 button watch in console."); + break; + case 3: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have\x04 enabled\1 button watch in chat and console."); + break; + } } bool IsButtonWatchEnabled() { - return std::any_of(mapIOFunctions.begin(), mapIOFunctions.end(), [](const auto& p) { - return p.first == "buttonwatch"; - }); + return std::any_of(mapIOFunctions.begin(), mapIOFunctions.end(), [](const auto& p) { + return p.first == "buttonwatch"; + }); } -std::map mapRecentEnts; +std::map mapRecentEnts; void ButtonWatch(const CEntityIOOutput* pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* value, float flDelay) { - if (!IsButtonWatchEnabled() || V_stricmp(pThis->m_pDesc->m_pName, "OnPressed") || - !pActivator || !((CBaseEntity*)pActivator)->IsPawn() || - !pCaller || mapRecentEnts.contains(pCaller->GetEntityIndex().Get())) - return; - - CCSPlayerController* ccsPlayer = CCSPlayerController::FromPawn(static_cast(pActivator)); - std::string strPlayerName = ccsPlayer->GetPlayerName(); - - ZEPlayer* zpPlayer = ccsPlayer->GetZEPlayer(); - std::string strPlayerID = ""; - if (zpPlayer && !zpPlayer->IsFakeClient()) - { - strPlayerID = std::to_string(zpPlayer->IsAuthenticated() ? zpPlayer->GetSteamId64() : zpPlayer->GetUnauthenticatedSteamId64()); - strPlayerID = "(" + strPlayerID + ")"; - } - - std::string strButton = std::to_string(pCaller->GetEntityIndex().Get()) + " " + - std::string(((CBaseEntity*)pCaller)->GetName()); - - for (int i = 0; i < gpGlobals->maxClients; i++) - { - CCSPlayerController* ccsPlayer = CCSPlayerController::FromSlot(i); - if (!ccsPlayer) - continue; - - ZEPlayer* zpPlayer = ccsPlayer->GetZEPlayer(); - if (!zpPlayer) - continue; - - if (zpPlayer->GetButtonWatchMode() % 2 == 1) - ClientPrint(ccsPlayer, HUD_PRINTTALK, " \x02[BW]\x0C %s\1 pressed button \x0C%s\1", strPlayerName.c_str(), strButton.c_str()); - if (zpPlayer->GetButtonWatchMode() >= 2) - { - ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "------------------------------------ [ButtonWatch] ------------------------------------"); - ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "Player: %s %s", strPlayerName.c_str(), strPlayerID.c_str()); - ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "Button: %s", strButton.c_str()); - ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "---------------------------------------------------------------------------------------"); - } - } - - // Limit each button to only printing out at most once every 5 seconds - int iIndex = pCaller->GetEntityIndex().Get(); - mapRecentEnts[iIndex] = true; - new CTimer(5.0f, true, true, [iIndex]() - { - mapRecentEnts.erase(iIndex); - return -1.0f; - }); + if (!IsButtonWatchEnabled() || V_stricmp(pThis->m_pDesc->m_pName, "OnPressed") || !pActivator || !((CBaseEntity*)pActivator)->IsPawn() || !pCaller || mapRecentEnts.contains(pCaller->GetEntityIndex().Get())) + return; + + CCSPlayerController* ccsPlayer = CCSPlayerController::FromPawn(static_cast(pActivator)); + std::string strPlayerName = ccsPlayer->GetPlayerName(); + + ZEPlayer* zpPlayer = ccsPlayer->GetZEPlayer(); + std::string strPlayerID = ""; + if (zpPlayer && !zpPlayer->IsFakeClient()) + { + strPlayerID = std::to_string(zpPlayer->IsAuthenticated() ? zpPlayer->GetSteamId64() : zpPlayer->GetUnauthenticatedSteamId64()); + strPlayerID = "(" + strPlayerID + ")"; + } + + std::string strButton = std::to_string(pCaller->GetEntityIndex().Get()) + " " + std::string(((CBaseEntity*)pCaller)->GetName()); + + for (int i = 0; i < gpGlobals->maxClients; i++) + { + CCSPlayerController* ccsPlayer = CCSPlayerController::FromSlot(i); + if (!ccsPlayer) + continue; + + ZEPlayer* zpPlayer = ccsPlayer->GetZEPlayer(); + if (!zpPlayer) + continue; + + if (zpPlayer->GetButtonWatchMode() % 2 == 1) + ClientPrint(ccsPlayer, HUD_PRINTTALK, " \x02[BW]\x0C %s\1 pressed button \x0C%s\1", strPlayerName.c_str(), strButton.c_str()); + if (zpPlayer->GetButtonWatchMode() >= 2) + { + ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "------------------------------------ [ButtonWatch] ------------------------------------"); + ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "Player: %s %s", strPlayerName.c_str(), strPlayerID.c_str()); + ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "Button: %s", strButton.c_str()); + ClientPrint(ccsPlayer, HUD_PRINTCONSOLE, "---------------------------------------------------------------------------------------"); + } + } + + // Limit each button to only printing out at most once every 5 seconds + int iIndex = pCaller->GetEntityIndex().Get(); + mapRecentEnts[iIndex] = true; + new CTimer(5.0f, true, true, [iIndex]() { + mapRecentEnts.erase(iIndex); + return -1.0f; + }); } \ No newline at end of file diff --git a/src/buttonwatch.h b/src/buttonwatch.h index f15877e9..f3c7c4aa 100644 --- a/src/buttonwatch.h +++ b/src/buttonwatch.h @@ -1,21 +1,21 @@ /** -* ============================================================================= -* CS2Fixes -* Copyright (C) 2023-2024 Source2ZE -* ============================================================================= -* -* This program is free software; you can redistribute it and/or modify it under -* the terms of the GNU General Public License, version 3.0, as published by the -* Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, but WITHOUT -* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -* details. -* -* You should have received a copy of the GNU General Public License along with -* this program. If not, see . -*/ + * ============================================================================= + * CS2Fixes + * Copyright (C) 2023-2024 Source2ZE + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ #pragma once #include "detours.h" diff --git a/src/cdetour.h b/src/cdetour.h index a20573b8..9e1493e7 100644 --- a/src/cdetour.h +++ b/src/cdetour.h @@ -18,19 +18,19 @@ */ #pragma once -#include +#include "addresses.h" #include "funchook.h" +#include "gameconfig.h" #include "module.h" -#include "utlvector.h" #include "plat.h" -#include "gameconfig.h" -#include "addresses.h" +#include "utlvector.h" +#include class CDetourBase { public: virtual const char* GetName() = 0; - virtual bool CreateDetour(CGameConfig *gameConfig) = 0; + virtual bool CreateDetour(CGameConfig* gameConfig) = 0; virtual void FreeDetour() = 0; virtual void EnableDetour() = 0; virtual void DisableDetour() = 0; @@ -40,23 +40,23 @@ template class CDetour : public CDetourBase { public: - CDetour(T *pfnDetour, const char *pszName); + CDetour(T* pfnDetour, const char* pszName); ~CDetour() { FreeDetour(); } - bool CreateDetour(CGameConfig *gameConfig) override; + bool CreateDetour(CGameConfig* gameConfig) override; void EnableDetour(); void DisableDetour(); void FreeDetour() override; const char* GetName() override { return m_pszName; } - T *GetFunc() { return m_pfnFunc; } + T* GetFunc() { return m_pfnFunc; } // Shorthand for calling original. template - auto operator()(Args &&...args) + auto operator()(Args&&... args) { return std::invoke(m_pfnFunc, std::forward(args)...); } @@ -75,7 +75,7 @@ class CDetour : public CDetourBase extern CUtlVector g_vecDetours; template -CDetour::CDetour(T *pfnDetour, const char *pszName) : +CDetour::CDetour(T* pfnDetour, const char* pszName) : m_pfnDetour(pfnDetour), m_pszName(pszName) { m_hook = nullptr; @@ -88,13 +88,13 @@ CDetour::CDetour(T *pfnDetour, const char *pszName) : } template -bool CDetour::CreateDetour(CGameConfig *gameConfig) +bool CDetour::CreateDetour(CGameConfig* gameConfig) { m_pfnFunc = (T*)gameConfig->ResolveSignature(m_pszName); if (!m_pfnFunc) return false; - T *pFunc = m_pfnFunc; + T* pFunc = m_pfnFunc; m_hook = funchook_create(); funchook_prepare(m_hook, (void**)&m_pfnFunc, (void*)m_pfnDetour); @@ -120,11 +120,11 @@ void CDetour::EnableDetour() template void CDetour::DisableDetour() { - if (!m_hook ) + if (!m_hook) return; int error = funchook_uninstall(m_hook, 0); - + if (!error) m_bInstalled = false; else diff --git a/src/clientframe.h b/src/clientframe.h index 71d58db0..3a7df38f 100644 --- a/src/clientframe.h +++ b/src/clientframe.h @@ -1,13 +1,13 @@ //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // -// Purpose: +// Purpose: // //=============================================================================// #ifndef CLIENTFRAME_H #define CLIENTFRAME_H #ifdef _WIN32 -#pragma once + #pragma once #endif #include @@ -22,24 +22,23 @@ class CClientFrame virtual ~CClientFrame(); public: - // State of entities this frame from the POV of the client. - int tick_count; // server tick of this snapshot - int last_entity; // highest entity index - CClientFrame* m_pNext; + int tick_count; // server tick of this snapshot + int last_entity; // highest entity index + CClientFrame* m_pNext; // Index of snapshot entry that stores the entities that were active and the serial numbers // for the frame number this packed entity corresponds to // m_pSnapshot MUST be private to force using SetSnapshot(), see reference counters - CFrameSnapshot *m_pSnapshot; + CFrameSnapshot* m_pSnapshot; // Used by server to indicate if the entity was in the player's pvs - CBitVec transmit_entity; // if bit n is set, entity n will be send to client - CBitVec unkBitVec2080; - CBitVec unkBitVec4128; - CBitVec unkBitVec6176; - CBitVec *transmit_always; // if bit is set, don't do PVS checks before sending (HLTV only) -}; // sizeof 8232 + CBitVec transmit_entity; // if bit n is set, entity n will be send to client + CBitVec unkBitVec2080; + CBitVec unkBitVec4128; + CBitVec unkBitVec6176; + CBitVec* transmit_always; // if bit is set, don't do PVS checks before sending (HLTV only) +}; // sizeof 8232 // TODO substitute CClientFrameManager with an intelligent structure (Tree, hash, cache, etc) class CClientFrameManager @@ -49,8 +48,8 @@ class CClientFrameManager public: char pad120[120]; - CUtlMemoryPool< CClientFrame > m_ClientFramePool; - CClientFrame *m_Frames; // updates can be delta'ed from here + CUtlMemoryPool m_ClientFramePool; + CClientFrame* m_Frames; // updates can be delta'ed from here }; // sizeof 288 #endif // CLIENTFRAME_H \ No newline at end of file diff --git a/src/commands.cpp b/src/commands.cpp index 6abcb3aa..69be8e1c 100644 --- a/src/commands.cpp +++ b/src/commands.cpp @@ -17,31 +17,30 @@ * this program. If not, see . */ -#include "usermessages.pb.h" -#include "detours.h" -#include "common.h" -#include "utlstring.h" -#include "recipientfilters.h" #include "commands.h" -#include "utils/entity.h" +#include "adminsystem.h" +#include "common.h" +#include "ctimer.h" +#include "detours.h" +#include "discord.h" +#include "engine/igameeventsystem.h" #include "entity/cbaseentity.h" -#include "entity/ccsweaponbase.h" +#include "entity/cbasemodelentity.h" #include "entity/ccsplayercontroller.h" #include "entity/ccsplayerpawn.h" -#include "entity/cbasemodelentity.h" #include "entity/ccsweaponbase.h" #include "entity/cparticlesystem.h" #include "entity/lights.h" -#include "playermanager.h" -#include "adminsystem.h" -#include "leader.h" -#include "ctimer.h" #include "httpmanager.h" -#include "discord.h" -#include "zombiereborn.h" +#include "leader.h" #include "networksystem/inetworkmessages.h" -#include "engine/igameeventsystem.h" +#include "playermanager.h" +#include "recipientfilters.h" #include "tier0/vprof.h" +#include "usermessages.pb.h" +#include "utils/entity.h" +#include "utlstring.h" +#include "zombiereborn.h" #undef snprintf #include "vendor/nlohmann/json.hpp" @@ -49,8 +48,8 @@ using json = nlohmann::json; -extern IGameEventSystem *g_gameEventSystem; -extern CGameEntitySystem *g_pEntitySystem; +extern IGameEventSystem* g_gameEventSystem; +extern CGameEntitySystem* g_pEntitySystem; extern IVEngineServer2* g_pEngineServer2; extern ISteamHTTP* g_http; @@ -60,6 +59,7 @@ bool g_bEnableAdminCommands; FAKE_BOOL_CVAR(cs2f_commands_enable, "Whether to enable chat commands", g_bEnableCommands, false, 0) FAKE_BOOL_CVAR(cs2f_admin_commands_enable, "Whether to enable admin chat commands", g_bEnableAdminCommands, false, 0) +// clang-format off WeaponMapEntry_t WeaponMap[] = { {{"bizon"}, "weapon_bizon", "PP-Bizon", 1400, 26, GEAR_SLOT_RIFLE}, {{"mac10", "mac"}, "weapon_mac10", "MAC-10", 1050, 27, GEAR_SLOT_RIFLE}, @@ -99,6 +99,7 @@ WeaponMapEntry_t WeaponMap[] = { {{"molotov"}, "weapon_molotov", "Molotov", 400, 46, GEAR_SLOT_GRENADES, 1}, {{"kevlar"}, "item_kevlar", "Kevlar Vest", 650, 50, GEAR_SLOT_UTILITY}, }; +// clang-format on bool g_bEnableWeapons = false; @@ -126,9 +127,9 @@ int GetGrenadeAmmo(CCSPlayer_WeaponServices* pWeaponServices, WeaponMapEntry_t w int GetGrenadeAmmoTotal(CCSPlayer_WeaponServices* pWeaponServices) { - if(!pWeaponServices) + if (!pWeaponServices) return -1; - + int grenadeAmmoOffsets[] = { AMMO_OFFSET_HEGRENADE, AMMO_OFFSET_FLASHBANG, @@ -139,10 +140,8 @@ int GetGrenadeAmmoTotal(CCSPlayer_WeaponServices* pWeaponServices) int totalGrenades = 0; for (int i = 0; i < (sizeof(grenadeAmmoOffsets) / sizeof(int)); i++) - { totalGrenades += pWeaponServices->m_iAmmo[grenadeAmmoOffsets[i]]; - } - + return totalGrenades; } @@ -190,7 +189,7 @@ void ParseWeaponCommand(const CCommand& args, CCSPlayerController* player) CCSPlayer_ItemServices* pItemServices = pPawn->m_pItemServices; CCSPlayer_WeaponServices* pWeaponServices = pPawn->m_pWeaponServices; - // it can sometimes be null when player joined on the very first round? + // it can sometimes be null when player joined on the very first round? if (!pItemServices || !pWeaponServices) return; @@ -218,13 +217,13 @@ void ParseWeaponCommand(const CCommand& args, CCSPlayerController* player) if (iMatchingGrenades >= iGrenadeLimitDefault) { - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX"You cannot carry any more %ss (Max %i)", weaponEntry.szWeaponName, iGrenadeLimitDefault); + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You cannot carry any more %ss (Max %i)", weaponEntry.szWeaponName, iGrenadeLimitDefault); return; } if (iTotalGrenades >= iGrenadeLimitTotal) { - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX"You cannot carry any more grenades (Max %i)", iGrenadeLimitTotal); + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You cannot carry any more grenades (Max %i)", iGrenadeLimitTotal); return; } } @@ -316,7 +315,7 @@ void RegisterWeaponCommands() } } -void ParseChatCommand(const char *pMessage, CCSPlayerController *pController) +void ParseChatCommand(const char* pMessage, CCSPlayerController* pController) { if (!pController || !pController->IsConnected()) return; @@ -333,20 +332,18 @@ void ParseChatCommand(const char *pMessage, CCSPlayerController *pController) uint16 index = g_CommandList.Find(hash_32_fnv1a_const(name.c_str())); if (g_CommandList.IsValidIndex(index)) - { (*g_CommandList[index])(args, pController); - } } -bool CChatCommand::CheckCommandAccess(CCSPlayerController *pPlayer, uint64 flags) +bool CChatCommand::CheckCommandAccess(CCSPlayerController* pPlayer, uint64 flags) { if (!pPlayer) return false; int slot = pPlayer->GetPlayerSlot(); - ZEPlayer *pZEPlayer = g_playerManager->GetPlayer(slot); - + ZEPlayer* pZEPlayer = g_playerManager->GetPlayer(slot); + if (!pZEPlayer) return false; @@ -377,7 +374,7 @@ bool CChatCommand::CheckCommandAccess(CCSPlayerController *pPlayer, uint64 flags return true; } -void ClientPrintAll(int hud_dest, const char *msg, ...) +void ClientPrintAll(int hud_dest, const char* msg, ...) { va_list args; va_start(args, msg); @@ -387,7 +384,7 @@ void ClientPrintAll(int hud_dest, const char *msg, ...) va_end(args); - INetworkMessageInternal *pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("TextMsg"); + INetworkMessageInternal* pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("TextMsg"); auto data = pNetMsg->AllocateMessage()->ToPB(); data->set_dest(hud_dest); @@ -403,7 +400,7 @@ void ClientPrintAll(int hud_dest, const char *msg, ...) ConMsg("%s\n", buf); } -void ClientPrint(CCSPlayerController *player, int hud_dest, const char *msg, ...) +void ClientPrint(CCSPlayerController* player, int hud_dest, const char* msg, ...) { va_list args; va_start(args, msg); @@ -419,7 +416,7 @@ void ClientPrint(CCSPlayerController *player, int hud_dest, const char *msg, ... return; } - INetworkMessageInternal *pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("TextMsg"); + INetworkMessageInternal* pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("TextMsg"); auto data = pNetMsg->AllocateMessage()->ToPB(); data->set_dest(hud_dest); @@ -436,7 +433,6 @@ bool g_bEnableStopSound = false; FAKE_BOOL_CVAR(cs2f_stopsound_enable, "Whether to enable stopsound", g_bEnableStopSound, false, false) - CON_COMMAND_CHAT(stopsound, "- Toggle weapon sounds") { if (!g_bEnableStopSound) @@ -455,7 +451,8 @@ CON_COMMAND_CHAT(stopsound, "- Toggle weapon sounds") g_playerManager->SetPlayerStopSound(iPlayer, bSilencedSet); g_playerManager->SetPlayerSilenceSound(iPlayer, !bSilencedSet && !bStopSet); - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have %s weapon sounds.", bSilencedSet ? "disabled" : !bSilencedSet && !bStopSet ? "silenced" : "enabled"); + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "You have %s weapon sounds.", bSilencedSet ? "disabled" : !bSilencedSet && !bStopSet ? "silenced" : + "enabled"); } CON_COMMAND_CHAT(toggledecals, "- Toggle world decals, if you're into having 10 fps in ZE") @@ -529,7 +526,7 @@ CON_COMMAND_CHAT(hide, " - Hide nearby players") return; } - ZEPlayer *pZEPlayer = player->GetZEPlayer(); + ZEPlayer* pZEPlayer = player->GetZEPlayer(); // Something has to really go wrong for this to happen if (!pZEPlayer) @@ -641,7 +638,7 @@ CON_COMMAND_CHAT(spec, "[name] - Spectate another player or join spectators") // 1 frame delay as observer services will be null on same frame as spectator team switch CHandle hPlayer = player->GetHandle(); CHandle hTarget = pTarget->GetHandle(); - new CTimer(0.0f, false, false, [hPlayer, hTarget](){ + new CTimer(0.0f, false, false, [hPlayer, hTarget]() { CCSPlayerController* pPlayer = hPlayer.Get(); CCSPlayerController* pTargetPlayer = hTarget.Get(); if (!pPlayer || !pTargetPlayer) @@ -691,7 +688,7 @@ CON_COMMAND_CHAT(info, " - Get a player's information") { CCSPlayerController* pTarget = CCSPlayerController::FromSlot(pSlots[i]); ZEPlayer* zpTarget = pTarget->GetZEPlayer(); - + ClientPrint(player, HUD_PRINTCONSOLE, "%s", pTarget->GetPlayerName()); ClientPrint(player, HUD_PRINTCONSOLE, "\tUser ID: %i", g_pEngineServer2->GetPlayerUserId(pTarget->GetPlayerSlot()).Get()); @@ -766,7 +763,7 @@ CON_COMMAND_CHAT(fl, "- Flashlight") if (!player) return; - CCSPlayerPawn *pPawn = (CCSPlayerPawn *)player->GetPawn(); + CCSPlayerPawn* pPawn = (CCSPlayerPawn*)player->GetPawn(); auto ptr = pPawn->m_pMovementServices->m_nButtons().m_pButtonStates(); @@ -777,7 +774,7 @@ CON_COMMAND_CHAT(fl, "- Flashlight") origin.z += 64.0f; origin += forward * 54.0f; // The minimum distance such that an awp wouldn't block the light - CBarnLight *pLight = CreateEntityByName("light_barn"); + CBarnLight* pLight = CreateEntityByName("light_barn"); pLight->m_bEnabled = true; pLight->m_Color->SetColor(255, 255, 255, 255); @@ -793,7 +790,7 @@ CON_COMMAND_CHAT(fl, "- Flashlight") pLight->Teleport(&origin, &pPawn->m_angEyeAngles(), nullptr); // Have to use keyvalues for this since the schema prop is a resource handle - CEntityKeyValues *pKeyValues = new CEntityKeyValues(); + CEntityKeyValues* pKeyValues = new CEntityKeyValues(); pKeyValues->SetString("lightcookie", "materials/effects/lightcookies/flashlight.vtex"); pLight->DispatchSpawn(pKeyValues); @@ -822,7 +819,6 @@ CON_COMMAND_CHAT(test_target, " [blocked flag] [...] - Test string targett uint64 iBlockedFlags = NO_TARGET_BLOCKS; for (int i = 1; i < args.ArgC(); i++) - { if (!V_stricmp(args[i], "NO_RANDOM")) iBlockedFlags |= NO_RANDOM; else if (!V_stricmp(args[i], "NO_MULTIPLE")) @@ -847,7 +843,6 @@ CON_COMMAND_CHAT(test_target, " [blocked flag] [...] - Test string targett iBlockedFlags |= NO_SPECTATOR; else if (!V_stricmp(args[i], "NO_IMMUNITY")) iBlockedFlags |= NO_IMMUNITY; - } int iNumClients = 0; int pSlots[MAXPLAYERS]; @@ -871,7 +866,7 @@ CON_COMMAND_CHAT(particle, "- Spawn a particle") Vector vecAbsOrigin = player->GetPawn()->GetAbsOrigin(); vecAbsOrigin.z += 64.0f; - CParticleSystem *particle = CreateEntityByName("info_particle_system"); + CParticleSystem* particle = CreateEntityByName("info_particle_system"); particle->m_bStartActive(true); particle->m_iszEffectName(args[1]); @@ -891,9 +886,9 @@ CON_COMMAND_CHAT(particle_kv, "- Spawn a particle but using keyvalues to spawn") Vector vecAbsOrigin = player->GetPawn()->GetAbsOrigin(); vecAbsOrigin.z += 64.0f; - CParticleSystem *particle = CreateEntityByName("info_particle_system"); + CParticleSystem* particle = CreateEntityByName("info_particle_system"); - CEntityKeyValues *pKeyValues = new CEntityKeyValues(); + CEntityKeyValues* pKeyValues = new CEntityKeyValues(); pKeyValues->SetString("effect_name", args[1]); pKeyValues->SetBool("start_active", true); @@ -921,7 +916,7 @@ CON_COMMAND_CHAT(emitsound, "- Emit a sound from the entity under crosshair") if (!player) return; - CBaseEntity *pEntity = UTIL_FindPickerEntity(player); + CBaseEntity* pEntity = UTIL_FindPickerEntity(player); if (!pEntity) { @@ -940,14 +935,14 @@ CON_COMMAND_CHAT(getstats, "- Get your stats") if (!player) return; - CSMatchStats_t *stats = &player->m_pActionTrackingServices->m_matchStats(); + CSMatchStats_t* stats = &player->m_pActionTrackingServices->m_matchStats(); - ClientPrint(player, HUD_PRINTCENTER, - "Kills: %i\n" - "Deaths: %i\n" - "Assists: %i\n" - "Damage: %i" - , stats->m_iKills.Get(), stats->m_iDeaths.Get(), stats->m_iAssists.Get(), stats->m_iDamage.Get()); + ClientPrint(player, HUD_PRINTCENTER, + "Kills: %i\n" + "Deaths: %i\n" + "Assists: %i\n" + "Damage: %i", + stats->m_iKills.Get(), stats->m_iDeaths.Get(), stats->m_iAssists.Get(), stats->m_iDamage.Get()); ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Kills: %d", stats->m_iKills.Get()); ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Deaths: %d", stats->m_iDeaths.Get()); diff --git a/src/commands.h b/src/commands.h index d1d80962..1959e750 100644 --- a/src/commands.h +++ b/src/commands.h @@ -18,19 +18,19 @@ */ #pragma once -#include "entity/ccsplayercontroller.h" -#include "convar.h" #include "adminsystem.h" +#include "convar.h" +#include "entity/ccsplayercontroller.h" #include "leader.h" #include -#define CMDFLAG_NONE (0) -#define CMDFLAG_NOHELP (1 << 0) // Don't show in !help menu +#define CMDFLAG_NONE (0) +#define CMDFLAG_NOHELP (1 << 0) // Don't show in !help menu #define COMMAND_PREFIX "c_" -#define CHAT_PREFIX " \7[CS2Fixes]\1 " +#define CHAT_PREFIX " \7[CS2Fixes]\1 " -typedef void (*FnChatCommandCallback_t)(const CCommand &args, CCSPlayerController *player); +typedef void (*FnChatCommandCallback_t)(const CCommand& args, CCSPlayerController* player); class CChatCommand; @@ -44,21 +44,20 @@ extern bool g_bEnableStopSound; extern bool g_bEnableNoShake; extern float g_flMaxShakeAmp; - -void ClientPrintAll(int destination, const char *msg, ...); -void ClientPrint(CCSPlayerController *player, int destination, const char *msg, ...); +void ClientPrintAll(int destination, const char* msg, ...); +void ClientPrint(CCSPlayerController* player, int destination, const char* msg, ...); // Just a wrapper class so we're able to insert the callback class CChatCommand { public: - CChatCommand(const char *cmd, FnChatCommandCallback_t callback, const char *description, uint64 adminFlags = ADMFLAG_NONE, uint64 cmdFlags = CMDFLAG_NONE) : + CChatCommand(const char* cmd, FnChatCommandCallback_t callback, const char* description, uint64 adminFlags = ADMFLAG_NONE, uint64 cmdFlags = CMDFLAG_NONE) : m_pfnCallback(callback), m_sName(cmd), m_sDescription(description), m_nAdminFlags(adminFlags), m_nCmdFlags(cmdFlags) { g_CommandList.Insert(hash_32_fnv1a_const(cmd), this); } - void operator()(const CCommand &args, CCSPlayerController *player) + void operator()(const CCommand& args, CCSPlayerController* player) { // Server disabled ALL chat commands if (!g_bEnableCommands) @@ -79,7 +78,7 @@ class CChatCommand m_pfnCallback(args, player); } - static bool CheckCommandAccess(CCSPlayerController *pPlayer, uint64 flags); + static bool CheckCommandAccess(CCSPlayerController* pPlayer, uint64 flags); const char* GetName() { return m_sName.c_str(); } const char* GetDescription() { return m_sDescription.c_str(); } @@ -109,23 +108,23 @@ struct WeaponMapEntry_t }; void RegisterWeaponCommands(); -void ParseChatCommand(const char *, CCSPlayerController *); - -#define CON_COMMAND_CHAT_FLAGS(name, description, flags) \ - void name##_callback(const CCommand &args, CCSPlayerController *player); \ - static CChatCommand name##_chat_command(#name, name##_callback, description, flags); \ - static void name##_con_callback(const CCommandContext &context, const CCommand &args) \ - { \ - CCSPlayerController *pController = nullptr; \ - if (context.GetPlayerSlot().Get() != -1) \ - pController = (CCSPlayerController *)g_pEntitySystem->GetEntityInstance((CEntityIndex)(context.GetPlayerSlot().Get() + 1)); \ - \ - name##_chat_command(args, pController); \ - } \ - static ConCommandRefAbstract name##_ref; \ - static ConCommand name##_command(&name##_ref, COMMAND_PREFIX #name, name##_con_callback, \ - description, FCVAR_CLIENT_CAN_EXECUTE | FCVAR_LINKED_CONCOMMAND); \ - void name##_callback(const CCommand &args, CCSPlayerController *player) +void ParseChatCommand(const char*, CCSPlayerController*); + +#define CON_COMMAND_CHAT_FLAGS(name, description, flags) \ + void name##_callback(const CCommand& args, CCSPlayerController* player); \ + static CChatCommand name##_chat_command(#name, name##_callback, description, flags); \ + static void name##_con_callback(const CCommandContext& context, const CCommand& args) \ + { \ + CCSPlayerController* pController = nullptr; \ + if (context.GetPlayerSlot().Get() != -1) \ + pController = (CCSPlayerController*)g_pEntitySystem->GetEntityInstance((CEntityIndex)(context.GetPlayerSlot().Get() + 1)); \ + \ + name##_chat_command(args, pController); \ + } \ + static ConCommandRefAbstract name##_ref; \ + static ConCommand name##_command(&name##_ref, COMMAND_PREFIX #name, name##_con_callback, \ + description, FCVAR_CLIENT_CAN_EXECUTE | FCVAR_LINKED_CONCOMMAND); \ + void name##_callback(const CCommand& args, CCSPlayerController* player) #define CON_COMMAND_CHAT(name, description) CON_COMMAND_CHAT_FLAGS(name, description, ADMFLAG_NONE) #define CON_COMMAND_CHAT_LEADER(name, description) CON_COMMAND_CHAT_FLAGS(name, description, FLAG_LEADER) diff --git a/src/common.h b/src/common.h index b0206184..9f488713 100644 --- a/src/common.h +++ b/src/common.h @@ -23,69 +23,69 @@ #define VPROF_LEVEL 1 -#define CS_TEAM_NONE 0 -#define CS_TEAM_SPECTATOR 1 -#define CS_TEAM_T 2 -#define CS_TEAM_CT 3 +#define CS_TEAM_NONE 0 +#define CS_TEAM_SPECTATOR 1 +#define CS_TEAM_T 2 +#define CS_TEAM_CT 3 -#define HUD_PRINTNOTIFY 1 -#define HUD_PRINTCONSOLE 2 -#define HUD_PRINTTALK 3 -#define HUD_PRINTCENTER 4 +#define HUD_PRINTNOTIFY 1 +#define HUD_PRINTCONSOLE 2 +#define HUD_PRINTTALK 3 +#define HUD_PRINTCENTER 4 #define MAXPLAYERS 64 #ifdef _WIN32 -#define ROOTBIN "/bin/win64/" -#define GAMEBIN "/csgo/bin/win64/" + #define ROOTBIN "/bin/win64/" + #define GAMEBIN "/csgo/bin/win64/" #else -#define ROOTBIN "/bin/linuxsteamrt64/" -#define GAMEBIN "/csgo/bin/linuxsteamrt64/" + #define ROOTBIN "/bin/linuxsteamrt64/" + #define GAMEBIN "/csgo/bin/linuxsteamrt64/" #endif void UnlockConVars(); void UnlockConCommands(); -void Message(const char *, ...); -void Panic(const char *, ...); +void Message(const char*, ...); +void Panic(const char*, ...); // CONVAR_TODO // Need to replace with actual cvars once available in SDK -#define FAKE_CVAR(name, description, variable_name, variable_type, variable_type_format, variable_default, protect) \ - CON_COMMAND_F(name, description, FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | (protect ? FCVAR_PROTECTED : FCVAR_NONE)) \ - { \ - if (args.ArgC() < 2) \ - Msg("%s " #variable_type_format "\n", args[0], variable_name); \ - else \ - variable_name = V_StringTo##variable_type(args[1], variable_default); \ +#define FAKE_CVAR(name, description, variable_name, variable_type, variable_type_format, variable_default, protect) \ + CON_COMMAND_F(name, description, FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | (protect ? FCVAR_PROTECTED : FCVAR_NONE)) \ + { \ + if (args.ArgC() < 2) \ + Msg("%s " #variable_type_format "\n", args[0], variable_name); \ + else \ + variable_name = V_StringTo##variable_type(args[1], variable_default); \ } -#define FAKE_INT_CVAR(name, description, variable_name, variable_default, protect) \ - FAKE_CVAR(name, description, variable_name, Int32, %i, variable_default, protect) +#define FAKE_INT_CVAR(name, description, variable_name, variable_default, protect) \ + FAKE_CVAR(name, description, variable_name, Int32, % i, variable_default, protect) -#define FAKE_BOOL_CVAR(name, description, variable_name, variable_default, protect) \ - FAKE_CVAR(name, description, variable_name, Bool, %i, variable_default, protect) +#define FAKE_BOOL_CVAR(name, description, variable_name, variable_default, protect) \ + FAKE_CVAR(name, description, variable_name, Bool, % i, variable_default, protect) -#define FAKE_FLOAT_CVAR(name, description, variable_name, variable_default, protect) \ - FAKE_CVAR(name, description, variable_name, Float32, %f, variable_default, protect) +#define FAKE_FLOAT_CVAR(name, description, variable_name, variable_default, protect) \ + FAKE_CVAR(name, description, variable_name, Float32, % f, variable_default, protect) // assumes std::string variable -#define FAKE_STRING_CVAR(name, description, variable_name, protect) \ - CON_COMMAND_F(name, description, FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | (protect ? FCVAR_PROTECTED : FCVAR_NONE)) \ - { \ - if (args.ArgC() < 2) \ - Msg("%s %s\n", args[0], variable_name.c_str()); \ - else \ - variable_name = args[1]; \ +#define FAKE_STRING_CVAR(name, description, variable_name, protect) \ + CON_COMMAND_F(name, description, FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | (protect ? FCVAR_PROTECTED : FCVAR_NONE)) \ + { \ + if (args.ArgC() < 2) \ + Msg("%s %s\n", args[0], variable_name.c_str()); \ + else \ + variable_name = args[1]; \ } -#define FAKE_COLOR_CVAR(name, description, variable_name, protect) \ - CON_COMMAND_F(name, description, FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | (protect ? FCVAR_PROTECTED : FCVAR_NONE)) \ - { \ - if (args.ArgC() < 2) \ - Msg("%s %i %i %i\n", args[0], variable_name[0], variable_name[1], variable_name[2]); \ - else if (args.ArgC() == 2) \ - V_StringToColor(args[1], variable_name); \ - else \ - V_StringToColor(args.ArgS(), variable_name); \ +#define FAKE_COLOR_CVAR(name, description, variable_name, protect) \ + CON_COMMAND_F(name, description, FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | (protect ? FCVAR_PROTECTED : FCVAR_NONE)) \ + { \ + if (args.ArgC() < 2) \ + Msg("%s %i %i %i\n", args[0], variable_name[0], variable_name[1], variable_name[2]); \ + else if (args.ArgC() == 2) \ + V_StringToColor(args[1], variable_name); \ + else \ + V_StringToColor(args.ArgS(), variable_name); \ } \ No newline at end of file diff --git a/src/cs2_sdk/entity/cbaseentity.h b/src/cs2_sdk/entity/cbaseentity.h index 0bb40b39..8faf928d 100644 --- a/src/cs2_sdk/entity/cbaseentity.h +++ b/src/cs2_sdk/entity/cbaseentity.h @@ -19,18 +19,18 @@ #pragma once -#include "schema.h" +#include "../../gameconfig.h" +#include "../detours.h" #include "ccollisionproperty.h" -#include "globaltypes.h" #include "ctakedamageinfo.h" -#include "mathlib/vector.h" #include "ehandle.h" -#include "../detours.h" #include "entitykeyvalues.h" -#include "../../gameconfig.h" +#include "globaltypes.h" +#include "mathlib/vector.h" +#include "schema.h" #include "tier1/utlstringtoken.h" -extern CGameConfig *g_GameConfig; +extern CGameConfig* g_GameConfig; class CGameUI; class CEnvHudHint; @@ -41,9 +41,9 @@ class CGameSceneNode public: DECLARE_SCHEMA_CLASS(CGameSceneNode) - SCHEMA_FIELD(CEntityInstance *, m_pOwner) - SCHEMA_FIELD(CGameSceneNode *, m_pParent) - SCHEMA_FIELD(CGameSceneNode *, m_pChild) + SCHEMA_FIELD(CEntityInstance*, m_pOwner) + SCHEMA_FIELD(CGameSceneNode*, m_pParent) + SCHEMA_FIELD(CGameSceneNode*, m_pChild) SCHEMA_FIELD(CNetworkOriginCellCoordQuantizedVector, m_vecOrigin) SCHEMA_FIELD(QAngle, m_angRotation) SCHEMA_FIELD(float, m_flScale) @@ -57,7 +57,7 @@ class CGameSceneNode matrix3x4_t mat; // issues with this and im tired so hardcoded it - //AngleMatrix(this->m_angAbsRotation(), this->m_vecAbsOrigin(), mat); + // AngleMatrix(this->m_angAbsRotation(), this->m_vecAbsOrigin(), mat); QAngle angles = this->m_angAbsRotation(); float sr, sp, sy, cr, cp, cy; @@ -94,7 +94,7 @@ class CBodyComponent public: DECLARE_SCHEMA_CLASS(CBodyComponent) - SCHEMA_FIELD(CGameSceneNode *, m_pSceneNode) + SCHEMA_FIELD(CGameSceneNode*, m_pSceneNode) }; class CModelState @@ -124,7 +124,7 @@ class CBaseEntity : public CEntityInstance public: DECLARE_SCHEMA_CLASS(CBaseEntity) - SCHEMA_FIELD(CBodyComponent *, m_CBodyComponent) + SCHEMA_FIELD(CBodyComponent*, m_CBodyComponent) SCHEMA_FIELD(CBitVec<64>, m_isSteadyState) SCHEMA_FIELD(float, m_lastNetworkChange) SCHEMA_FIELD_POINTER(CNetworkTransmitComponent, m_NetworkTransmitComponent) @@ -164,17 +164,17 @@ class CBaseEntity : public CEntityInstance void SetAbsVelocity(Vector vecVelocity) { m_vecAbsVelocity = vecVelocity; } void SetBaseVelocity(Vector vecVelocity) { m_vecBaseVelocity = vecVelocity; } - void SetName(const char *pName) + void SetName(const char* pName) { addresses::CEntityIdentity_SetEntityName(m_pEntity, pName); } - void TakeDamage(CTakeDamageInfo &info) + void TakeDamage(CTakeDamageInfo& info) { Detour_CBaseEntity_TakeDamageOld(this, &info); } - void Teleport(const Vector *position, const QAngle *angles, const Vector *velocity) + void Teleport(const Vector* position, const QAngle* angles, const Vector* velocity) { static int offset = g_GameConfig->GetOffset("Teleport"); CALL_VIRTUAL(void, offset, this, position, angles, velocity); @@ -207,7 +207,7 @@ class CBaseEntity : public CEntityInstance return CALL_VIRTUAL(bool, offset, this); } - void AcceptInput(const char *pInputName, variant_t value = variant_t(""), CEntityInstance *pActivator = nullptr, CEntityInstance *pCaller = nullptr) + void AcceptInput(const char* pInputName, variant_t value = variant_t(""), CEntityInstance* pActivator = nullptr, CEntityInstance* pCaller = nullptr) { addresses::CEntityInstance_AcceptInput(this, pInputName, pActivator, pCaller, &value, 0); } @@ -219,18 +219,18 @@ class CBaseEntity : public CEntityInstance // A double pointer to entity VData is available 4 bytes past m_nSubclassID, if applicable CEntitySubclassVDataBase* GetVData() { return *(CEntitySubclassVDataBase**)((uint8*)(m_nSubclassID()) + 4); } - void DispatchSpawn(CEntityKeyValues *pEntityKeyValues = nullptr) + void DispatchSpawn(CEntityKeyValues* pEntityKeyValues = nullptr) { addresses::DispatchSpawn(this, pEntityKeyValues); } // Emit a sound event - void EmitSound(const char *pszSound, int nPitch = 100, float flVolume = 1.0, float flDelay = 0.0) + void EmitSound(const char* pszSound, int nPitch = 100, float flVolume = 1.0, float flDelay = 0.0) { addresses::CBaseEntity_EmitSoundParams(this, pszSound, nPitch, flVolume, flDelay); } - SndOpEventGuid_t EmitSoundFilter(IRecipientFilter &filter, const char *pszSound, float flVolume = 1.0, float flPitch = 1.0) + SndOpEventGuid_t EmitSoundFilter(IRecipientFilter& filter, const char* pszSound, float flVolume = 1.0, float flPitch = 1.0) { EmitSound_t params; params.m_pSoundName = pszSound; @@ -240,14 +240,14 @@ class CBaseEntity : public CEntityInstance return addresses::CBaseEntity_EmitSoundFilter(filter, entindex(), params); } - void DispatchParticle(const char *pszParticleName, IRecipientFilter *pFilter, ParticleAttachment_t nAttachType = PATTACH_POINT_FOLLOW, - char iAttachmentPoint = 0, CUtlSymbolLarge iAttachmentName = "") + void DispatchParticle(const char* pszParticleName, IRecipientFilter* pFilter, ParticleAttachment_t nAttachType = PATTACH_POINT_FOLLOW, + char iAttachmentPoint = 0, CUtlSymbolLarge iAttachmentName = "") { addresses::DispatchParticleEffect(pszParticleName, nAttachType, this, iAttachmentPoint, iAttachmentName, false, 0, pFilter, 0); } // This was needed so we can parent to nameless entities using pointers - void SetParent(CBaseEntity *pNewParent) + void SetParent(CBaseEntity* pNewParent) { addresses::CBaseEntity_SetParent(this, pNewParent, MakeStringToken(""), nullptr); } @@ -262,7 +262,7 @@ class CBaseEntity : public CEntityInstance addresses::CBaseEntity_SetMoveType(this, nMoveType, m_MoveCollide); } - void SetGroundEntity(CBaseEntity *pGround) + void SetGroundEntity(CBaseEntity* pGround) { addresses::SetGroundEntity(this, pGround, nullptr); } @@ -271,7 +271,7 @@ class CBaseEntity : public CEntityInstance /* Begin Custom Entities Cast */ - [[nodiscard]] CGameUI *AsGameUI() + [[nodiscard]] CGameUI* AsGameUI() { if (V_strcasecmp(GetClassname(), "logic_case") != 0) return nullptr; @@ -279,20 +279,20 @@ class CBaseEntity : public CEntityInstance const auto tag = m_iszPrivateVScripts.IsValid() ? m_iszPrivateVScripts.String() : nullptr; if (tag && V_strcasecmp(tag, "game_ui") == 0) - return reinterpret_cast(this); + return reinterpret_cast(this); return nullptr; } - [[nodiscard]] CEnvHudHint *AsHudHint() + [[nodiscard]] CEnvHudHint* AsHudHint() { if (V_strcasecmp(GetClassname(), "env_hudhint") == 0) - return reinterpret_cast(this); + return reinterpret_cast(this); return nullptr; } - [[nodiscard]] CPointViewControl *AsPointViewControl() + [[nodiscard]] CPointViewControl* AsPointViewControl() { if (V_strcasecmp(GetClassname(), "logic_relay") != 0) return nullptr; @@ -300,7 +300,7 @@ class CBaseEntity : public CEntityInstance const auto tag = m_iszPrivateVScripts.IsValid() ? m_iszPrivateVScripts.String() : nullptr; if (tag && V_strcasecmp(tag, "point_viewcontrol") == 0) - return reinterpret_cast(this); + return reinterpret_cast(this); return nullptr; } diff --git a/src/cs2_sdk/entity/cbasemodelentity.h b/src/cs2_sdk/entity/cbasemodelentity.h index 74ab7635..1c291e9f 100644 --- a/src/cs2_sdk/entity/cbasemodelentity.h +++ b/src/cs2_sdk/entity/cbasemodelentity.h @@ -34,7 +34,7 @@ class CBaseModelEntity : public CBaseEntity SCHEMA_FIELD(float, m_flDissolveStartTime) SCHEMA_FIELD(Vector, m_vecViewOffset) - void SetModel(const char *szModel) + void SetModel(const char* szModel) { addresses::CBaseModelEntity_SetModel(this, szModel); } @@ -44,7 +44,7 @@ class CBaseModelEntity : public CBaseEntity m_Collision().m_CollisionGroup = static_cast(nCollisionGroup); CollisionRulesChanged(); } - + const char* GetModelName() { return ((CSkeletonInstance*)m_CBodyComponent->m_pSceneNode.Get())->m_modelState().m_ModelName.Get().String(); diff --git a/src/cs2_sdk/entity/cbaseplayercontroller.h b/src/cs2_sdk/entity/cbaseplayercontroller.h index f8610cfa..d89afdda 100644 --- a/src/cs2_sdk/entity/cbaseplayercontroller.h +++ b/src/cs2_sdk/entity/cbaseplayercontroller.h @@ -19,9 +19,9 @@ #pragma once -#include "ehandle.h" #include "cbaseentity.h" #include "ccsplayerpawn.h" +#include "ehandle.h" enum class PlayerConnectedState : uint32_t { @@ -50,8 +50,8 @@ class CBasePlayerController : public CBaseEntity // - The player's actual pawn // - An observer pawn if spectating // - A bot pawn if controlling one - CBasePlayerPawn *GetPawn() { return m_hPawn.Get(); } - const char *GetPlayerName() { return m_iszPlayerName(); } + CBasePlayerPawn* GetPawn() { return m_hPawn.Get(); } + const char* GetPlayerName() { return m_iszPlayerName(); } int GetPlayerSlot() { return entindex() - 1; } bool IsConnected() { return m_iConnected() == PlayerConnectedState::PlayerConnected; } void SetPawn(CCSPlayerPawn* pawn) diff --git a/src/cs2_sdk/entity/cbaseplayerpawn.h b/src/cs2_sdk/entity/cbaseplayerpawn.h index 5341beed..34a50896 100644 --- a/src/cs2_sdk/entity/cbaseplayerpawn.h +++ b/src/cs2_sdk/entity/cbaseplayerpawn.h @@ -70,5 +70,5 @@ class CBasePlayerPawn : public CBaseModelEntity CALL_VIRTUAL(void, offset, this, bExplode, bForce); } - CBasePlayerController *GetController() { return m_hController.Get(); } + CBasePlayerController* GetController() { return m_hController.Get(); } }; \ No newline at end of file diff --git a/src/cs2_sdk/entity/cbasetrigger.h b/src/cs2_sdk/entity/cbasetrigger.h index de942bff..d9528596 100644 --- a/src/cs2_sdk/entity/cbasetrigger.h +++ b/src/cs2_sdk/entity/cbasetrigger.h @@ -19,8 +19,8 @@ #pragma once +#include "../schema.h" #include "cbasemodelentity.h" -#include"../schema.h" #define SF_TRIG_PUSH_ONCE 0x80 @@ -34,7 +34,7 @@ class CBaseTrigger : public CBaseModelEntity SCHEMA_FIELD_POINTER(CUtlVector>, m_hTouchingEntities) SCHEMA_FIELD(bool, m_bClientSidePredicted) - bool PassesTriggerFilters(CBaseEntity *pOther) + bool PassesTriggerFilters(CBaseEntity* pOther) { static int offset = g_GameConfig->GetOffset("PassesTriggerFilters"); return CALL_VIRTUAL(bool, offset, this, pOther); diff --git a/src/cs2_sdk/entity/ccollisionproperty.h b/src/cs2_sdk/entity/ccollisionproperty.h index a21f5d6c..9e418f1a 100644 --- a/src/cs2_sdk/entity/ccollisionproperty.h +++ b/src/cs2_sdk/entity/ccollisionproperty.h @@ -19,7 +19,7 @@ #pragma once -#include "cbaseentity.h" +#include "schema.h" struct VPhysicsCollisionAttribute_t { diff --git a/src/cs2_sdk/entity/ccsplayercontroller.h b/src/cs2_sdk/entity/ccsplayercontroller.h index 93a0f57b..ee01df9d 100644 --- a/src/cs2_sdk/entity/ccsplayercontroller.h +++ b/src/cs2_sdk/entity/ccsplayercontroller.h @@ -19,12 +19,12 @@ #pragma once -#include "cbaseplayercontroller.h" -#include "services.h" #include "../playermanager.h" #include "../serversideclient.h" +#include "cbaseplayercontroller.h" +#include "services.h" -extern CServerSideClient *GetClientBySlot(CPlayerSlot slot); +extern CServerSideClient* GetClientBySlot(CPlayerSlot slot); extern CGameEntitySystem* g_pEntitySystem; @@ -63,7 +63,7 @@ class CCSPlayerController : public CBasePlayerController } // Returns the actual player pawn - CCSPlayerPawn *GetPlayerPawn() + CCSPlayerPawn* GetPlayerPawn() { return m_hPlayerPawn().Get(); } @@ -73,7 +73,7 @@ class CCSPlayerController : public CBasePlayerController return g_playerManager->GetPlayer(GetPlayerSlot()); } - CServerSideClient *GetServerSideClient() + CServerSideClient* GetServerSideClient() { return GetClientBySlot(GetPlayerSlot()); } @@ -95,18 +95,14 @@ class CCSPlayerController : public CBasePlayerController return; if (iTeam == CS_TEAM_SPECTATOR) - { ChangeTeam(iTeam); - } else - { addresses::CCSPlayerController_SwitchTeam(this, iTeam); - } } void Respawn() { - CCSPlayerPawn *pPawn = GetPlayerPawn(); + CCSPlayerPawn* pPawn = GetPlayerPawn(); if (!pPawn || pPawn->IsAlive()) return; @@ -118,7 +114,7 @@ class CCSPlayerController : public CBasePlayerController CSPlayerState GetPawnState() { // All CS2 pawns are derived from this - CCSPlayerPawnBase *pPawn = (CCSPlayerPawnBase*)GetPawn(); + CCSPlayerPawnBase* pPawn = (CCSPlayerPawnBase*)GetPawn(); // The player is still joining so their pawn doesn't exist yet, and STATE_WELCOME is what they start with if (!pPawn) @@ -129,7 +125,7 @@ class CCSPlayerController : public CBasePlayerController CSPlayerState GetPlayerPawnState() { - CCSPlayerPawn *pPawn = GetPlayerPawn(); + CCSPlayerPawn* pPawn = GetPlayerPawn(); // The player is still joining so their pawn doesn't exist yet, and STATE_WELCOME is what they start with if (!pPawn) @@ -138,7 +134,7 @@ class CCSPlayerController : public CBasePlayerController return pPawn->m_iPlayerState(); } - CBaseEntity *GetObserverTarget() + CBaseEntity* GetObserverTarget() { auto pPawn = GetPawn(); diff --git a/src/cs2_sdk/entity/ccsplayerpawn.h b/src/cs2_sdk/entity/ccsplayerpawn.h index 6b6b6a0f..88ab8b54 100644 --- a/src/cs2_sdk/entity/ccsplayerpawn.h +++ b/src/cs2_sdk/entity/ccsplayerpawn.h @@ -35,7 +35,6 @@ enum CSPlayerState NUM_PLAYER_STATES = 0x9, }; - class CCSPlayerPawnBase : public CBasePlayerPawn { public: @@ -44,7 +43,7 @@ class CCSPlayerPawnBase : public CBasePlayerPawn SCHEMA_FIELD(CSPlayerState, m_iPlayerState) SCHEMA_FIELD(CHandle, m_hOriginalController) - CCSPlayerController *GetOriginalController() + CCSPlayerController* GetOriginalController() { return m_hOriginalController().Get(); } diff --git a/src/cs2_sdk/entity/cenventitymaker.h b/src/cs2_sdk/entity/cenventitymaker.h index 9858ee74..5c96b4f8 100644 --- a/src/cs2_sdk/entity/cenventitymaker.h +++ b/src/cs2_sdk/entity/cenventitymaker.h @@ -19,8 +19,8 @@ #pragma once +#include "../schema.h" #include "cbaseentity.h" -#include"../schema.h" #define SF_TRIG_PUSH_ONCE 0x80 diff --git a/src/cs2_sdk/entity/cenvhudhint.h b/src/cs2_sdk/entity/cenvhudhint.h index 1993bc0c..0a4f5df7 100644 --- a/src/cs2_sdk/entity/cenvhudhint.h +++ b/src/cs2_sdk/entity/cenvhudhint.h @@ -25,7 +25,7 @@ class CEnvHudHint : public CBaseEntity { public: - DECLARE_SCHEMA_CLASS(CEnvHudHint) + DECLARE_SCHEMA_CLASS(CEnvHudHint) - SCHEMA_FIELD(CUtlSymbolLarge, m_iszMessage) + SCHEMA_FIELD(CUtlSymbolLarge, m_iszMessage) }; diff --git a/src/cs2_sdk/entity/cgameplayerequip.h b/src/cs2_sdk/entity/cgameplayerequip.h index f97ec385..7097a644 100644 --- a/src/cs2_sdk/entity/cgameplayerequip.h +++ b/src/cs2_sdk/entity/cgameplayerequip.h @@ -26,13 +26,12 @@ class CGamePlayerEquip : public CBaseEntity { DECLARE_SCHEMA_CLASS(CGamePlayerEquip) public: + static constexpr int MAX_EQUIPMENTS_SIZE = 32; - static constexpr int MAX_EQUIPMENTS_SIZE = 32; + static constexpr int SF_PLAYEREQUIP_USEONLY = 0x0001; + static constexpr int SF_PLAYEREQUIP_STRIPFIRST = 0x0002; - static constexpr int SF_PLAYEREQUIP_USEONLY = 0x0001; - static constexpr int SF_PLAYEREQUIP_STRIPFIRST = 0x0002; - - // TODO this flag copied from CSGO, and impl on FyS server. but CS2Fixes not support aws currently. - // Add it in the future. - static constexpr int SF_PLAYEREQUIP_ONLYSTRIPSAME = 0x0004; + // TODO this flag copied from CSGO, and impl on FyS server. but CS2Fixes not support aws currently. + // Add it in the future. + static constexpr int SF_PLAYEREQUIP_ONLYSTRIPSAME = 0x0004; }; \ No newline at end of file diff --git a/src/cs2_sdk/entity/cgamerules.h b/src/cs2_sdk/entity/cgamerules.h index 61c25a63..edb40f8e 100644 --- a/src/cs2_sdk/entity/cgamerules.h +++ b/src/cs2_sdk/entity/cgamerules.h @@ -18,9 +18,9 @@ */ #pragma once -#include -#include "globaltypes.h" #include "cbaseentity.h" +#include "globaltypes.h" +#include enum CSRoundEndReason { @@ -40,10 +40,10 @@ enum CSRoundEndReason TerroristsNotEscaped, /**< Terrorists have not escaped! */ VIPNotEscaped, /**< VIP has not escaped! - Doesn't exist on CS:GO */ GameStart, /**< Game Commencing! */ - TerroristsSurrender, /**< Terrorists Surrender */ - CTSurrender, /**< CTs Surrender */ - TerroristsPlanted, /**< Terrorists Planted the bomb */ - CTsReachedHostage, /**< CTs Reached the hostage */ + TerroristsSurrender, /**< Terrorists Surrender */ + CTSurrender, /**< CTs Surrender */ + TerroristsPlanted, /**< Terrorists Planted the bomb */ + CTsReachedHostage, /**< CTs Reached the hostage */ SurvivalWin, SurvivalDraw }; @@ -82,5 +82,5 @@ class CCSGameRulesProxy : public CBaseEntity public: DECLARE_SCHEMA_CLASS(CCSGameRulesProxy) - SCHEMA_FIELD(CCSGameRules *, m_pGameRules) + SCHEMA_FIELD(CCSGameRules*, m_pGameRules) }; \ No newline at end of file diff --git a/src/cs2_sdk/entity/clogiccase.h b/src/cs2_sdk/entity/clogiccase.h index 80b60736..c7c20e9d 100644 --- a/src/cs2_sdk/entity/clogiccase.h +++ b/src/cs2_sdk/entity/clogiccase.h @@ -25,18 +25,18 @@ class CLogicCase : public CBaseEntity { public: - DECLARE_SCHEMA_CLASS(CLogicCase) + DECLARE_SCHEMA_CLASS(CLogicCase) }; class CGameUI : public CLogicCase { public: - static constexpr int SF_GAMEUI_FREEZE_PLAYER = 32; - static constexpr int SF_GAMEUI_JUMP_DEACTIVATE = 256; + static constexpr int SF_GAMEUI_FREEZE_PLAYER = 32; + static constexpr int SF_GAMEUI_JUMP_DEACTIVATE = 256; - // TODO Hide Weapon requires more RE - static constexpr int SF_GAMEUI_HIDE_WEAPON = 64; + // TODO Hide Weapon requires more RE + static constexpr int SF_GAMEUI_HIDE_WEAPON = 64; - // TODO subtick problem - static constexpr int SF_GAMEUI_USE_DEACTIVATE = 128; + // TODO subtick problem + static constexpr int SF_GAMEUI_USE_DEACTIVATE = 128; }; \ No newline at end of file diff --git a/src/cs2_sdk/entity/cpointviewcontrol.h b/src/cs2_sdk/entity/cpointviewcontrol.h index 069d45a8..a5b4b15b 100644 --- a/src/cs2_sdk/entity/cpointviewcontrol.h +++ b/src/cs2_sdk/entity/cpointviewcontrol.h @@ -27,43 +27,43 @@ class CPointViewControl : public CBaseEntity { - DECLARE_SCHEMA_CLASS(CPointViewControl) + DECLARE_SCHEMA_CLASS(CPointViewControl) - // hello, don't port my garbage code to cssharp :) + // hello, don't port my garbage code to cssharp :) - static constexpr int SF_POINT_VIEWCONTROL_FROZEN = 1 << 5; - static constexpr int SF_POINT_VIEWCONTROL_FOV = 1 << 6; - static constexpr int SF_POINT_VIEWCONTROL_DISARM = 1 << 7; + static constexpr int SF_POINT_VIEWCONTROL_FROZEN = 1 << 5; + static constexpr int SF_POINT_VIEWCONTROL_FOV = 1 << 6; + static constexpr int SF_POINT_VIEWCONTROL_DISARM = 1 << 7; public: - [[nodiscard]] CBaseEntity* GetTargetCameraEntity() - { - const auto pTarget = UTIL_FindEntityByName(nullptr, m_target().String()); - return pTarget && pTarget->m_pCollision() ? pTarget : nullptr; - } + [[nodiscard]] CBaseEntity* GetTargetCameraEntity() + { + const auto pTarget = UTIL_FindEntityByName(nullptr, m_target().String()); + return pTarget && pTarget->m_pCollision() ? pTarget : nullptr; + } - [[nodiscard]] bool HasTargetCameraEntity() - { - return m_target().IsValid() && strlen(m_target().String()) >= 2; - } + [[nodiscard]] bool HasTargetCameraEntity() + { + return m_target().IsValid() && strlen(m_target().String()) >= 2; + } - [[nodiscard]] bool HasFrozen() - { - return !!(m_spawnflags() & SF_POINT_VIEWCONTROL_FROZEN); - } + [[nodiscard]] bool HasFrozen() + { + return !!(m_spawnflags() & SF_POINT_VIEWCONTROL_FROZEN); + } - [[nodiscard]] bool HasFOV() - { - return !!(m_spawnflags() & SF_POINT_VIEWCONTROL_FOV); - } + [[nodiscard]] bool HasFOV() + { + return !!(m_spawnflags() & SF_POINT_VIEWCONTROL_FOV); + } - [[nodiscard]] bool HasDisarm() - { - return !!(m_spawnflags() & SF_POINT_VIEWCONTROL_DISARM); - } + [[nodiscard]] bool HasDisarm() + { + return !!(m_spawnflags() & SF_POINT_VIEWCONTROL_DISARM); + } - [[nodiscard]] uint GetFOV() - { - return clamp(static_cast(m_iHealth()), 16, 179); - } + [[nodiscard]] uint GetFOV() + { + return clamp(static_cast(m_iHealth()), 16, 179); + } }; diff --git a/src/cs2_sdk/entity/ctakedamageinfo.h b/src/cs2_sdk/entity/ctakedamageinfo.h index db348ef0..af1bf53f 100644 --- a/src/cs2_sdk/entity/ctakedamageinfo.h +++ b/src/cs2_sdk/entity/ctakedamageinfo.h @@ -18,8 +18,8 @@ */ #pragma once -#include #include "ehandle.h" +#include enum DamageTypes_t : uint32_t { @@ -81,7 +81,7 @@ struct AttackerInfo_t // No idea what this is meant to have, but OnTakeDamage_Alive expects this and we only care about pInfo struct CTakeDamageInfoContainer { - CTakeDamageInfo *pInfo; + CTakeDamageInfo* pInfo; }; class CTakeDamageInfo @@ -95,7 +95,7 @@ class CTakeDamageInfo addresses::CTakeDamageInfo_Constructor(this, nullptr, nullptr, nullptr, &vec3_origin, &vec3_origin, 0.f, 0, 0, nullptr); } - CTakeDamageInfo(CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pAbility, float flDamage, DamageTypes_t bitsDamageType) + CTakeDamageInfo(CBaseEntity* pInflictor, CBaseEntity* pAttacker, CBaseEntity* pAbility, float flDamage, DamageTypes_t bitsDamageType) { addresses::CTakeDamageInfo_Constructor(this, pInflictor, pAttacker, pAbility, &vec3_origin, &vec3_origin, flDamage, bitsDamageType, 0, nullptr); } diff --git a/src/cs2_sdk/entity/cteam.h b/src/cs2_sdk/entity/cteam.h index 8b7f955a..49e243f5 100644 --- a/src/cs2_sdk/entity/cteam.h +++ b/src/cs2_sdk/entity/cteam.h @@ -17,7 +17,6 @@ * this program. If not, see . */ - #pragma once #include "cbaseentity.h" #include "cbaseplayercontroller.h" diff --git a/src/cs2_sdk/entity/ctriggerpush.h b/src/cs2_sdk/entity/ctriggerpush.h index 73169bfd..e8a909c7 100644 --- a/src/cs2_sdk/entity/ctriggerpush.h +++ b/src/cs2_sdk/entity/ctriggerpush.h @@ -19,8 +19,8 @@ #pragma once +#include "../schema.h" #include "cbasetrigger.h" -#include"../schema.h" #define SF_TRIG_PUSH_ONCE 0x80 diff --git a/src/cs2_sdk/entity/cvotecontroller.h b/src/cs2_sdk/entity/cvotecontroller.h index d96a7823..68112cdc 100644 --- a/src/cs2_sdk/entity/cvotecontroller.h +++ b/src/cs2_sdk/entity/cvotecontroller.h @@ -20,7 +20,7 @@ #pragma once #include "cbaseentity.h" -//#include "util_shared.h" +// #include "util_shared.h" class CVoteController : public CBaseEntity { @@ -28,11 +28,11 @@ class CVoteController : public CBaseEntity DECLARE_SCHEMA_CLASS(CVoteController); SCHEMA_FIELD(int, m_iActiveIssueIndex) - SCHEMA_FIELD(int, m_iOnlyTeamToVote) - SCHEMA_FIELD_POINTER(int, m_nVoteOptionCount) - SCHEMA_FIELD(int, m_nPotentialVotes) - SCHEMA_FIELD(bool, m_bIsYesNoVote) - SCHEMA_FIELD_POINTER(int, m_nVotesCast) - SCHEMA_FIELD(int, m_nHighestCountIndex) - SCHEMA_FIELD_POINTER(CUtlVector, m_VoteOptions) + SCHEMA_FIELD(int, m_iOnlyTeamToVote) + SCHEMA_FIELD_POINTER(int, m_nVoteOptionCount) + SCHEMA_FIELD(int, m_nPotentialVotes) + SCHEMA_FIELD(bool, m_bIsYesNoVote) + SCHEMA_FIELD_POINTER(int, m_nVotesCast) + SCHEMA_FIELD(int, m_nHighestCountIndex) + SCHEMA_FIELD_POINTER(CUtlVector, m_VoteOptions) }; diff --git a/src/cs2_sdk/entity/globaltypes.h b/src/cs2_sdk/entity/globaltypes.h index 58561b05..ac72820a 100644 --- a/src/cs2_sdk/entity/globaltypes.h +++ b/src/cs2_sdk/entity/globaltypes.h @@ -18,9 +18,9 @@ */ #pragma once -#include #include "schema.h" #include "soundflags.h" +#include enum InputBitMask_t : uint64_t { @@ -66,12 +66,12 @@ enum EInButtonState : uint32_t enum ParticleAttachment_t : uint32_t { PATTACH_INVALID = 0xffffffff, - PATTACH_ABSORIGIN = 0x0, // Spawn at entity origin - PATTACH_ABSORIGIN_FOLLOW = 0x1, // Spawn at and follow entity origin + PATTACH_ABSORIGIN = 0x0, // Spawn at entity origin + PATTACH_ABSORIGIN_FOLLOW = 0x1, // Spawn at and follow entity origin PATTACH_CUSTOMORIGIN = 0x2, PATTACH_CUSTOMORIGIN_FOLLOW = 0x3, - PATTACH_POINT = 0x4, // Spawn at attachment point - PATTACH_POINT_FOLLOW = 0x5, // Spawn at and follow attachment point + PATTACH_POINT = 0x4, // Spawn at attachment point + PATTACH_POINT_FOLLOW = 0x5, // Spawn at and follow attachment point PATTACH_EYES_FOLLOW = 0x6, PATTACH_OVERHEAD_FOLLOW = 0x7, PATTACH_WORLDORIGIN = 0x8, @@ -151,14 +151,14 @@ struct EmitSound_t { } int m_nChannel; - const char *m_pSoundName; + const char* m_pSoundName; float m_flVolume; soundlevel_t m_SoundLevel; int m_nFlags; int m_nPitch; - const Vector *m_pOrigin; + const Vector* m_pOrigin; float m_flSoundTime; - float *m_pflSoundDuration; + float* m_pflSoundDuration; bool m_bEmitCloseCaption; bool m_bWarnOnMissingCloseCaption; bool m_bWarnOnDirectWaveReference; diff --git a/src/cs2_sdk/entity/lights.h b/src/cs2_sdk/entity/lights.h index 52bd5a6e..a2dec1fd 100644 --- a/src/cs2_sdk/entity/lights.h +++ b/src/cs2_sdk/entity/lights.h @@ -47,13 +47,13 @@ class CBarnLight : public CBaseModelEntity SCHEMA_FIELD(float, m_flColorTemperature) // default 6500 SCHEMA_FIELD(float, m_flBrightness) SCHEMA_FIELD(float, m_flBrightnessScale) - SCHEMA_FIELD(int, m_nDirectLight) // Always set to 2 for dynamic - SCHEMA_FIELD(int, m_nCastShadows) // 0 = no, 1 = dynamic (and baked but pointless here) + SCHEMA_FIELD(int, m_nDirectLight) // Always set to 2 for dynamic + SCHEMA_FIELD(int, m_nCastShadows) // 0 = no, 1 = dynamic (and baked but pointless here) SCHEMA_FIELD(int, m_nShadowMapSize) // Shadowmap size in pixels (512 is a good starting value) SCHEMA_FIELD(int, m_nShadowPriority) SCHEMA_FIELD(bool, m_bContactShadow) SCHEMA_FIELD(float, m_flRange) - SCHEMA_FIELD(float, m_flSkirt) // Falloff over the range + SCHEMA_FIELD(float, m_flSkirt) // Falloff over the range SCHEMA_FIELD(float, m_flSkirtNear) // Falloff from the source SCHEMA_FIELD(float, m_flSoftX) SCHEMA_FIELD(float, m_flSoftY) diff --git a/src/cs2_sdk/entity/services.h b/src/cs2_sdk/entity/services.h index e198332e..a9cb36e5 100644 --- a/src/cs2_sdk/entity/services.h +++ b/src/cs2_sdk/entity/services.h @@ -18,16 +18,16 @@ */ #pragma once -#include #include "globaltypes.h" -#include #include +#include +#include -#define AMMO_OFFSET_HEGRENADE 13 -#define AMMO_OFFSET_FLASHBANG 14 -#define AMMO_OFFSET_SMOKEGRENADE 15 -#define AMMO_OFFSET_MOLOTOV 16 -#define AMMO_OFFSET_DECOY 17 +#define AMMO_OFFSET_HEGRENADE 13 +#define AMMO_OFFSET_FLASHBANG 14 +#define AMMO_OFFSET_SMOKEGRENADE 15 +#define AMMO_OFFSET_MOLOTOV 16 +#define AMMO_OFFSET_DECOY 17 class CBaseEntity; @@ -65,7 +65,7 @@ class CPlayerPawnComponent SCHEMA_FIELD(CCSPlayerPawn*, __m_pChainEntity) - CCSPlayerPawn *GetPawn() { return __m_pChainEntity; } + CCSPlayerPawn* GetPawn() { return __m_pChainEntity; } }; class CPlayer_MovementServices : public CPlayerPawnComponent @@ -155,15 +155,16 @@ class CCSPlayerController_InGameMoneyServices public: DECLARE_SCHEMA_CLASS(CCSPlayerController_InGameMoneyServices); - SCHEMA_FIELD(int, m_iAccount) + SCHEMA_FIELD(int, m_iAccount) }; class CCSPlayer_ItemServices { public: DECLARE_SCHEMA_CLASS(CCSPlayer_ItemServices); - + virtual ~CCSPlayer_ItemServices() = 0; + private: virtual void unk_01() = 0; virtual void unk_02() = 0; @@ -182,12 +183,13 @@ class CCSPlayer_ItemServices virtual void unk_15() = 0; virtual void unk_16() = 0; virtual CBaseEntity* _GiveNamedItem(const char* pchName) = 0; + public: - virtual bool GiveNamedItemBool(const char* pchName) = 0; - virtual CBaseEntity* GiveNamedItem(const char* pchName) = 0; + virtual bool GiveNamedItemBool(const char* pchName) = 0; + virtual CBaseEntity* GiveNamedItem(const char* pchName) = 0; // Recommended to use CCSPlayer_WeaponServices::DropWeapon instead (parameter is ignored here) - virtual void DropActiveWeapon(CBasePlayerWeapon* pWeapon) = 0; - virtual void StripPlayerWeapons(bool removeSuit) = 0; + virtual void DropActiveWeapon(CBasePlayerWeapon* pWeapon) = 0; + virtual void StripPlayerWeapons(bool removeSuit) = 0; }; // We need an exactly sized class to be able to iterate the vector, our schema system implementation can't do this @@ -195,14 +197,14 @@ class WeaponPurchaseCount_t { private: virtual void unk01() {}; - uint64_t unk1 = 0; // 0x8 - uint64_t unk2 = 0; // 0x10 - uint64_t unk3 = 0; // 0x18 - uint64_t unk4 = 0; // 0x20 + uint64_t unk1 = 0; // 0x8 + uint64_t unk2 = 0; // 0x10 + uint64_t unk3 = 0; // 0x18 + uint64_t unk4 = 0; // 0x20 uint64_t unk5 = -1; // 0x28 public: - uint16_t m_nItemDefIndex; // 0x30 - uint16_t m_nCount; // 0x32 + uint16_t m_nItemDefIndex; // 0x30 + uint16_t m_nCount; // 0x32 private: uint32_t unk6 = 0; }; @@ -237,18 +239,18 @@ class CPlayer_ObserverServices class CPlayer_CameraServices { public: - DECLARE_SCHEMA_CLASS(CPlayer_CameraServices) + DECLARE_SCHEMA_CLASS(CPlayer_CameraServices) - SCHEMA_FIELD(CHandle, m_hViewEntity) + SCHEMA_FIELD(CHandle, m_hViewEntity) }; class CCSPlayerBase_CameraServices : public CPlayer_CameraServices { public: - DECLARE_SCHEMA_CLASS(CCSPlayerBase_CameraServices) + DECLARE_SCHEMA_CLASS(CCSPlayerBase_CameraServices) - SCHEMA_FIELD(CHandle, m_hZoomOwner) - SCHEMA_FIELD(uint, m_iFOV) + SCHEMA_FIELD(CHandle, m_hZoomOwner) + SCHEMA_FIELD(uint, m_iFOV) }; class CCSPlayer_CameraServices : public CCSPlayerBase_CameraServices diff --git a/src/cs2_sdk/entityio.h b/src/cs2_sdk/entityio.h index fbc8f6e6..e2934a47 100644 --- a/src/cs2_sdk/entityio.h +++ b/src/cs2_sdk/entityio.h @@ -1,21 +1,21 @@ /** -* ============================================================================= -* CS2Fixes -* Copyright (C) 2023-2024 Source2ZE -* ============================================================================= -* -* This program is free software; you can redistribute it and/or modify it under -* the terms of the GNU General Public License, version 3.0, as published by the -* Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, but WITHOUT -* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -* details. -* -* You should have received a copy of the GNU General Public License along with -* this program. If not, see . -*/ + * ============================================================================= + * CS2Fixes + * Copyright (C) 2023-2024 Source2ZE + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ #pragma once @@ -24,10 +24,10 @@ #define NULL 0 #endif -#include #include -#include #include +#include +#include struct EntityIOConnectionDesc_t { diff --git a/src/cs2_sdk/schema.cpp b/src/cs2_sdk/schema.cpp index 4d1ce959..888a6e39 100644 --- a/src/cs2_sdk/schema.cpp +++ b/src/cs2_sdk/schema.cpp @@ -20,129 +20,125 @@ #include "schema.h" #include "../common.h" +#include "entity/cbaseentity.h" +#include "plat.h" #include "schemasystem/schemasystem.h" #include "tier1/utlmap.h" + #include "tier0/memdbgon.h" -#include "plat.h" -#include "entity/cbaseentity.h" -extern CGlobalVars *gpGlobals; +extern CGlobalVars* gpGlobals; using SchemaKeyValueMap_t = CUtlMap; using SchemaTableMap_t = CUtlMap; - static bool IsFieldNetworked(SchemaClassFieldData_t& field) { - for (int i = 0; i < field.m_nStaticMetadataCount; i++) - { - static auto networkEnabled = hash_32_fnv1a_const("MNetworkEnable"); - if (networkEnabled == hash_32_fnv1a_const(field.m_pStaticMetadata[i].m_pszName)) - return true; - } - - return false; -} + for (int i = 0; i < field.m_nStaticMetadataCount; i++) + { + static auto networkEnabled = hash_32_fnv1a_const("MNetworkEnable"); + if (networkEnabled == hash_32_fnv1a_const(field.m_pStaticMetadata[i].m_pszName)) + return true; + } + + return false; +} -static bool InitSchemaFieldsForClass(SchemaTableMap_t *tableMap, const char* className, uint32_t classKey) +static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap, const char* className, uint32_t classKey) { - CSchemaSystemTypeScope* pType = g_pSchemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); + CSchemaSystemTypeScope* pType = g_pSchemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); - if (!pType) - return false; + if (!pType) + return false; - SchemaClassInfoData_t *pClassInfo = pType->FindDeclaredClass(className).Get(); + SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get(); - if (!pClassInfo) - { - SchemaKeyValueMap_t *map = new SchemaKeyValueMap_t(0, 0, DefLessFunc(uint32_t)); - tableMap->Insert(classKey, map); + if (!pClassInfo) + { + SchemaKeyValueMap_t* map = new SchemaKeyValueMap_t(0, 0, DefLessFunc(uint32_t)); + tableMap->Insert(classKey, map); - Warning("InitSchemaFieldsForClass(): '%s' was not found!\n", className); - return false; - } + Warning("InitSchemaFieldsForClass(): '%s' was not found!\n", className); + return false; + } - short fieldsSize = pClassInfo->m_nFieldCount; - SchemaClassFieldData_t* pFields = pClassInfo->m_pFields; + short fieldsSize = pClassInfo->m_nFieldCount; + SchemaClassFieldData_t* pFields = pClassInfo->m_pFields; - SchemaKeyValueMap_t *keyValueMap = new SchemaKeyValueMap_t(0, 0, DefLessFunc(uint32_t)); - keyValueMap->EnsureCapacity(fieldsSize); - tableMap->Insert(classKey, keyValueMap); + SchemaKeyValueMap_t* keyValueMap = new SchemaKeyValueMap_t(0, 0, DefLessFunc(uint32_t)); + keyValueMap->EnsureCapacity(fieldsSize); + tableMap->Insert(classKey, keyValueMap); - for (int i = 0; i < fieldsSize; ++i) - { - SchemaClassFieldData_t& field = pFields[i]; + for (int i = 0; i < fieldsSize; ++i) + { + SchemaClassFieldData_t& field = pFields[i]; #ifdef _DEBUG Message("%s::%s found at -> 0x%X - %llx\n", className, field.m_pszName, field.m_nSingleInheritanceOffset, &field); #endif - keyValueMap->Insert(hash_32_fnv1a_const(field.m_pszName), {field.m_nSingleInheritanceOffset, IsFieldNetworked(field)}); - } + keyValueMap->Insert(hash_32_fnv1a_const(field.m_pszName), {field.m_nSingleInheritanceOffset, IsFieldNetworked(field)}); + } - return true; + return true; } int16_t schema::FindChainOffset(const char* className) { - CSchemaSystemTypeScope* pType = g_pSchemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); + CSchemaSystemTypeScope* pType = g_pSchemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); - if (!pType) - return false; + if (!pType) + return false; - SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get(); + SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get(); - do - { - SchemaClassFieldData_t* pFields = pClassInfo->m_pFields; - short fieldsSize = pClassInfo->m_nFieldCount; - for (int i = 0; i < fieldsSize; ++i) - { - SchemaClassFieldData_t& field = pFields[i]; + do + { + SchemaClassFieldData_t* pFields = pClassInfo->m_pFields; + short fieldsSize = pClassInfo->m_nFieldCount; + for (int i = 0; i < fieldsSize; ++i) + { + SchemaClassFieldData_t& field = pFields[i]; - if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0) - { - return field.m_nSingleInheritanceOffset; - } - } - } while ((pClassInfo = pClassInfo->m_pBaseClasses ? pClassInfo->m_pBaseClasses->m_pClass : nullptr) != nullptr); + if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0) + return field.m_nSingleInheritanceOffset; + } + } while ((pClassInfo = pClassInfo->m_pBaseClasses ? pClassInfo->m_pBaseClasses->m_pClass : nullptr) != nullptr); - return 0; + return 0; } SchemaKey schema::GetOffset(const char* className, uint32_t classKey, const char* memberName, uint32_t memberKey) { static SchemaTableMap_t schemaTableMap(0, 0, DefLessFunc(uint32_t)); int16_t tableMapIndex = schemaTableMap.Find(classKey); - if (!schemaTableMap.IsValidIndex(tableMapIndex)) - { - if (InitSchemaFieldsForClass(&schemaTableMap, className, classKey)) - return GetOffset(className, classKey, memberName, memberKey); + if (!schemaTableMap.IsValidIndex(tableMapIndex)) + { + if (InitSchemaFieldsForClass(&schemaTableMap, className, classKey)) + return GetOffset(className, classKey, memberName, memberKey); - return { 0, 0 }; - } + return {0, 0}; + } - SchemaKeyValueMap_t *tableMap = schemaTableMap[tableMapIndex]; + SchemaKeyValueMap_t* tableMap = schemaTableMap[tableMapIndex]; int16_t memberIndex = tableMap->Find(memberKey); - if (!tableMap->IsValidIndex(memberIndex)) - { - Warning("schema::GetOffset(): '%s' was not found in '%s'!\n", memberName, className); - return { 0, 0 }; - } + if (!tableMap->IsValidIndex(memberIndex)) + { + Warning("schema::GetOffset(): '%s' was not found in '%s'!\n", memberName, className); + return {0, 0}; + } - return tableMap->Element(memberIndex); + return tableMap->Element(memberIndex); } void EntityNetworkStateChanged(uintptr_t entityInstance, uint nOffset) { - reinterpret_cast(entityInstance)->NetworkStateChanged(nOffset); + reinterpret_cast(entityInstance)->NetworkStateChanged(nOffset); } void ChainNetworkStateChanged(uintptr_t networkVarChainer, uint nLocalOffset) { - CEntityInstance* pEntity = *reinterpret_cast(networkVarChainer); - if (pEntity && (pEntity->m_pEntity->m_flags & EF_IS_CONSTRUCTION_IN_PROGRESS) == 0) - { - pEntity->NetworkStateChanged(nLocalOffset, -1, *reinterpret_cast(networkVarChainer + 32)); - } + CEntityInstance* pEntity = *reinterpret_cast(networkVarChainer); + if (pEntity && (pEntity->m_pEntity->m_flags & EF_IS_CONSTRUCTION_IN_PROGRESS) == 0) + pEntity->NetworkStateChanged(nLocalOffset, -1, *reinterpret_cast(networkVarChainer + 32)); } diff --git a/src/cs2_sdk/schema.h b/src/cs2_sdk/schema.h index ad6cf639..0576db0a 100644 --- a/src/cs2_sdk/schema.h +++ b/src/cs2_sdk/schema.h @@ -20,21 +20,21 @@ #pragma once #ifdef _WIN32 -#pragma warning(push) -#pragma warning(disable : 4005) + #pragma warning(push) + #pragma warning(disable : 4005) #endif #include #ifdef _WIN32 -#pragma warning(pop) + #pragma warning(pop) #endif #include "../addresses.h" -#include "tier0/dbg.h" #include "const.h" -#include "virtual.h" #include "stdint.h" +#include "tier0/dbg.h" +#include "virtual.h" #undef schema struct SchemaKey @@ -51,92 +51,116 @@ constexpr uint32_t prime_32_const = 0x1000193; constexpr uint64_t val_64_const = 0xcbf29ce484222325; constexpr uint64_t prime_64_const = 0x100000001b3; -inline constexpr uint32_t hash_32_fnv1a_const(const char *const str, const uint32_t value = val_32_const) noexcept +inline constexpr uint32_t hash_32_fnv1a_const(const char* const str, const uint32_t value = val_32_const) noexcept { return (str[0] == '\0') ? value : hash_32_fnv1a_const(&str[1], (value ^ uint32_t(str[0])) * prime_32_const); } -inline constexpr uint64_t hash_64_fnv1a_const(const char *const str, const uint64_t value = val_64_const) noexcept +inline constexpr uint64_t hash_64_fnv1a_const(const char* const str, const uint64_t value = val_64_const) noexcept { return (str[0] == '\0') ? value : hash_64_fnv1a_const(&str[1], (value ^ uint64_t(str[0])) * prime_64_const); } -#define SCHEMA_FIELD_OFFSET(type, varName, extra_offset) \ - class varName##_prop \ - { \ - public: \ - std::add_lvalue_reference_t Get() \ - { \ - static constexpr auto datatable_hash = hash_32_fnv1a_const(ThisClassName); \ - static constexpr auto prop_hash = hash_32_fnv1a_const(#varName); \ - \ - static const auto m_key = \ - schema::GetOffset(ThisClassName, datatable_hash, #varName, prop_hash); \ - \ - static const size_t offset = offsetof(ThisClass, varName); \ - ThisClass *pThisClass = (ThisClass *)((byte *)this - offset); \ - \ - return *reinterpret_cast>( \ - (uintptr_t)(pThisClass) + m_key.offset + extra_offset); \ - } \ - void Set(type val) \ - { \ - static constexpr auto datatable_hash = hash_32_fnv1a_const(ThisClassName); \ - static constexpr auto prop_hash = hash_32_fnv1a_const(#varName); \ - \ - static const auto m_key = \ - schema::GetOffset(ThisClassName, datatable_hash, #varName, prop_hash); \ - \ - static const auto m_chain = \ - schema::FindChainOffset(ThisClassName); \ - \ - static const size_t offset = offsetof(ThisClass, varName); \ - ThisClass *pThisClass = (ThisClass *)((byte *)this - offset); \ - \ - if (m_chain != 0 && m_key.networked) \ - { \ - DevMsg("Found chain offset %d for %s::%s\n", m_chain, ThisClassName, #varName); \ - ChainNetworkStateChanged((uintptr_t)(pThisClass) + m_chain, m_key.offset + extra_offset); \ - } \ - else if(m_key.networked) \ - { \ - /* WIP: Works fine for most props, but inlined classes in the middle of a class will - need to have their this pointer corrected by the offset .*/ \ - if (!IsStruct) \ - EntityNetworkStateChanged((uintptr_t)pThisClass, m_key.offset + extra_offset); \ - else \ - CALL_VIRTUAL(void, 1, pThisClass, m_key.offset + extra_offset, 0xFFFFFFFF, 0xFFFFFFFF); \ - } \ - *reinterpret_cast>((uintptr_t)(pThisClass) + m_key.offset + extra_offset) = val; \ - } \ - operator std::add_lvalue_reference_t() { return Get(); } \ - std::add_lvalue_reference_t operator ()() { return Get(); } \ - std::add_lvalue_reference_t operator->() { return Get(); } \ - void operator()(type val) { Set(val); } \ - void operator=(type val) { Set(val); } \ +#define SCHEMA_FIELD_OFFSET(type, varName, extra_offset) \ + class varName##_prop \ + { \ + public: \ + std::add_lvalue_reference_t Get() \ + { \ + static constexpr auto datatable_hash = hash_32_fnv1a_const(ThisClassName); \ + static constexpr auto prop_hash = hash_32_fnv1a_const(#varName); \ + \ + static const auto m_key = \ + schema::GetOffset(ThisClassName, datatable_hash, #varName, prop_hash); \ + \ + static const size_t offset = offsetof(ThisClass, varName); \ + ThisClass* pThisClass = (ThisClass*)((byte*)this - offset); \ + \ + return *reinterpret_cast>( \ + (uintptr_t)(pThisClass) + m_key.offset + extra_offset); \ + } \ + void Set(type val) \ + { \ + static constexpr auto datatable_hash = hash_32_fnv1a_const(ThisClassName); \ + static constexpr auto prop_hash = hash_32_fnv1a_const(#varName); \ + \ + static const auto m_key = \ + schema::GetOffset(ThisClassName, datatable_hash, #varName, prop_hash); \ + \ + static const auto m_chain = \ + schema::FindChainOffset(ThisClassName); \ + \ + static const size_t offset = offsetof(ThisClass, varName); \ + ThisClass* pThisClass = (ThisClass*)((byte*)this - offset); \ + \ + if (m_chain != 0 && m_key.networked) \ + { \ + DevMsg("Found chain offset %d for %s::%s\n", m_chain, ThisClassName, #varName); \ + ChainNetworkStateChanged((uintptr_t)(pThisClass) + m_chain, m_key.offset + extra_offset); \ + } \ + else if (m_key.networked) \ + { \ + /* WIP: Works fine for most props, but inlined classes in the middle of a class will \ + need to have their this pointer corrected by the offset .*/ \ + if (!IsStruct) \ + EntityNetworkStateChanged((uintptr_t)pThisClass, m_key.offset + extra_offset); \ + else \ + CALL_VIRTUAL(void, 1, pThisClass, m_key.offset + extra_offset, 0xFFFFFFFF, 0xFFFFFFFF); \ + } \ + *reinterpret_cast>((uintptr_t)(pThisClass) + m_key.offset + extra_offset) = val; \ + } \ + operator std::add_lvalue_reference_t() \ + { \ + return Get(); \ + } \ + std::add_lvalue_reference_t operator()() \ + { \ + return Get(); \ + } \ + std::add_lvalue_reference_t operator->() \ + { \ + return Get(); \ + } \ + void operator()(type val) \ + { \ + Set(val); \ + } \ + void operator=(type val) \ + { \ + Set(val); \ + } \ } varName; -#define SCHEMA_FIELD_POINTER_OFFSET(type, varName, extra_offset) \ - class varName##_prop \ - { \ - public: \ - type *Get() \ - { \ - static constexpr auto datatable_hash = hash_32_fnv1a_const(ThisClassName); \ - static constexpr auto prop_hash = hash_32_fnv1a_const(#varName); \ - \ - static const auto m_key = \ - schema::GetOffset(ThisClassName, datatable_hash, #varName, prop_hash); \ - \ - static const size_t offset = offsetof(ThisClass, varName); \ - ThisClass *pThisClass = (ThisClass *)((byte *)this - offset); \ - \ - return reinterpret_cast>( \ - (uintptr_t)(pThisClass) + m_key.offset + extra_offset); \ - } \ - operator type*() { return Get(); } \ - type* operator ()() { return Get(); } \ - type* operator->() { return Get(); } \ +#define SCHEMA_FIELD_POINTER_OFFSET(type, varName, extra_offset) \ + class varName##_prop \ + { \ + public: \ + type* Get() \ + { \ + static constexpr auto datatable_hash = hash_32_fnv1a_const(ThisClassName); \ + static constexpr auto prop_hash = hash_32_fnv1a_const(#varName); \ + \ + static const auto m_key = \ + schema::GetOffset(ThisClassName, datatable_hash, #varName, prop_hash); \ + \ + static const size_t offset = offsetof(ThisClass, varName); \ + ThisClass* pThisClass = (ThisClass*)((byte*)this - offset); \ + \ + return reinterpret_cast>( \ + (uintptr_t)(pThisClass) + m_key.offset + extra_offset); \ + } \ + operator type*() \ + { \ + return Get(); \ + } \ + type* operator()() \ + { \ + return Get(); \ + } \ + type* operator->() \ + { \ + return Get(); \ + } \ } varName; // Use this when you want the member's value itself @@ -149,14 +173,14 @@ inline constexpr uint64_t hash_64_fnv1a_const(const char *const str, const uint6 namespace schema { - int16_t FindChainOffset(const char *className); - SchemaKey GetOffset(const char *className, uint32_t classKey, const char *memberName, uint32_t memberKey); -} - -#define DECLARE_SCHEMA_CLASS_BASE(className, isStruct) \ - typedef className ThisClass; \ - static constexpr const char *ThisClassName = #className; \ - static constexpr bool IsStruct = isStruct; + int16_t FindChainOffset(const char* className); + SchemaKey GetOffset(const char* className, uint32_t classKey, const char* memberName, uint32_t memberKey); +} // namespace schema + +#define DECLARE_SCHEMA_CLASS_BASE(className, isStruct) \ + typedef className ThisClass; \ + static constexpr const char* ThisClassName = #className; \ + static constexpr bool IsStruct = isStruct; #define DECLARE_SCHEMA_CLASS(className) DECLARE_SCHEMA_CLASS_BASE(className, false) diff --git a/src/cs2fixes.cpp b/src/cs2fixes.cpp index 8e51133d..1c5270d4 100644 --- a/src/cs2fixes.cpp +++ b/src/cs2fixes.cpp @@ -20,46 +20,45 @@ #include "cs2fixes.h" #include "iserver.h" +#include "adminsystem.h" #include "appframework/IAppSystem.h" -#include "common.h" #include "commands.h" +#include "common.h" +#include "cs_gameevents.pb.h" +#include "ctimer.h" #include "detours.h" -#include "patches.h" -#include "icvar.h" -#include "interface.h" -#include "tier0/dbg.h" -#include "tier0/vprof.h" -#include "schemasystem/schemasystem.h" -#include "plat.h" -#include "entitysystem.h" +#include "discord.h" #include "engine/igameeventsystem.h" -#include "networkstringtabledefs.h" -#include "gamesystem.h" -#include "ctimer.h" #include "entities.h" -#include "playermanager.h" -#include -#include "adminsystem.h" -#include "commands.h" +#include "entity/ccsplayercontroller.h" +#include "entity/cgamerules.h" +#include "entitylistener.h" +#include "entitysystem.h" #include "eventlistener.h" #include "gameconfig.h" -#include "votemanager.h" -#include "zombiereborn.h" +#include "gameevents.pb.h" +#include "gamesystem.h" #include "httpmanager.h" +#include "icvar.h" #include "idlemanager.h" -#include "discord.h" -#include "panoramavote.h" +#include "interface.h" +#include "leader.h" #include "map_votes.h" -#include "user_preferences.h" -#include "entity/cgamerules.h" -#include "entity/ccsplayercontroller.h" -#include "entitylistener.h" +#include "networkstringtabledefs.h" +#include "panoramavote.h" +#include "patches.h" +#include "plat.h" +#include "playermanager.h" +#include "schemasystem/schemasystem.h" #include "serversideclient.h" #include "te.pb.h" -#include "cs_gameevents.pb.h" -#include "gameevents.pb.h" -#include "leader.h" +#include "tier0/dbg.h" +#include "tier0/vprof.h" +#include "user_preferences.h" #include "usermessages.pb.h" +#include "votemanager.h" +#include "zombiereborn.h" +#include #include "tier0/memdbgon.h" @@ -68,7 +67,7 @@ float g_flLastTickedTime; bool g_bHasTicked; int g_iRoundNum = 0; -void Message(const char *msg, ...) +void Message(const char* msg, ...) { va_list args; va_start(args, msg); @@ -81,7 +80,7 @@ void Message(const char *msg, ...) va_end(args); } -void Panic(const char *msg, ...) +void Panic(const char* msg, ...) { va_list args; va_start(args, msg); @@ -94,46 +93,47 @@ void Panic(const char *msg, ...) va_end(args); } -class GameSessionConfiguration_t { }; +class GameSessionConfiguration_t +{}; SH_DECL_HOOK3_void(IServerGameDLL, GameFrame, SH_NOATTRIB, 0, bool, bool, bool); SH_DECL_HOOK0_void(IServerGameDLL, GameServerSteamAPIActivated, SH_NOATTRIB, 0); SH_DECL_HOOK0_void(IServerGameDLL, GameServerSteamAPIDeactivated, SH_NOATTRIB, 0); SH_DECL_HOOK1_void(IServerGameDLL, ApplyGameSettings, SH_NOATTRIB, 0, KeyValues*); -SH_DECL_HOOK4_void(IServerGameClients, ClientActive, SH_NOATTRIB, 0, CPlayerSlot, bool, const char *, uint64); -SH_DECL_HOOK5_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, CPlayerSlot, ENetworkDisconnectionReason, const char *, uint64, const char *); -SH_DECL_HOOK4_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, CPlayerSlot, char const *, int, uint64); -SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, CPlayerSlot ); -SH_DECL_HOOK6_void(IServerGameClients, OnClientConnected, SH_NOATTRIB, 0, CPlayerSlot, const char*, uint64, const char *, const char *, bool); -SH_DECL_HOOK6(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, CPlayerSlot, const char*, uint64, const char *, bool, CBufferString *); +SH_DECL_HOOK4_void(IServerGameClients, ClientActive, SH_NOATTRIB, 0, CPlayerSlot, bool, const char*, uint64); +SH_DECL_HOOK5_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, CPlayerSlot, ENetworkDisconnectionReason, const char*, uint64, const char*); +SH_DECL_HOOK4_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, CPlayerSlot, char const*, int, uint64); +SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, CPlayerSlot); +SH_DECL_HOOK6_void(IServerGameClients, OnClientConnected, SH_NOATTRIB, 0, CPlayerSlot, const char*, uint64, const char*, const char*, bool); +SH_DECL_HOOK6(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, CPlayerSlot, const char*, uint64, const char*, bool, CBufferString*); SH_DECL_HOOK8_void(IGameEventSystem, PostEventAbstract, SH_NOATTRIB, 0, CSplitScreenSlot, bool, int, const uint64*, - INetworkMessageInternal*, const CNetMessage*, unsigned long, NetChannelBufType_t) -SH_DECL_HOOK3_void(INetworkServerService, StartupServer, SH_NOATTRIB, 0, const GameSessionConfiguration_t&, ISource2WorldSession*, const char*); -SH_DECL_HOOK7_void(ISource2GameEntities, CheckTransmit, SH_NOATTRIB, 0, CCheckTransmitInfo **, int, CBitVec<16384> &, const Entity2Networkable_t **, const uint16 *, int, bool); -SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, CPlayerSlot, const CCommand &); + INetworkMessageInternal*, const CNetMessage*, unsigned long, NetChannelBufType_t) + SH_DECL_HOOK3_void(INetworkServerService, StartupServer, SH_NOATTRIB, 0, const GameSessionConfiguration_t&, ISource2WorldSession*, const char*); +SH_DECL_HOOK7_void(ISource2GameEntities, CheckTransmit, SH_NOATTRIB, 0, CCheckTransmitInfo**, int, CBitVec<16384>&, const Entity2Networkable_t**, const uint16*, int, bool); +SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, CPlayerSlot, const CCommand&); SH_DECL_HOOK3_void(ICvar, DispatchConCommand, SH_NOATTRIB, 0, ConCommandHandle, const CCommandContext&, const CCommand&); SH_DECL_MANUALHOOK1_void(CGamePlayerEquipUse, 0, 0, 0, InputData_t*); SH_DECL_MANUALHOOK2_void(CreateWorkshopMapGroup, 0, 0, 0, const char*, const CUtlStringList&); -SH_DECL_MANUALHOOK1(OnTakeDamage_Alive, 0, 0, 0, bool, CTakeDamageInfoContainer *); +SH_DECL_MANUALHOOK1(OnTakeDamage_Alive, 0, 0, 0, bool, CTakeDamageInfoContainer*); SH_DECL_MANUALHOOK1_void(CheckMovingGround, 0, 0, 0, double); -SH_DECL_HOOK2(IGameEventManager2, LoadEventsFromFile, SH_NOATTRIB, 0, int, const char *, bool); +SH_DECL_HOOK2(IGameEventManager2, LoadEventsFromFile, SH_NOATTRIB, 0, int, const char*, bool); SH_DECL_MANUALHOOK1_void(GoToIntermission, 0, 0, 0, bool); SH_DECL_MANUALHOOK2_void(PhysicsTouchShuffle, 0, 0, 0, CUtlVector*, bool); CS2Fixes g_CS2Fixes; -IGameEventSystem *g_gameEventSystem = nullptr; -IGameEventManager2 *g_gameEventManager = nullptr; -INetworkGameServer *g_pNetworkGameServer = nullptr; -CGameEntitySystem *g_pEntitySystem = nullptr; -CEntityListener *g_pEntityListener = nullptr; -CGlobalVars *gpGlobals = nullptr; -CPlayerManager *g_playerManager = nullptr; -IVEngineServer2 *g_pEngineServer2 = nullptr; -CGameConfig *g_GameConfig = nullptr; -ISteamHTTP *g_http = nullptr; +IGameEventSystem* g_gameEventSystem = nullptr; +IGameEventManager2* g_gameEventManager = nullptr; +INetworkGameServer* g_pNetworkGameServer = nullptr; +CGameEntitySystem* g_pEntitySystem = nullptr; +CEntityListener* g_pEntityListener = nullptr; +CGlobalVars* gpGlobals = nullptr; +CPlayerManager* g_playerManager = nullptr; +IVEngineServer2* g_pEngineServer2 = nullptr; +CGameConfig* g_GameConfig = nullptr; +ISteamHTTP* g_http = nullptr; CSteamGameServerAPIContext g_steamAPI; -CCSGameRules *g_pGameRules = nullptr; +CCSGameRules* g_pGameRules = nullptr; int g_iCGamePlayerEquipUseId = -1; int g_iCreateWorkshopMapGroupId = -1; int g_iOnTakeDamageAliveId = -1; @@ -142,14 +142,14 @@ int g_iLoadEventsFromFileId = -1; int g_iGoToIntermissionId = -1; int g_iPhysicsTouchShuffle = -1; -CGameEntitySystem *GameEntitySystem() +CGameEntitySystem* GameEntitySystem() { static int offset = g_GameConfig->GetOffset("GameEntitySystem"); - return *reinterpret_cast((uintptr_t)(g_pGameResourceServiceServer) + offset); + return *reinterpret_cast((uintptr_t)(g_pGameResourceServiceServer) + offset); } PLUGIN_EXPOSE(CS2Fixes, g_CS2Fixes); -bool CS2Fixes::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late) +bool CS2Fixes::Load(PluginId id, ISmmAPI* ismm, char* error, size_t maxlen, bool late) { PLUGIN_SAVEVARS(); @@ -171,7 +171,7 @@ bool CS2Fixes::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool // Required to get the IMetamodListener events g_SMAPI->AddListener(this, this); - Message( "Starting plugin.\n" ); + Message("Starting plugin.\n"); CBufferStringGrowable<256> gamedirpath; g_pEngineServer2->GetGameDir(gamedirpath); @@ -202,7 +202,7 @@ bool CS2Fixes::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool SH_ADD_HOOK(IServerGameClients, ClientPutInServer, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientPutInServer), true); SH_ADD_HOOK(IServerGameClients, ClientSettingsChanged, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientSettingsChanged), false); SH_ADD_HOOK(IServerGameClients, OnClientConnected, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_OnClientConnected), false); - SH_ADD_HOOK(IServerGameClients, ClientConnect, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientConnect), false ); + SH_ADD_HOOK(IServerGameClients, ClientConnect, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientConnect), false); SH_ADD_HOOK(IServerGameClients, ClientCommand, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientCommand), false); SH_ADD_HOOK(IGameEventSystem, PostEventAbstract, g_gameEventSystem, SH_MEMBER(this, &CS2Fixes::Hook_PostEvent), false); SH_ADD_HOOK(INetworkServerService, StartupServer, g_pNetworkServerService, SH_MEMBER(this, &CS2Fixes::Hook_StartupServer), true); @@ -210,7 +210,7 @@ bool CS2Fixes::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool SH_ADD_HOOK(ICvar, DispatchConCommand, g_pCVar, SH_MEMBER(this, &CS2Fixes::Hook_DispatchConCommand), false); g_iCreateWorkshopMapGroupId = SH_ADD_MANUALVPHOOK(CreateWorkshopMapGroup, g_pGameTypes, SH_MEMBER(this, &CS2Fixes::Hook_CreateWorkshopMapGroup), false); - META_CONPRINTF( "All hooks started!\n" ); + META_CONPRINTF("All hooks started!\n"); bool bRequiredInitLoaded = true; @@ -300,7 +300,7 @@ bool CS2Fixes::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool SH_MANUALHOOK_RECONFIGURE(GoToIntermission, offset, 0, 0); g_iGoToIntermissionId = SH_ADD_MANUALDVPHOOK(GoToIntermission, pCCSGameRulesVTable, SH_MEMBER(this, &CS2Fixes::Hook_GoToIntermission), false); - Message( "All hooks started!\n" ); + Message("All hooks started!\n"); UnlockConVars(); UnlockConCommands(); @@ -331,22 +331,19 @@ bool CS2Fixes::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool RegisterWeaponCommands(); // Check hide distance - new CTimer(0.5f, true, true, []() - { + new CTimer(0.5f, true, true, []() { g_playerManager->CheckHideDistances(); return 0.5f; }); // Check for the expiration of infractions like mutes or gags - new CTimer(30.0f, true, true, []() - { + new CTimer(30.0f, true, true, []() { g_playerManager->CheckInfractions(); return 30.0f; }); // Check for idle players and kick them if permitted by cs2f_idle_kick_* 'convars' - new CTimer(5.0f, true, true, []() - { + new CTimer(5.0f, true, true, []() { g_pIdleSystem->CheckForIdleClients(); return 5.0f; }); @@ -361,9 +358,9 @@ bool CS2Fixes::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool return true; } -bool CS2Fixes::Unload(char *error, size_t maxlen) +bool CS2Fixes::Unload(char* error, size_t maxlen) { - SH_REMOVE_HOOK(IServerGameDLL, GameFrame, g_pSource2Server, SH_MEMBER(this, &CS2Fixes::Hook_GameFramePost), true); + SH_REMOVE_HOOK(IServerGameDLL, GameFrame, g_pSource2Server, SH_MEMBER(this, &CS2Fixes::Hook_GameFramePost), true); SH_REMOVE_HOOK(IServerGameDLL, GameServerSteamAPIActivated, g_pSource2Server, SH_MEMBER(this, &CS2Fixes::Hook_GameServerSteamAPIActivated), false); SH_REMOVE_HOOK(IServerGameDLL, GameServerSteamAPIDeactivated, g_pSource2Server, SH_MEMBER(this, &CS2Fixes::Hook_GameServerSteamAPIDeactivated), false); SH_REMOVE_HOOK(IServerGameDLL, ApplyGameSettings, g_pSource2Server, SH_MEMBER(this, &CS2Fixes::Hook_ApplyGameSettings), false); @@ -372,7 +369,7 @@ bool CS2Fixes::Unload(char *error, size_t maxlen) SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientPutInServer), true); SH_REMOVE_HOOK(IServerGameClients, ClientSettingsChanged, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientSettingsChanged), false); SH_REMOVE_HOOK(IServerGameClients, OnClientConnected, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_OnClientConnected), false); - SH_REMOVE_HOOK(IServerGameClients, ClientConnect, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientConnect), false ); + SH_REMOVE_HOOK(IServerGameClients, ClientConnect, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientConnect), false); SH_REMOVE_HOOK(IServerGameClients, ClientCommand, g_pSource2GameClients, SH_MEMBER(this, &CS2Fixes::Hook_ClientCommand), false); SH_REMOVE_HOOK(IGameEventSystem, PostEventAbstract, g_gameEventSystem, SH_MEMBER(this, &CS2Fixes::Hook_PostEvent), false); SH_REMOVE_HOOK(INetworkServerService, StartupServer, g_pNetworkServerService, SH_MEMBER(this, &CS2Fixes::Hook_StartupServer), true); @@ -413,7 +410,7 @@ bool CS2Fixes::Unload(char *error, size_t maxlen) if (g_pZRWeaponConfig) delete g_pZRWeaponConfig; - + if (g_pZRHitgroupConfig) delete g_pZRHitgroupConfig; @@ -465,7 +462,7 @@ void CS2Fixes::Hook_DispatchConCommand(ConCommandHandle cmdHandle, const CComman // Chat messages should generate events regardless if (pController) { - IGameEvent *pEvent = g_gameEventManager->CreateEvent("player_chat"); + IGameEvent* pEvent = g_gameEventManager->CreateEvent("player_chat"); if (pEvent) { @@ -479,7 +476,8 @@ void CS2Fixes::Hook_DispatchConCommand(ConCommandHandle cmdHandle, const CComman if (!bGagged && !bSilent && !bFlooding) { - SH_CALL(g_pCVar, &ICvar::DispatchConCommand)(cmdHandle, ctx, args); + SH_CALL(g_pCVar, &ICvar::DispatchConCommand) + (cmdHandle, ctx, args); } else if (bFlooding) { @@ -490,12 +488,12 @@ void CS2Fixes::Hook_DispatchConCommand(ConCommandHandle cmdHandle, const CComman { // HACK: At this point, we can safely modify the arg buffer as it won't be passed anywhere else // The string here is originally ("@foo bar"), trim it to be (foo bar) - char *pszMessage = (char*)(args.ArgS() + 2); + char* pszMessage = (char*)(args.ArgS() + 2); pszMessage[V_strlen(pszMessage) - 1] = 0; for (int i = 0; i < gpGlobals->maxClients; i++) { - ZEPlayer *pPlayer = g_playerManager->GetPlayer(i); + ZEPlayer* pPlayer = g_playerManager->GetPlayer(i); if (!pPlayer) continue; @@ -510,16 +508,14 @@ void CS2Fixes::Hook_DispatchConCommand(ConCommandHandle cmdHandle, const CComman // Finally, run the chat command if it is one, so anything will print after the player's message if (bCommand) { - char *pszMessage = (char *)(args.ArgS() + 1); + char* pszMessage = (char*)(args.ArgS() + 1); - if (pszMessage[0] == '"' || pszMessage[0] == '!' || pszMessage[0] == '/'){ + if (pszMessage[0] == '"' || pszMessage[0] == '!' || pszMessage[0] == '/') pszMessage += 1; - } // Host_Say at some point removes the trailing " for whatever reason, so we only remove if it was never called - if (bSilent && pszMessage[V_strlen(pszMessage) - 1] == '"'){ + if (bSilent && pszMessage[V_strlen(pszMessage) - 1] == '"') pszMessage[V_strlen(pszMessage) - 1] = '\0'; - } ParseChatCommand(pszMessage, pController); } @@ -530,7 +526,7 @@ void CS2Fixes::Hook_DispatchConCommand(ConCommandHandle cmdHandle, const CComman RETURN_META(MRES_IGNORED); } -void CS2Fixes::Hook_StartupServer(const GameSessionConfiguration_t& config, ISource2WorldSession *pSession, const char *pszMapName) +void CS2Fixes::Hook_StartupServer(const GameSessionConfiguration_t& config, ISource2WorldSession* pSession, const char* pszMapName) { g_pNetworkGameServer = g_pNetworkServerService->GetIGameServer(); g_pEntitySystem = GameEntitySystem(); @@ -539,7 +535,7 @@ void CS2Fixes::Hook_StartupServer(const GameSessionConfiguration_t& config, ISou Message("Hook_StartupServer: %s\n", pszMapName); - if(g_bHasTicked) + if (g_bHasTicked) RemoveMapTimers(); g_bHasTicked = false; @@ -580,14 +576,14 @@ void CS2Fixes::Hook_GameServerSteamAPIDeactivated() } void CS2Fixes::Hook_PostEvent(CSplitScreenSlot nSlot, bool bLocalOnly, int nClientCount, const uint64* clients, - INetworkMessageInternal* pEvent, const CNetMessage* pData, unsigned long nSize, NetChannelBufType_t bufType) + INetworkMessageInternal* pEvent, const CNetMessage* pData, unsigned long nSize, NetChannelBufType_t bufType) { // Message( "Hook_PostEvent(%d, %d, %d, %lli)\n", nSlot, bLocalOnly, nClientCount, clients ); // Need to explicitly get a pointer to the right function as it's overloaded and SH_CALL can't resolve that - static void (IGameEventSystem::*PostEventAbstract)(CSplitScreenSlot, bool, int, const uint64 *, - INetworkMessageInternal *, const CNetMessage *, unsigned long, NetChannelBufType_t) = &IGameEventSystem::PostEventAbstract; + static void (IGameEventSystem::*PostEventAbstract)(CSplitScreenSlot, bool, int, const uint64*, + INetworkMessageInternal*, const CNetMessage*, unsigned long, NetChannelBufType_t) = &IGameEventSystem::PostEventAbstract; - NetMessageInfo_t *info = pEvent->GetNetMessageInfo(); + NetMessageInfo_t* info = pEvent->GetNetMessageInfo(); if (g_bEnableStopSound && info->m_MessageId == GE_FireBulletsId) { @@ -607,7 +603,7 @@ void CS2Fixes::Hook_PostEvent(CSplitScreenSlot nSlot, bool bLocalOnly, int nClie msg->set_sound_type(9); msg->set_item_def_index(61); // weapon_usp_silencer - uint64 clientMask = *(uint64 *)clients & g_playerManager->GetSilenceSoundMask(); + uint64 clientMask = *(uint64*)clients & g_playerManager->GetSilenceSoundMask(); SH_CALL(g_gameEventSystem, PostEventAbstract) (nSlot, bLocalOnly, nClientCount, &clientMask, pEvent, msg, nSize, bufType); @@ -618,12 +614,12 @@ void CS2Fixes::Hook_PostEvent(CSplitScreenSlot nSlot, bool bLocalOnly, int nClie } // Filter out people using stop/silence sound from the original event - *(uint64 *)clients &= ~g_playerManager->GetStopSoundMask(); - *(uint64 *)clients &= ~g_playerManager->GetSilenceSoundMask(); + *(uint64*)clients &= ~g_playerManager->GetStopSoundMask(); + *(uint64*)clients &= ~g_playerManager->GetSilenceSoundMask(); } else if (info->m_MessageId == TE_WorldDecalId) { - *(uint64 *)clients &= ~g_playerManager->GetStopDecalsMask(); + *(uint64*)clients &= ~g_playerManager->GetStopDecalsMask(); } else if (info->m_MessageId == GE_Source1LegacyGameEvent) { @@ -638,32 +634,31 @@ void CS2Fixes::Hook_PostEvent(CSplitScreenSlot nSlot, bool bLocalOnly, int nClie // remove client with noshake from the event if (g_bEnableNoShake) - *(uint64 *)clients &= ~g_playerManager->GetNoShakeMask(); + *(uint64*)clients &= ~g_playerManager->GetNoShakeMask(); } - } void CS2Fixes::AllPluginsLoaded() { - /* This is where we'd do stuff that relies on the mod or other plugins + /* This is where we'd do stuff that relies on the mod or other plugins * being initialized (for example, cvars added and events registered). */ - Message( "AllPluginsLoaded\n" ); + Message("AllPluginsLoaded\n"); } -CUtlVector *GetClientList() +CUtlVector* GetClientList() { if (!g_pNetworkGameServer) return nullptr; static int offset = g_GameConfig->GetOffset("CNetworkGameServer_ClientList"); - return (CUtlVector *)(&g_pNetworkGameServer[offset]); + return (CUtlVector*)(&g_pNetworkGameServer[offset]); } -CServerSideClient *GetClientBySlot(CPlayerSlot slot) +CServerSideClient* GetClientBySlot(CPlayerSlot slot) { - CUtlVector *pClients = GetClientList(); + CUtlVector* pClients = GetClientList(); if (!pClients) return nullptr; @@ -676,7 +671,7 @@ void FullUpdateAllClients() auto pClients = GetClientList(); FOR_EACH_VEC(*pClients, i) - (*pClients)[i]->ForceFullUpdate(); + (*pClients)[i]->ForceFullUpdate(); } // Because sv_fullupdate doesn't work @@ -685,15 +680,15 @@ CON_COMMAND_F(cs2f_fullupdate, "Force a full update for all clients.", FCVAR_LIN FullUpdateAllClients(); } -void CS2Fixes::Hook_ClientActive( CPlayerSlot slot, bool bLoadGame, const char *pszName, uint64 xuid ) +void CS2Fixes::Hook_ClientActive(CPlayerSlot slot, bool bLoadGame, const char* pszName, uint64 xuid) { - Message( "Hook_ClientActive(%d, %d, \"%s\", %lli)\n", slot, bLoadGame, pszName, xuid ); + Message("Hook_ClientActive(%d, %d, \"%s\", %lli)\n", slot, bLoadGame, pszName, xuid); } -void CS2Fixes::Hook_ClientCommand( CPlayerSlot slot, const CCommand &args ) +void CS2Fixes::Hook_ClientCommand(CPlayerSlot slot, const CCommand& args) { #ifdef _DEBUG - Message( "Hook_ClientCommand(%d, \"%s\")\n", slot, args.GetCommandString() ); + Message("Hook_ClientCommand(%d, \"%s\")\n", slot, args.GetCommandString()); #endif if (g_fIdleKickTime > 0.0f) @@ -719,10 +714,10 @@ void CS2Fixes::Hook_ClientCommand( CPlayerSlot slot, const CCommand &args ) } } -void CS2Fixes::Hook_ClientSettingsChanged( CPlayerSlot slot ) +void CS2Fixes::Hook_ClientSettingsChanged(CPlayerSlot slot) { #ifdef _DEBUG - Message( "Hook_ClientSettingsChanged(%d)\n", slot ); + Message("Hook_ClientSettingsChanged(%d)\n", slot); #endif } @@ -740,9 +735,9 @@ void CS2Fixes::Hook_OnClientConnected(CPlayerSlot slot, const char* pszName, uin g_playerManager->OnBotConnected(slot); } -bool CS2Fixes::Hook_ClientConnect( CPlayerSlot slot, const char *pszName, uint64 xuid, const char *pszNetworkID, bool unk1, CBufferString *pRejectReason ) +bool CS2Fixes::Hook_ClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason) { - Message( "Hook_ClientConnect(%d, \"%s\", %lli, \"%s\", %d, \"%s\")\n", slot, pszName, xuid, pszNetworkID, unk1, pRejectReason->ToGrowable()->Get() ); + Message("Hook_ClientConnect(%d, \"%s\", %lli, \"%s\", %d, \"%s\")\n", slot, pszName, xuid, pszNetworkID, unk1, pRejectReason->ToGrowable()->Get()); // Player is banned if (!g_playerManager->OnClientConnected(slot, xuid, pszNetworkID)) @@ -751,9 +746,9 @@ bool CS2Fixes::Hook_ClientConnect( CPlayerSlot slot, const char *pszName, uint64 RETURN_META_VALUE(MRES_IGNORED, true); } -void CS2Fixes::Hook_ClientPutInServer( CPlayerSlot slot, char const *pszName, int type, uint64 xuid ) +void CS2Fixes::Hook_ClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid) { - Message( "Hook_ClientPutInServer(%d, \"%s\", %d, %d, %lli)\n", slot, pszName, type, xuid ); + Message("Hook_ClientPutInServer(%d, \"%s\", %d, %d, %lli)\n", slot, pszName, type, xuid); if (!g_playerManager->GetPlayer(slot)) return; @@ -764,9 +759,9 @@ void CS2Fixes::Hook_ClientPutInServer( CPlayerSlot slot, char const *pszName, in ZR_Hook_ClientPutInServer(slot, pszName, type, xuid); } -void CS2Fixes::Hook_ClientDisconnect( CPlayerSlot slot, ENetworkDisconnectionReason reason, const char *pszName, uint64 xuid, const char *pszNetworkID ) +void CS2Fixes::Hook_ClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID) { - Message( "Hook_ClientDisconnect(%d, %d, \"%s\", %lli)\n", slot, reason, pszName, xuid ); + Message("Hook_ClientDisconnect(%d, %d, \"%s\", %lli)\n", slot, reason, pszName, xuid); ZEPlayer* pPlayer = g_playerManager->GetPlayer(slot); if (!pPlayer) @@ -791,9 +786,7 @@ void CS2Fixes::Hook_GameFramePost(bool simulating, bool bFirstTick, bool bLastTi VPROF_BUDGET("CS2Fixes::Hook_GameFramePost", "CS2FixesPerFrame"); if (simulating && g_bHasTicked) - { g_flUniversalTime += gpGlobals->curtime - g_flLastTickedTime; - } g_flLastTickedTime = gpGlobals->curtime; g_bHasTicked = true; @@ -808,7 +801,7 @@ void CS2Fixes::Hook_GameFramePost(bool simulating, bool bFirstTick, bool bLastTi if (timer->m_flLastExecute == -1) timer->m_flLastExecute = g_flUniversalTime; - // Timer execute + // Timer execute if (timer->m_flLastExecute + timer->m_flInterval <= g_flUniversalTime) { if ((!timer->m_bPreserveRoundChange && timer->m_iRoundNum != g_iRoundNum) || !timer->Execute()) @@ -826,13 +819,13 @@ void CS2Fixes::Hook_GameFramePost(bool simulating, bool bFirstTick, bool bLastTi if (g_bEnableZR) CZRRegenTimer::Tick(); - EntityHandler_OnGameFramePost(simulating, gpGlobals->tickcount); + EntityHandler_OnGameFramePost(simulating, gpGlobals->tickcount); } extern bool g_bFlashLightTransmitOthers; -void CS2Fixes::Hook_CheckTransmit(CCheckTransmitInfo **ppInfoList, int infoCount, CBitVec<16384> &unionTransmitEdicts, - const Entity2Networkable_t **pNetworkables, const uint16 *pEntityIndicies, int nEntities, bool bEnablePVSBits) +void CS2Fixes::Hook_CheckTransmit(CCheckTransmitInfo** ppInfoList, int infoCount, CBitVec<16384>& unionTransmitEdicts, + const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntities, bool bEnablePVSBits) { if (!g_pEntitySystem) return; @@ -841,12 +834,12 @@ void CS2Fixes::Hook_CheckTransmit(CCheckTransmitInfo **ppInfoList, int infoCount for (int i = 0; i < infoCount; i++) { - auto &pInfo = ppInfoList[i]; + auto& pInfo = ppInfoList[i]; // the offset happens to have a player index here, // though this is probably part of the client class that contains the CCheckTransmitInfo static int offset = g_GameConfig->GetOffset("CheckTransmitPlayerSlot"); - int iPlayerSlot = (int)*((uint8 *)pInfo + offset); + int iPlayerSlot = (int)*((uint8*)pInfo + offset); CCSPlayerController* pSelfController = CCSPlayerController::FromSlot(iPlayerSlot); @@ -866,18 +859,16 @@ void CS2Fixes::Hook_CheckTransmit(CCheckTransmitInfo **ppInfoList, int infoCount continue; // Don't transmit other players' flashlights - CBarnLight *pFlashLight = pController->IsConnected() ? g_playerManager->GetPlayer(j)->GetFlashLight() : nullptr; + CBarnLight* pFlashLight = pController->IsConnected() ? g_playerManager->GetPlayer(j)->GetFlashLight() : nullptr; if (!g_bFlashLightTransmitOthers && pFlashLight) - { pInfo->m_pTransmitEntity->Clear(pFlashLight->entindex()); - } // Always transmit other players if spectating if (!g_bEnableHide || pSelfController->GetPawnState() == STATE_OBSERVER_MODE) continue; // Get the actual pawn as the player could be currently spectating - CCSPlayerPawn *pPawn = pController->GetPlayerPawn(); + CCSPlayerPawn* pPawn = pController->GetPlayerPawn(); if (!pPawn) continue; @@ -885,13 +876,13 @@ void CS2Fixes::Hook_CheckTransmit(CCheckTransmitInfo **ppInfoList, int infoCount // Hide players marked as hidden or ANY dead player, it seems that a ragdoll of a previously hidden player can crash? // TODO: Revert this if/when valve fixes the issue? // Also do not hide leaders to other players - ZEPlayer *pOtherZEPlayer = g_playerManager->GetPlayer(j); + ZEPlayer* pOtherZEPlayer = g_playerManager->GetPlayer(j); if ((pSelfZEPlayer->ShouldBlockTransmit(j) && (pOtherZEPlayer && !pOtherZEPlayer->IsLeader())) || !pPawn->IsAlive()) pInfo->m_pTransmitEntity->Clear(pPawn->entindex()); } // Don't transmit glow model to it's owner - CBaseModelEntity *pGlowModel = pSelfZEPlayer->GetGlowModel(); + CBaseModelEntity* pGlowModel = pSelfZEPlayer->GetGlowModel(); if (pGlowModel) pInfo->m_pTransmitEntity->Clear(pGlowModel->entindex()); @@ -929,9 +920,9 @@ bool g_bDropMapWeapons = false; FAKE_BOOL_CVAR(cs2f_drop_map_weapons, "Whether to force drop map-spawned weapons on death", g_bDropMapWeapons, false, false) -bool CS2Fixes::Hook_OnTakeDamage_Alive(CTakeDamageInfoContainer *pInfoContainer) +bool CS2Fixes::Hook_OnTakeDamage_Alive(CTakeDamageInfoContainer* pInfoContainer) { - CCSPlayerPawn *pPawn = META_IFACEPTR(CCSPlayerPawn); + CCSPlayerPawn* pPawn = META_IFACEPTR(CCSPlayerPawn); if (g_bEnableZR && ZR_Hook_OnTakeDamage_Alive(pInfoContainer->pInfo, pPawn)) RETURN_META_VALUE(MRES_SUPERCEDE, false); @@ -1008,21 +999,21 @@ void CS2Fixes::Hook_PhysicsTouchShuffle(CUtlVector* pList, bool u pList->Purge(); - for (const auto &link : touchingLinks) + for (const auto& link : touchingLinks) pList->AddToTail(link); - for (const auto &link : unTouchLinks) + for (const auto& link : unTouchLinks) pList->AddToTail(link); } void CS2Fixes::Hook_CheckMovingGround(double frametime) { - CCSPlayer_MovementServices *pMove = META_IFACEPTR(CCSPlayer_MovementServices); - CCSPlayerPawn *pPawn = pMove->GetPawn(); + CCSPlayer_MovementServices* pMove = META_IFACEPTR(CCSPlayer_MovementServices); + CCSPlayerPawn* pPawn = pMove->GetPawn(); if (!pPawn) RETURN_META(MRES_IGNORED); - CCSPlayerController *pController = pPawn->GetOriginalController(); + CCSPlayerController* pController = pPawn->GetOriginalController(); if (!pController) RETURN_META(MRES_IGNORED); @@ -1041,19 +1032,19 @@ void CS2Fixes::Hook_CheckMovingGround(double frametime) RETURN_META(MRES_IGNORED); } -int CS2Fixes::Hook_LoadEventsFromFile(const char *filename, bool bSearchAll) +int CS2Fixes::Hook_LoadEventsFromFile(const char* filename, bool bSearchAll) { ExecuteOnce(g_gameEventManager = META_IFACEPTR(IGameEventManager2)); RETURN_META_VALUE(MRES_IGNORED, 0); } -void CS2Fixes::OnLevelInit( char const *pMapName, - char const *pMapEntities, - char const *pOldLevel, - char const *pLandmarkName, - bool loadGame, - bool background ) +void CS2Fixes::OnLevelInit(char const* pMapName, + char const* pMapEntities, + char const* pOldLevel, + char const* pLandmarkName, + bool loadGame, + bool background) { Message("OnLevelInit(%s)\n", pMapName); g_iRoundNum = 0; @@ -1079,56 +1070,56 @@ void CS2Fixes::OnLevelShutdown() Message("OnLevelShutdown()\n"); } -bool CS2Fixes::Pause(char *error, size_t maxlen) +bool CS2Fixes::Pause(char* error, size_t maxlen) { return true; } -bool CS2Fixes::Unpause(char *error, size_t maxlen) +bool CS2Fixes::Unpause(char* error, size_t maxlen) { return true; } -const char *CS2Fixes::GetLicense() +const char* CS2Fixes::GetLicense() { return "GPL v3 License"; } -const char *CS2Fixes::GetVersion() +const char* CS2Fixes::GetVersion() { #ifndef CS2FIXES_VERSION -#define CS2FIXES_VERSION "1.7-dev" + #define CS2FIXES_VERSION "1.7-dev" #endif return CS2FIXES_VERSION; // defined by the build script } -const char *CS2Fixes::GetDate() +const char* CS2Fixes::GetDate() { return __DATE__; } -const char *CS2Fixes::GetLogTag() +const char* CS2Fixes::GetLogTag() { return "CS2Fixes"; } -const char *CS2Fixes::GetAuthor() +const char* CS2Fixes::GetAuthor() { return "xen, Poggu, and the Source2ZE community"; } -const char *CS2Fixes::GetDescription() +const char* CS2Fixes::GetDescription() { return "A bunch of experiments thrown together into one big mess of a plugin."; } -const char *CS2Fixes::GetName() +const char* CS2Fixes::GetName() { return "CS2Fixes"; } -const char *CS2Fixes::GetURL() +const char* CS2Fixes::GetURL() { return "https://github.com/Source2ZE/CS2Fixes"; } \ No newline at end of file diff --git a/src/cs2fixes.h b/src/cs2fixes.h index c51ac92a..77acd441 100644 --- a/src/cs2fixes.h +++ b/src/cs2fixes.h @@ -19,12 +19,12 @@ #pragma once -#include #include "igameevents.h" -#include -#include #include "networksystem/inetworkserializer.h" +#include +#include #include +#include struct CTakeDamageInfoContainer; class CCSPlayer_MovementServices; @@ -34,40 +34,41 @@ struct TouchLinked_t; class CS2Fixes : public ISmmPlugin, public IMetamodListener { public: - bool Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late); + bool Load(PluginId id, ISmmAPI* ismm, char* error, size_t maxlen, bool late); void Hook_PostEvent(CSplitScreenSlot nSlot, bool bLocalOnly, int nClientCount, const uint64* clients, - INetworkMessageInternal* pEvent, const CNetMessage* pData, unsigned long nSize, NetChannelBufType_t bufType); - bool Unload(char *error, size_t maxlen); - bool Pause(char *error, size_t maxlen); - bool Unpause(char *error, size_t maxlen); + INetworkMessageInternal* pEvent, const CNetMessage* pData, unsigned long nSize, NetChannelBufType_t bufType); + bool Unload(char* error, size_t maxlen); + bool Pause(char* error, size_t maxlen); + bool Unpause(char* error, size_t maxlen); void AllPluginsLoaded(); -public: //hooks + +public: // hooks void Hook_GameServerSteamAPIActivated(); void Hook_GameServerSteamAPIDeactivated(); - void OnLevelInit( char const *pMapName, - char const *pMapEntities, - char const *pOldLevel, - char const *pLandmarkName, - bool loadGame, - bool background ); + void OnLevelInit(char const* pMapName, + char const* pMapEntities, + char const* pOldLevel, + char const* pLandmarkName, + bool loadGame, + bool background); void OnLevelShutdown(); void Hook_GameFramePost(bool simulating, bool bFirstTick, bool bLastTick); - void Hook_ClientActive( CPlayerSlot slot, bool bLoadGame, const char *pszName, uint64 xuid ); - void Hook_ClientDisconnect( CPlayerSlot slot, ENetworkDisconnectionReason reason, const char *pszName, uint64 xuid, const char *pszNetworkID ); - void Hook_ClientPutInServer( CPlayerSlot slot, char const *pszName, int type, uint64 xuid ); - void Hook_ClientSettingsChanged( CPlayerSlot slot ); - void Hook_OnClientConnected( CPlayerSlot slot, const char *pszName, uint64 xuid, const char *pszNetworkID, const char *pszAddress, bool bFakePlayer ); - bool Hook_ClientConnect( CPlayerSlot slot, const char *pszName, uint64 xuid, const char *pszNetworkID, bool unk1, CBufferString *pRejectReason ); - void Hook_ClientCommand( CPlayerSlot nSlot, const CCommand &_cmd ); - void Hook_CheckTransmit(CCheckTransmitInfo **ppInfoList, int infoCount, CBitVec<16384> &unionTransmitEdicts, - const Entity2Networkable_t **pNetworkables, const uint16 *pEntityIndicies, int nEntities, bool bEnablePVSBits); + void Hook_ClientActive(CPlayerSlot slot, bool bLoadGame, const char* pszName, uint64 xuid); + void Hook_ClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID); + void Hook_ClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid); + void Hook_ClientSettingsChanged(CPlayerSlot slot); + void Hook_OnClientConnected(CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, const char* pszAddress, bool bFakePlayer); + bool Hook_ClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason); + void Hook_ClientCommand(CPlayerSlot nSlot, const CCommand& _cmd); + void Hook_CheckTransmit(CCheckTransmitInfo** ppInfoList, int infoCount, CBitVec<16384>& unionTransmitEdicts, + const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntities, bool bEnablePVSBits); void Hook_DispatchConCommand(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args); void Hook_CGamePlayerEquipUse(class InputData_t*); void Hook_StartupServer(const GameSessionConfiguration_t& config, ISource2WorldSession*, const char*); void Hook_ApplyGameSettings(KeyValues* pKV); void Hook_CreateWorkshopMapGroup(const char* name, const CUtlStringList& mapList); void Hook_GoToIntermission(bool bAbortedMatch); - bool Hook_OnTakeDamage_Alive(CTakeDamageInfoContainer *pInfoContainer); + bool Hook_OnTakeDamage_Alive(CTakeDamageInfoContainer* pInfoContainer); void Hook_PhysicsTouchShuffle(CUtlVector* pList, bool unknown); #ifdef PLATFORM_WINDOWS Vector* Hook_GetEyePosition(Vector*); @@ -77,17 +78,17 @@ class CS2Fixes : public ISmmPlugin, public IMetamodListener QAngle Hook_GetEyeAngles(); #endif void Hook_CheckMovingGround(double frametime); - int Hook_LoadEventsFromFile(const char *filename, bool bSearchAll); + int Hook_LoadEventsFromFile(const char* filename, bool bSearchAll); public: - const char *GetAuthor(); - const char *GetName(); - const char *GetDescription(); - const char *GetURL(); - const char *GetLicense(); - const char *GetVersion(); - const char *GetDate(); - const char *GetLogTag(); + const char* GetAuthor(); + const char* GetName(); + const char* GetDescription(); + const char* GetURL(); + const char* GetLicense(); + const char* GetVersion(); + const char* GetDate(); + const char* GetLogTag(); }; extern CS2Fixes g_CS2Fixes; diff --git a/src/ctimer.cpp b/src/ctimer.cpp index 2fc938e8..47b7bd9d 100644 --- a/src/ctimer.cpp +++ b/src/ctimer.cpp @@ -28,15 +28,15 @@ void RemoveTimers() void RemoveMapTimers() { - for (int i = g_timers.Tail(); i != g_timers.InvalidIndex();) - { - int prevIndex = i; - i = g_timers.Previous(i); + for (int i = g_timers.Tail(); i != g_timers.InvalidIndex();) + { + int prevIndex = i; + i = g_timers.Previous(i); - if(g_timers[prevIndex]->m_bPreserveMapChange) - continue; + if (g_timers[prevIndex]->m_bPreserveMapChange) + continue; - delete g_timers[prevIndex]; - g_timers.Remove(prevIndex); - } + delete g_timers[prevIndex]; + g_timers.Remove(prevIndex); + } } \ No newline at end of file diff --git a/src/ctimer.h b/src/ctimer.h index 2abc13ab..f0140bc3 100644 --- a/src/ctimer.h +++ b/src/ctimer.h @@ -18,26 +18,27 @@ */ #pragma once -#include #include "utllinkedlist.h" +#include extern int g_iRoundNum; -class CTimerBase { +class CTimerBase +{ public: - CTimerBase(float flInitialInterval, bool bPreserveMapChange, bool bPreserveRoundChange) : - m_flInterval(flInitialInterval), m_bPreserveMapChange(bPreserveMapChange), m_bPreserveRoundChange(bPreserveRoundChange) - { - m_iRoundNum = g_iRoundNum; - } + CTimerBase(float flInitialInterval, bool bPreserveMapChange, bool bPreserveRoundChange) : + m_flInterval(flInitialInterval), m_bPreserveMapChange(bPreserveMapChange), m_bPreserveRoundChange(bPreserveRoundChange) + { + m_iRoundNum = g_iRoundNum; + } - virtual bool Execute() = 0; + virtual bool Execute() = 0; - float m_flInterval; - float m_flLastExecute = -1; - bool m_bPreserveMapChange; - bool m_bPreserveRoundChange; - int m_iRoundNum; + float m_flInterval; + float m_flLastExecute = -1; + bool m_bPreserveMapChange; + bool m_bPreserveRoundChange; + int m_iRoundNum; }; extern CUtlLinkedList g_timers; @@ -47,22 +48,21 @@ extern CUtlLinkedList g_timers; class CTimer : public CTimerBase { public: - CTimer(float flInitialInterval, bool bPreserveMapChange, bool bPreserveRoundChange, std::function func) : + CTimer(float flInitialInterval, bool bPreserveMapChange, bool bPreserveRoundChange, std::function func) : CTimerBase(flInitialInterval, bPreserveMapChange, bPreserveRoundChange), m_func(func) - { - g_timers.AddToTail(this); - }; + { + g_timers.AddToTail(this); + }; - inline bool Execute() override - { - m_flInterval = m_func(); + inline bool Execute() override + { + m_flInterval = m_func(); - return m_flInterval >= 0; + return m_flInterval >= 0; } - std::function m_func; + std::function m_func; }; - void RemoveTimers(); void RemoveMapTimers(); \ No newline at end of file diff --git a/src/customio.cpp b/src/customio.cpp index 7b0a6d2d..2d06d8df 100644 --- a/src/customio.cpp +++ b/src/customio.cpp @@ -35,369 +35,369 @@ extern CGlobalVars* gpGlobals; struct AddOutputKey_t { - AddOutputKey_t(const char* pName, int32_t parts) : - m_pName(pName) - { - m_nLength = strlen(pName); - m_nParts = parts; - } - - AddOutputKey_t(const AddOutputKey_t& other) : - m_pName(other.m_pName), - m_nLength(other.m_nLength), - m_nParts(other.m_nParts) {} - - const char* m_pName; - size_t m_nLength; - int32_t m_nParts; + AddOutputKey_t(const char* pName, int32_t parts) : + m_pName(pName) + { + m_nLength = strlen(pName); + m_nParts = parts; + } + + AddOutputKey_t(const AddOutputKey_t& other) : + m_pName(other.m_pName), + m_nLength(other.m_nLength), + m_nParts(other.m_nParts) {} + + const char* m_pName; + size_t m_nLength; + int32_t m_nParts; }; -using AddOutputHandler_t = void (*)(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs); +using AddOutputHandler_t = void (*)(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs); struct AddOutputInfo_t { - AddOutputInfo_t(const AddOutputKey_t& key, const AddOutputHandler_t& handler) : - m_Key(key), m_Handler(handler) {} + AddOutputInfo_t(const AddOutputKey_t& key, const AddOutputHandler_t& handler) : + m_Key(key), m_Handler(handler) {} - AddOutputKey_t m_Key; - AddOutputHandler_t m_Handler; + AddOutputKey_t m_Key; + AddOutputHandler_t m_Handler; }; static void AddOutputCustom_Targetname(CBaseEntity* pInstance, CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) + CEntityInstance* pCaller, + const std::vector& vecArgs) { - pInstance->SetName(vecArgs[1].c_str()); + pInstance->SetName(vecArgs[1].c_str()); #ifdef _DEBUG - Message("SetName %s to %d", vecArgs[1].c_str(), pInstance->GetHandle().GetEntryIndex()); + Message("SetName %s to %d", vecArgs[1].c_str(), pInstance->GetHandle().GetEntryIndex()); #endif } -static void AddOutputCustom_Origin(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Origin(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - Vector origin(clamp(Q_atof(vecArgs[1].c_str()), -16384.f, 16384.f), - clamp(Q_atof(vecArgs[2].c_str()), -16384.f, 16384.f), - clamp(Q_atof(vecArgs[3].c_str()), -16384.f, 16384.f)); - pInstance->Teleport(&origin, nullptr, nullptr); + Vector origin(clamp(Q_atof(vecArgs[1].c_str()), -16384.f, 16384.f), + clamp(Q_atof(vecArgs[2].c_str()), -16384.f, 16384.f), + clamp(Q_atof(vecArgs[3].c_str()), -16384.f, 16384.f)); + pInstance->Teleport(&origin, nullptr, nullptr); #ifdef _DEBUG - Message("SetOrigin %f %f %f for %s", origin.x, origin.y, origin.z, pInstance->GetName()); + Message("SetOrigin %f %f %f for %s", origin.x, origin.y, origin.z, pInstance->GetName()); #endif } -static void AddOutputCustom_Angles(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Angles(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - QAngle angles(clamp(Q_atof(vecArgs[1].c_str()), -360.f, 360.f), - clamp(Q_atof(vecArgs[2].c_str()), -360.f, 360.f), - clamp(Q_atof(vecArgs[3].c_str()), -360.f, 360.f)); - pInstance->Teleport(nullptr, &angles, nullptr); + QAngle angles(clamp(Q_atof(vecArgs[1].c_str()), -360.f, 360.f), + clamp(Q_atof(vecArgs[2].c_str()), -360.f, 360.f), + clamp(Q_atof(vecArgs[3].c_str()), -360.f, 360.f)); + pInstance->Teleport(nullptr, &angles, nullptr); #ifdef _DEBUG - Message("SetAngles %f %f %f for %s", angles.x, angles.y, angles.z, pInstance->GetName()); + Message("SetAngles %f %f %f for %s", angles.x, angles.y, angles.z, pInstance->GetName()); #endif } -static void AddOutputCustom_MaxHealth(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_MaxHealth(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - pInstance->m_iMaxHealth(clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX)); + pInstance->m_iMaxHealth(clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX)); #ifdef _DEBUG - const int m_iMaxHealth = pInstance->m_iMaxHealth; - Message("SetMaxHealth %d for %s", m_iMaxHealth, pInstance->GetName()); + const int m_iMaxHealth = pInstance->m_iMaxHealth; + Message("SetMaxHealth %d for %s", m_iMaxHealth, pInstance->GetName()); #endif } -static void AddOutputCustom_Health(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Health(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - pInstance->m_iHealth(clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX)); + pInstance->m_iHealth(clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX)); #ifdef _DEBUG - const int m_iHealth = pInstance->m_iHealth; - Message("SetHealth %d for %s", m_iHealth, pInstance->GetName()); + const int m_iHealth = pInstance->m_iHealth; + Message("SetHealth %d for %s", m_iHealth, pInstance->GetName()); #endif } -static void AddOutputCustom_MoveType(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_MoveType(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - static Vector stopVelocity(0, 0, 0); - const auto value = clamp(Q_atoi(vecArgs[1].c_str()), MOVETYPE_NONE, MOVETYPE_LAST); - const auto type = static_cast(value); + static Vector stopVelocity(0, 0, 0); + const auto value = clamp(Q_atoi(vecArgs[1].c_str()), MOVETYPE_NONE, MOVETYPE_LAST); + const auto type = static_cast(value); - pInstance->SetMoveType(type); + pInstance->SetMoveType(type); #ifdef _DEBUG - Message("SetMoveType %d for %s", type, pInstance->GetName()); + Message("SetMoveType %d for %s", type, pInstance->GetName()); #endif } -static void AddOutputCustom_EntityTemplate(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_EntityTemplate(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - if (strcmp(pInstance->GetClassname(), "env_entity_maker") == 0) - { - const auto pEntity = reinterpret_cast(pInstance); - const auto pValue = g_pEntitySystem->AllocPooledString(vecArgs[1].c_str()); - pEntity->m_iszTemplate(pValue); + if (strcmp(pInstance->GetClassname(), "env_entity_maker") == 0) + { + const auto pEntity = reinterpret_cast(pInstance); + const auto pValue = g_pEntitySystem->AllocPooledString(vecArgs[1].c_str()); + pEntity->m_iszTemplate(pValue); #ifdef _DEBUG - Message("Set EntityTemplate to %s for %s\n", pValue.String(), pInstance->GetName()); + Message("Set EntityTemplate to %s for %s\n", pValue.String(), pInstance->GetName()); #endif - } - else - Message("Only env_entity_maker is supported\n"); + } + else + Message("Only env_entity_maker is supported\n"); } -static void AddOutputCustom_BaseVelocity(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_BaseVelocity(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - const Vector velocity(clamp(Q_atof(vecArgs[1].c_str()), -4096.f, 4096.f), - clamp(Q_atof(vecArgs[2].c_str()), -4096.f, 4096.f), - clamp(Q_atof(vecArgs[3].c_str()), -4096.f, 4096.f)); + const Vector velocity(clamp(Q_atof(vecArgs[1].c_str()), -4096.f, 4096.f), + clamp(Q_atof(vecArgs[2].c_str()), -4096.f, 4096.f), + clamp(Q_atof(vecArgs[3].c_str()), -4096.f, 4096.f)); - pInstance->SetBaseVelocity(velocity); + pInstance->SetBaseVelocity(velocity); #ifdef _DEBUG - Message("SetOrigin %f %f %f for %s", velocity.x, velocity.y, velocity.z, pInstance->GetName()); + Message("SetOrigin %f %f %f for %s", velocity.x, velocity.y, velocity.z, pInstance->GetName()); #endif } -static void AddOutputCustom_AbsVelocity(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_AbsVelocity(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - Vector velocity(clamp(Q_atof(vecArgs[1].c_str()), -4096.f, 4096.f), - clamp(Q_atof(vecArgs[2].c_str()), -4096.f, 4096.f), - clamp(Q_atof(vecArgs[3].c_str()), -4096.f, 4096.f)); + Vector velocity(clamp(Q_atof(vecArgs[1].c_str()), -4096.f, 4096.f), + clamp(Q_atof(vecArgs[2].c_str()), -4096.f, 4096.f), + clamp(Q_atof(vecArgs[3].c_str()), -4096.f, 4096.f)); - pInstance->Teleport(nullptr, nullptr, &velocity); + pInstance->Teleport(nullptr, nullptr, &velocity); #ifdef _DEBUG - Message("SetOrigin %f %f %f for %s", velocity.x, velocity.y, velocity.z, pInstance->GetName()); + Message("SetOrigin %f %f %f for %s", velocity.x, velocity.y, velocity.z, pInstance->GetName()); #endif } -static void AddOutputCustom_Target(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Target(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - if (const auto pTarget = UTIL_FindEntityByName(nullptr, vecArgs[1].c_str())) - { - const auto pEntity = pInstance; - pEntity->m_target(pTarget->m_pEntity->m_name); + if (const auto pTarget = UTIL_FindEntityByName(nullptr, vecArgs[1].c_str())) + { + const auto pEntity = pInstance; + pEntity->m_target(pTarget->m_pEntity->m_name); #ifdef _DEBUG - Message("Set Target to %s for %s\n", pTarget->m_pEntity->m_name.String(), pEntity->m_pEntity->m_name.String()); + Message("Set Target to %s for %s\n", pTarget->m_pEntity->m_name.String(), pEntity->m_pEntity->m_name.String()); #endif - } + } } -static void AddOutputCustom_FilterName(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_FilterName(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - if (V_strncasecmp(pInstance->GetClassname(), "trigger_", 8) == 0) - { - if (const auto pTarget = UTIL_FindEntityByName(nullptr, vecArgs[1].c_str())) - { - if (V_strncasecmp(pTarget->GetClassname(), "filter_", 7) == 0) - { - const auto pTrigger = reinterpret_cast(pInstance); - pTrigger->m_iFilterName(pTarget->GetName()); - pTrigger->m_hFilter(pTarget->GetRefEHandle()); + if (V_strncasecmp(pInstance->GetClassname(), "trigger_", 8) == 0) + { + if (const auto pTarget = UTIL_FindEntityByName(nullptr, vecArgs[1].c_str())) + { + if (V_strncasecmp(pTarget->GetClassname(), "filter_", 7) == 0) + { + const auto pTrigger = reinterpret_cast(pInstance); + pTrigger->m_iFilterName(pTarget->GetName()); + pTrigger->m_hFilter(pTarget->GetRefEHandle()); #ifdef _DEBUG - Message("Set FilterName to %s for %s\n", pTarget->GetName(), - pTrigger->GetName()); + Message("Set FilterName to %s for %s\n", pTarget->GetName(), + pTrigger->GetName()); #endif - } - } - } + } + } + } } -static void AddOutputCustom_Force(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Force(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - const auto value = Q_atof(vecArgs[1].c_str()); - const auto pEntity = reinterpret_cast(pInstance); - if (V_strcasecmp(pEntity->GetClassname(), "phys_thruster") == 0) - { - pEntity->m_force(value); + const auto value = Q_atof(vecArgs[1].c_str()); + const auto pEntity = reinterpret_cast(pInstance); + if (V_strcasecmp(pEntity->GetClassname(), "phys_thruster") == 0) + { + pEntity->m_force(value); #ifdef _DEBUG - Message("Set force to %f for %s\n", value, pEntity->GetName()); + Message("Set force to %f for %s\n", value, pEntity->GetName()); #endif - } + } } -static void AddOutputCustom_Gravity(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Gravity(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - const auto value = Q_atof(vecArgs[1].c_str()); + const auto value = Q_atof(vecArgs[1].c_str()); - pInstance->m_flGravityScale = value; + pInstance->m_flGravityScale = value; #ifdef _DEBUG - Message("Set gravity to %f for %s\n", value, pInstance->GetName()); + Message("Set gravity to %f for %s\n", value, pInstance->GetName()); #endif } -static void AddOutputCustom_Timescale(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Timescale(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - const auto value = Q_atof(vecArgs[1].c_str()); + const auto value = Q_atof(vecArgs[1].c_str()); - pInstance->m_flTimeScale = value; + pInstance->m_flTimeScale = value; #ifdef _DEBUG - Message("Set timescale to %f for %s\n", value, pInstance->GetName()); + Message("Set timescale to %f for %s\n", value, pInstance->GetName()); #endif } -static void AddOutputCustom_Friction(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Friction(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - const auto value = Q_atof(vecArgs[1].c_str()); + const auto value = Q_atof(vecArgs[1].c_str()); - pInstance->m_flFriction = value; + pInstance->m_flFriction = value; #ifdef _DEBUG - Message("Set friction to %f for %s\n", value, pInstance->GetName()); + Message("Set friction to %f for %s\n", value, pInstance->GetName()); #endif } -static void AddOutputCustom_Speed(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_Speed(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - if (!pInstance->IsPawn()) - return; + if (!pInstance->IsPawn()) + return; - const auto pPawn = reinterpret_cast(pInstance); - const auto pController = pPawn->GetOriginalController(); + const auto pPawn = reinterpret_cast(pInstance); + const auto pController = pPawn->GetOriginalController(); - if (!pController || !pController->IsConnected()) - return; + if (!pController || !pController->IsConnected()) + return; - const auto value = Q_atof(vecArgs[1].c_str()); + const auto value = Q_atof(vecArgs[1].c_str()); - pController->GetZEPlayer()->SetSpeedMod(value); + pController->GetZEPlayer()->SetSpeedMod(value); #ifdef _DEBUG - Message("Set speed to %f for %s\n", value, pInstance->GetName()); + Message("Set speed to %f for %s\n", value, pInstance->GetName()); #endif } -static void AddOutputCustom_RunSpeed(CBaseEntity* pInstance, - CEntityInstance* pActivator, - CEntityInstance* pCaller, - const std::vector& vecArgs) +static void AddOutputCustom_RunSpeed(CBaseEntity* pInstance, + CEntityInstance* pActivator, + CEntityInstance* pCaller, + const std::vector& vecArgs) { - if (!pInstance->IsPawn()) - return; + if (!pInstance->IsPawn()) + return; - const auto pPawn = reinterpret_cast(pInstance); + const auto pPawn = reinterpret_cast(pInstance); - const auto value = Q_atof(vecArgs[1].c_str()); + const auto value = Q_atof(vecArgs[1].c_str()); - pPawn->m_flVelocityModifier = value; + pPawn->m_flVelocityModifier = value; #ifdef _DEBUG - Message("Set runspeed to %f for %s\n", value, pInstance->GetName()); + Message("Set runspeed to %f for %s\n", value, pInstance->GetName()); #endif } const std::vector s_AddOutputHandlers = { - {{"targetname", 2}, AddOutputCustom_Targetname }, - {{"origin", 4}, AddOutputCustom_Origin }, - {{"angles", 4}, AddOutputCustom_Angles }, - {{"max_health", 2}, AddOutputCustom_MaxHealth }, - {{"health", 2}, AddOutputCustom_Health }, - {{"movetype", 2}, AddOutputCustom_MoveType }, - {{"EntityTemplate", 2}, AddOutputCustom_EntityTemplate}, - {{"basevelocity", 4}, AddOutputCustom_BaseVelocity }, - {{"absvelocity", 4}, AddOutputCustom_AbsVelocity }, - {{"target", 2}, AddOutputCustom_Target }, - {{"filtername", 2}, AddOutputCustom_FilterName }, - {{"force", 2}, AddOutputCustom_Force }, - {{"gravity", 2}, AddOutputCustom_Gravity }, - {{"timescale", 2}, AddOutputCustom_Timescale }, - {{"friction", 2}, AddOutputCustom_Friction }, - {{"speed", 2}, AddOutputCustom_Speed }, - {{"runspeed", 2}, AddOutputCustom_RunSpeed }, + {{"targetname", 2}, AddOutputCustom_Targetname }, + {{"origin", 4}, AddOutputCustom_Origin }, + {{"angles", 4}, AddOutputCustom_Angles }, + {{"max_health", 2}, AddOutputCustom_MaxHealth }, + {{"health", 2}, AddOutputCustom_Health }, + {{"movetype", 2}, AddOutputCustom_MoveType }, + {{"EntityTemplate", 2}, AddOutputCustom_EntityTemplate}, + {{"basevelocity", 4}, AddOutputCustom_BaseVelocity }, + {{"absvelocity", 4}, AddOutputCustom_AbsVelocity }, + {{"target", 2}, AddOutputCustom_Target }, + {{"filtername", 2}, AddOutputCustom_FilterName }, + {{"force", 2}, AddOutputCustom_Force }, + {{"gravity", 2}, AddOutputCustom_Gravity }, + {{"timescale", 2}, AddOutputCustom_Timescale }, + {{"friction", 2}, AddOutputCustom_Friction }, + {{"speed", 2}, AddOutputCustom_Speed }, + {{"runspeed", 2}, AddOutputCustom_RunSpeed }, }; inline std::vector StringSplit(const char* str, const char* delimiter) { - std::vector result; - std::string_view strV(str); - size_t pos; - - while ((pos = strV.find(delimiter)) != std::string_view::npos) - { - result.emplace_back(strV.substr(0, pos)); - strV.remove_prefix(pos + std::string_view(delimiter).size()); - } - - result.emplace_back(strV); - return result; + std::vector result; + std::string_view strV(str); + size_t pos; + + while ((pos = strV.find(delimiter)) != std::string_view::npos) + { + result.emplace_back(strV.substr(0, pos)); + strV.remove_prefix(pos + std::string_view(delimiter).size()); + } + + result.emplace_back(strV); + return result; } bool CustomIO_HandleInput(CEntityInstance* pInstance, - const char* param, - CEntityInstance* pActivator, - CEntityInstance* pCaller) + const char* param, + CEntityInstance* pActivator, + CEntityInstance* pCaller) { - for (auto& [input, handler] : s_AddOutputHandlers) - { - if (V_strncasecmp(param, input.m_pName, input.m_nLength) == 0) - { - if (const auto split = StringSplit(param, " "); - split.size() == input.m_nParts) - { - handler(reinterpret_cast(pInstance), pActivator, pCaller, split); - return true; - } - - break; - } - } - - return false; + for (auto& [input, handler] : s_AddOutputHandlers) + { + if (V_strncasecmp(param, input.m_pName, input.m_nLength) == 0) + { + if (const auto split = StringSplit(param, " "); + split.size() == input.m_nParts) + { + handler(reinterpret_cast(pInstance), pActivator, pCaller, split); + return true; + } + + break; + } + } + + return false; } std::string g_sBurnParticle = "particles/burning_fx/burning_character_b.vpcf"; @@ -414,75 +414,75 @@ FAKE_FLOAT_CVAR(cs2f_burn_interval, "The interval between burn damage ticks", g_ bool IgnitePawn(CCSPlayerPawn* pPawn, float flDuration, CBaseEntity* pInflictor, CBaseEntity* pAttacker, CBaseEntity* pAbility, DamageTypes_t nDamageType) { - auto pParticleEnt = reinterpret_cast(pPawn->m_hEffectEntity().Get()); + auto pParticleEnt = reinterpret_cast(pPawn->m_hEffectEntity().Get()); - // This guy is already burning, don't ignite again - if (pParticleEnt) - { - // Override the end time instead of just adding to it so players who get a ton of ignite inputs don't burn forever - pParticleEnt->m_flDissolveStartTime = gpGlobals->curtime + flDuration; - return true; - } + // This guy is already burning, don't ignite again + if (pParticleEnt) + { + // Override the end time instead of just adding to it so players who get a ton of ignite inputs don't burn forever + pParticleEnt->m_flDissolveStartTime = gpGlobals->curtime + flDuration; + return true; + } - const auto vecOrigin = pPawn->GetAbsOrigin(); + const auto vecOrigin = pPawn->GetAbsOrigin(); - pParticleEnt = CreateEntityByName("info_particle_system"); + pParticleEnt = CreateEntityByName("info_particle_system"); - pParticleEnt->m_bStartActive(true); - pParticleEnt->m_iszEffectName(g_sBurnParticle.c_str()); - pParticleEnt->m_hControlPointEnts[0] = pPawn; - pParticleEnt->m_flDissolveStartTime = gpGlobals->curtime + flDuration; // Store the end time in the particle itself so we can increment if needed - pParticleEnt->Teleport(&vecOrigin, nullptr, nullptr); + pParticleEnt->m_bStartActive(true); + pParticleEnt->m_iszEffectName(g_sBurnParticle.c_str()); + pParticleEnt->m_hControlPointEnts[0] = pPawn; + pParticleEnt->m_flDissolveStartTime = gpGlobals->curtime + flDuration; // Store the end time in the particle itself so we can increment if needed + pParticleEnt->Teleport(&vecOrigin, nullptr, nullptr); - pParticleEnt->DispatchSpawn(); + pParticleEnt->DispatchSpawn(); - pParticleEnt->SetParent(pPawn); + pParticleEnt->SetParent(pPawn); - pPawn->m_hEffectEntity = pParticleEnt; + pPawn->m_hEffectEntity = pParticleEnt; - CHandle hPawn(pPawn); - CHandle hInflictor(pInflictor); - CHandle hAttacker(pAttacker); - CHandle hAbility(pAbility); + CHandle hPawn(pPawn); + CHandle hInflictor(pInflictor); + CHandle hAttacker(pAttacker); + CHandle hAbility(pAbility); - new CTimer(0.f, false, false, [hPawn, hInflictor, hAttacker, hAbility, nDamageType]() { - CCSPlayerPawn* pPawn = hPawn.Get(); + new CTimer(0.f, false, false, [hPawn, hInflictor, hAttacker, hAbility, nDamageType]() { + CCSPlayerPawn* pPawn = hPawn.Get(); - if (!pPawn) - return -1.f; + if (!pPawn) + return -1.f; - const auto pParticleEnt = reinterpret_cast(pPawn->m_hEffectEntity().Get()); + const auto pParticleEnt = reinterpret_cast(pPawn->m_hEffectEntity().Get()); - if (!pParticleEnt) - return -1.f; + if (!pParticleEnt) + return -1.f; - if (V_strncmp(pParticleEnt->GetClassname(), "info_part", 9) != 0) - { - // This should never happen but just in case - Panic("Found unexpected entity %s while burning a pawn!\n", pParticleEnt->GetClassname()); - return -1.f; - } + if (V_strncmp(pParticleEnt->GetClassname(), "info_part", 9) != 0) + { + // This should never happen but just in case + Panic("Found unexpected entity %s while burning a pawn!\n", pParticleEnt->GetClassname()); + return -1.f; + } - if (pParticleEnt->m_flDissolveStartTime() <= gpGlobals->curtime || !pPawn->IsAlive()) - { - pParticleEnt->AcceptInput("Stop"); - UTIL_AddEntityIOEvent(pParticleEnt, "Kill"); // Kill on the next frame + if (pParticleEnt->m_flDissolveStartTime() <= gpGlobals->curtime || !pPawn->IsAlive()) + { + pParticleEnt->AcceptInput("Stop"); + UTIL_AddEntityIOEvent(pParticleEnt, "Kill"); // Kill on the next frame - return -1.f; - } + return -1.f; + } - CTakeDamageInfo info(hInflictor, hAttacker, hAbility, g_flBurnDamage, nDamageType); + CTakeDamageInfo info(hInflictor, hAttacker, hAbility, g_flBurnDamage, nDamageType); - // Damage doesn't apply if the inflictor is null - if (!hInflictor.Get()) - info.m_hInflictor.Set(hAttacker); + // Damage doesn't apply if the inflictor is null + if (!hInflictor.Get()) + info.m_hInflictor.Set(hAttacker); - pPawn->TakeDamage(info); + pPawn->TakeDamage(info); - pPawn->m_flVelocityModifier = g_flBurnSlowdown; + pPawn->m_flVelocityModifier = g_flBurnSlowdown; - return g_flBurnInterval; - }); + return g_flBurnInterval; + }); - return true; + return true; } diff --git a/src/customio.h b/src/customio.h index 7ea53568..16cdba63 100644 --- a/src/customio.h +++ b/src/customio.h @@ -26,13 +26,13 @@ class CCSPlayerPawn; enum DamageTypes_t : unsigned int; bool CustomIO_HandleInput(CEntityInstance* pEntityInstance, - const char* pParams, - CEntityInstance* pActivator, - CEntityInstance* pCaller); + const char* pParams, + CEntityInstance* pActivator, + CEntityInstance* pCaller); -bool IgnitePawn(CCSPlayerPawn *pEntity, - float flDuration, - CBaseEntity *pInflictor = nullptr, - CBaseEntity *pAttacker = nullptr, - CBaseEntity *pAbility = nullptr, - DamageTypes_t nDamageType = DamageTypes_t(8)); // DMG_BURN +bool IgnitePawn(CCSPlayerPawn* pEntity, + float flDuration, + CBaseEntity* pInflictor = nullptr, + CBaseEntity* pAttacker = nullptr, + CBaseEntity* pAbility = nullptr, + DamageTypes_t nDamageType = DamageTypes_t(8)); // DMG_BURN diff --git a/src/cvars.cpp b/src/cvars.cpp index f6de75f3..b47abb75 100644 --- a/src/cvars.cpp +++ b/src/cvars.cpp @@ -24,8 +24,8 @@ static uint64 g_iFlagsToRemove = (FCVAR_HIDDEN | FCVAR_DEVELOPMENTONLY | FCVAR_MISSING0 | FCVAR_MISSING1 | FCVAR_MISSING2 | FCVAR_MISSING3); -static constexpr const char *pUnCheatCvars[] = { "bot_stop", "bot_freeze", "bot_zombie" }; -static constexpr const char* pUnCheatCmds[] = { "report_entities", "endround" }; +static constexpr const char* pUnCheatCvars[] = {"bot_stop", "bot_freeze", "bot_zombie"}; +static constexpr const char* pUnCheatCmds[] = {"report_entities", "endround"}; void UnlockConVars() { @@ -34,7 +34,7 @@ void UnlockConVars() int iUnhiddenConVars = 0; - ConVar *pCvar = nullptr; + ConVar* pCvar = nullptr; ConVarHandle hCvarHandle; hCvarHandle.Set(0); @@ -47,12 +47,10 @@ void UnlockConVars() if (!pCvar) continue; - + for (int i = 0; i < sizeof(pUnCheatCvars) / sizeof(*pUnCheatCvars); i++) - { if (!V_strcmp(pCvar->m_pszName, pUnCheatCvars[i])) pCvar->flags &= ~FCVAR_CHEAT; - } if (!(pCvar->flags & g_iFlagsToRemove)) continue; @@ -71,8 +69,8 @@ void UnlockConCommands() int iUnhiddenConCommands = 0; - ConCommand *pConCommand = nullptr; - ConCommand *pInvalidCommand = g_pCVar->GetCommand(ConCommandHandle()); + ConCommand* pConCommand = nullptr; + ConCommand* pInvalidCommand = g_pCVar->GetCommand(ConCommandHandle()); ConCommandHandle hConCommandHandle; hConCommandHandle.Set(0); @@ -86,10 +84,8 @@ void UnlockConCommands() continue; for (int i = 0; i < sizeof(pUnCheatCmds) / sizeof(*pUnCheatCmds); i++) - { if (!V_strcmp(pConCommand->GetName(), pUnCheatCmds[i])) pConCommand->RemoveFlags(FCVAR_CHEAT); - } if (pConCommand->GetFlags() & g_iFlagsToRemove) { @@ -103,7 +99,7 @@ void UnlockConCommands() CON_COMMAND_F(c_dump_cvars, "dump all cvars", FCVAR_SPONLY | FCVAR_LINKED_CONCOMMAND) { - ConVar *pCvar = nullptr; + ConVar* pCvar = nullptr; ConVarHandle hCvarHandle; hCvarHandle.Set(0); @@ -114,75 +110,73 @@ CON_COMMAND_F(c_dump_cvars, "dump all cvars", FCVAR_SPONLY | FCVAR_LINKED_CONCOM hCvarHandle.Set(hCvarHandle.Get() + 1); if (pCvar) - { switch (pCvar->m_eVarType) { - case EConVarType_Bool: - Message("%s : bool : %s\n", pCvar->m_pszName, (bool)pCvar->values ? "true" : "false"); - break; - case EConVarType_Int16: - Message("%s : int16 : %i\n", pCvar->m_pszName, *(int16*)&pCvar->values); - break; - case EConVarType_Int32: - Message("%s : int32 : %i\n", pCvar->m_pszName, *(int32*)&pCvar->values); - break; - case EConVarType_Int64: - Message("%s : int64 : %lli\n", pCvar->m_pszName, (int64)pCvar->values); - break; - case EConVarType_UInt16: - Message("%s : uint16 : %i\n", pCvar->m_pszName, *(uint16*)&pCvar->values); - break; - case EConVarType_UInt32: - Message("%s : uint32 : %i\n", pCvar->m_pszName, *(uint32*)&pCvar->values); - break; - case EConVarType_UInt64: - Message("%s : uint64 : %lli\n", pCvar->m_pszName, (uint64)pCvar->values); - break; - case EConVarType_Float32: - Message("%s : float32 : %.2f\n", pCvar->m_pszName, *(float32 *)&pCvar->values); - break; - case EConVarType_Float64: - Message("%s : float64 : %.2f\n", pCvar->m_pszName, *(float64 *)&pCvar->values); - break; - case EConVarType_String: - Message("%s : string : %s\n", pCvar->m_pszName, (char *)pCvar->values); - break; - - case EConVarType_Color: - int color[4]; - V_memcpy(&color, &pCvar->values, sizeof(color)); - Message("%s : color : %.2f %.2f %.2f %.2f\n", pCvar->m_pszName, color[0], color[1], color[2], color[3]); - break; - - case EConVarType_Vector2: - float vec2[2]; - V_memcpy(&vec2, &pCvar->values, sizeof(vec2)); - Message("%s : vector2 : %.2f %.2f\n", pCvar->m_pszName, vec2[0], vec2[1]); - break; - - case EConVarType_Vector3: - float vec3[3]; - V_memcpy(&vec3, &pCvar->values, sizeof(vec3)); - Message("%s : vector3 : %.2f %.2f %.2f\n", pCvar->m_pszName, vec3[0], vec3[1], vec3[2]); - break; - - case EConVarType_Vector4: - float vec4[4]; - V_memcpy(&vec4, &pCvar->values, sizeof(vec4)); - Message("%s : vector4 : %.2f %.2f %.2f %.2f\n", pCvar->m_pszName, vec4[0], vec4[1], vec4[2], vec4[3]); - break; - - case EConVarType_Qangle: - float angle[3]; - V_memcpy(&vec3, &pCvar->values, sizeof(angle)); - Message("%s : qangle : %.2f %.2f %.2f\n", pCvar->m_pszName, angle[0], angle[1], angle[2]); - break; - - default: - Message("%s : unknown type : %p\n", pCvar->m_pszName, (void*)pCvar->values); - break; + case EConVarType_Bool: + Message("%s : bool : %s\n", pCvar->m_pszName, (bool)pCvar->values ? "true" : "false"); + break; + case EConVarType_Int16: + Message("%s : int16 : %i\n", pCvar->m_pszName, *(int16*)&pCvar->values); + break; + case EConVarType_Int32: + Message("%s : int32 : %i\n", pCvar->m_pszName, *(int32*)&pCvar->values); + break; + case EConVarType_Int64: + Message("%s : int64 : %lli\n", pCvar->m_pszName, (int64)pCvar->values); + break; + case EConVarType_UInt16: + Message("%s : uint16 : %i\n", pCvar->m_pszName, *(uint16*)&pCvar->values); + break; + case EConVarType_UInt32: + Message("%s : uint32 : %i\n", pCvar->m_pszName, *(uint32*)&pCvar->values); + break; + case EConVarType_UInt64: + Message("%s : uint64 : %lli\n", pCvar->m_pszName, (uint64)pCvar->values); + break; + case EConVarType_Float32: + Message("%s : float32 : %.2f\n", pCvar->m_pszName, *(float32*)&pCvar->values); + break; + case EConVarType_Float64: + Message("%s : float64 : %.2f\n", pCvar->m_pszName, *(float64*)&pCvar->values); + break; + case EConVarType_String: + Message("%s : string : %s\n", pCvar->m_pszName, (char*)pCvar->values); + break; + + case EConVarType_Color: + int color[4]; + V_memcpy(&color, &pCvar->values, sizeof(color)); + Message("%s : color : %.2f %.2f %.2f %.2f\n", pCvar->m_pszName, color[0], color[1], color[2], color[3]); + break; + + case EConVarType_Vector2: + float vec2[2]; + V_memcpy(&vec2, &pCvar->values, sizeof(vec2)); + Message("%s : vector2 : %.2f %.2f\n", pCvar->m_pszName, vec2[0], vec2[1]); + break; + + case EConVarType_Vector3: + float vec3[3]; + V_memcpy(&vec3, &pCvar->values, sizeof(vec3)); + Message("%s : vector3 : %.2f %.2f %.2f\n", pCvar->m_pszName, vec3[0], vec3[1], vec3[2]); + break; + + case EConVarType_Vector4: + float vec4[4]; + V_memcpy(&vec4, &pCvar->values, sizeof(vec4)); + Message("%s : vector4 : %.2f %.2f %.2f %.2f\n", pCvar->m_pszName, vec4[0], vec4[1], vec4[2], vec4[3]); + break; + + case EConVarType_Qangle: + float angle[3]; + V_memcpy(&vec3, &pCvar->values, sizeof(angle)); + Message("%s : qangle : %.2f %.2f %.2f\n", pCvar->m_pszName, angle[0], angle[1], angle[2]); + break; + + default: + Message("%s : unknown type : %p\n", pCvar->m_pszName, (void*)pCvar->values); + break; }; - } } while (pCvar); } diff --git a/src/detours.cpp b/src/detours.cpp index be839315..cd76871d 100644 --- a/src/detours.cpp +++ b/src/detours.cpp @@ -22,6 +22,7 @@ #include "usercmd.pb.h" #include "addresses.h" +#include "buttonwatch.h" #include "cdetour.h" #include "commands.h" #include "common.h" @@ -49,18 +50,17 @@ #include "serversideclient.h" #include "tier0/vprof.h" #include "zombiereborn.h" -#include "buttonwatch.h" #include "tier0/memdbgon.h" -extern CGlobalVars *gpGlobals; -extern CGameEntitySystem *g_pEntitySystem; -extern IGameEventManager2 *g_gameEventManager; -extern CCSGameRules *g_pGameRules; -extern CMapVoteSystem *g_pMapVoteSystem; +extern CGlobalVars* gpGlobals; +extern CGameEntitySystem* g_pEntitySystem; +extern IGameEventManager2* g_gameEventManager; +extern CCSGameRules* g_pGameRules; +extern CMapVoteSystem* g_pMapVoteSystem; extern CUtlVector* GetClientList(); -CUtlVector g_vecDetours; +CUtlVector g_vecDetours; DECLARE_DETOUR(UTIL_SayTextFilter, Detour_UTIL_SayTextFilter); DECLARE_DETOUR(UTIL_SayText2Filter, Detour_UTIL_SayText2Filter); @@ -90,7 +90,7 @@ FAKE_BOOL_CVAR(cs2f_block_molotov_self_dmg, "Whether to block self-damage from m FAKE_BOOL_CVAR(cs2f_block_all_dmg, "Whether to block all damage to players", g_bBlockAllDamage, false, false) FAKE_BOOL_CVAR(cs2f_fix_block_dmg, "Whether to fix block-damage on players", g_bFixBlockDamage, false, false) -void FASTCALL Detour_CBaseEntity_TakeDamageOld(CBaseEntity *pThis, CTakeDamageInfo *inputInfo) +void FASTCALL Detour_CBaseEntity_TakeDamageOld(CBaseEntity* pThis, CTakeDamageInfo* inputInfo) { #ifdef _DEBUG Message("\n--------------------------------\n" @@ -108,13 +108,13 @@ void FASTCALL Detour_CBaseEntity_TakeDamageOld(CBaseEntity *pThis, CTakeDamageIn inputInfo->m_flDamage, inputInfo->m_bitsDamageType); #endif - + // Block all player damage if desired if (g_bBlockAllDamage && pThis->IsPawn()) return; - CBaseEntity *pInflictor = inputInfo->m_hInflictor.Get(); - const char *pszInflictorClass = pInflictor ? pInflictor->GetClassname() : ""; + CBaseEntity* pInflictor = inputInfo->m_hInflictor.Get(); + const char* pszInflictorClass = pInflictor ? pInflictor->GetClassname() : ""; // After Armory update, activator became attacker on block damage, which broke it.. if (g_bFixBlockDamage && inputInfo->m_AttackerInfo.m_bIsPawn && inputInfo->m_bitsDamageType ^ DMG_BULLET && inputInfo->m_hAttacker != pThis->GetHandle()) @@ -190,9 +190,7 @@ void FASTCALL Detour_TriggerPush_Touch(CTriggerPush* pPush, CBaseEntity* pOther) uint32 flags = pOther->m_fFlags(); if (flags & FL_BASEVELOCITY) - { vecPush = vecPush + pOther->m_vecBaseVelocity(); - } if (vecPush.z > 0 && (flags & FL_ONGROUND)) { @@ -233,7 +231,7 @@ bool FASTCALL Detour_IsHearingClient(void* serverClient, int index) return IsHearingClient(serverClient, index); } -void SayChatMessageWithTimer(IRecipientFilter &filter, const char *pText, CCSPlayerController *pPlayer, uint64 eMessageType) +void SayChatMessageWithTimer(IRecipientFilter& filter, const char* pText, CCSPlayerController* pPlayer, uint64 eMessageType) { VPROF("SayChatMessageWithTimer"); @@ -256,7 +254,7 @@ void SayChatMessageWithTimer(IRecipientFilter &filter, const char *pText, CCSPla // Split console message into words seperated by the space character CSplitString words(filteredText, " "); - //Word count includes the first word "Console:" at index 0, first relevant word is at index 1 + // Word count includes the first word "Console:" at index 0, first relevant word is at index 1 int iWordCount = words.Count(); uint32 uiTriggerTimerLength = 0; @@ -294,7 +292,7 @@ void SayChatMessageWithTimer(IRecipientFilter &filter, const char *pText, CCSPla { if (pCurrentWord[j] >= '0' && pCurrentWord[j] <= '9') continue; - + if (pCurrentWord[j] == 's') { pCurrentWord[j] = '\0'; @@ -331,7 +329,7 @@ bool g_bEnableTriggerTimer = false; FAKE_BOOL_CVAR(cs2f_trigger_timer_enable, "Whether to process countdown messages said by Console (e.g. Hold for 10 seconds) and append the round time where the countdown resolves", g_bEnableTriggerTimer, false, false) -void FASTCALL Detour_UTIL_SayTextFilter(IRecipientFilter &filter, const char *pText, CCSPlayerController *pPlayer, uint64 eMessageType) +void FASTCALL Detour_UTIL_SayTextFilter(IRecipientFilter& filter, const char* pText, CCSPlayerController* pPlayer, uint64 eMessageType) { if (pPlayer) return UTIL_SayTextFilter(filter, pText, pPlayer, eMessageType); @@ -346,17 +344,17 @@ void FASTCALL Detour_UTIL_SayTextFilter(IRecipientFilter &filter, const char *pT } void FASTCALL Detour_UTIL_SayText2Filter( - IRecipientFilter &filter, - CCSPlayerController *pEntity, + IRecipientFilter& filter, + CCSPlayerController* pEntity, uint64 eMessageType, - const char *msg_name, - const char *param1, - const char *param2, - const char *param3, - const char *param4) + const char* msg_name, + const char* param1, + const char* param2, + const char* param3, + const char* param4) { #ifdef _DEBUG - CPlayerSlot slot = filter.GetRecipientIndex(0); + CPlayerSlot slot = filter.GetRecipientIndex(0); CCSPlayerController* target = CCSPlayerController::FromSlot(slot); if (target) @@ -366,12 +364,10 @@ void FASTCALL Detour_UTIL_SayText2Filter( UTIL_SayText2Filter(filter, pEntity, eMessageType, msg_name, param1, param2, param3, param4); } -bool FASTCALL Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices *pWeaponServices, CBasePlayerWeapon* pPlayerWeapon) +bool FASTCALL Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices* pWeaponServices, CBasePlayerWeapon* pPlayerWeapon) { if (g_bEnableZR && !ZR_Detour_CCSPlayer_WeaponServices_CanUse(pWeaponServices, pPlayerWeapon)) - { return false; - } return CCSPlayer_WeaponServices_CanUse(pWeaponServices, pPlayerWeapon); } @@ -404,7 +400,7 @@ bool FASTCALL Detour_CEntityIdentity_AcceptInput(CEntityIdentity* pThis, CUtlSym else flDuration = value->m_float; - CCSPlayerPawn *pPawn = reinterpret_cast(pThis->m_pInstance); + CCSPlayerPawn* pPawn = reinterpret_cast(pThis->m_pInstance); if (pPawn->IsPawn() && IgnitePawn(pPawn, flDuration, pPawn, pPawn)) return true; @@ -418,7 +414,7 @@ bool FASTCALL Detour_CEntityIdentity_AcceptInput(CEntityIdentity* pThis, CUtlSym else iScore = value->m_int; - CCSPlayerPawn *pPawn = reinterpret_cast(pThis->m_pInstance); + CCSPlayerPawn* pPawn = reinterpret_cast(pThis->m_pInstance); if (pPawn->IsPawn() && pPawn->GetOriginalController()) { @@ -426,14 +422,12 @@ bool FASTCALL Detour_CEntityIdentity_AcceptInput(CEntityIdentity* pThis, CUtlSym return true; } } - else if (!V_strcasecmp(pInputName->String(), "SetMessage")) + else if (!V_strcasecmp(pInputName->String(), "SetMessage")) { if (const auto pHudHint = reinterpret_cast(pThis->m_pInstance)->AsHudHint()) { if ((value->m_type == FIELD_CSTRING || value->m_type == FIELD_STRING) && value->m_pszString) - { pHudHint->m_iszMessage(GameEntitySystem()->AllocPooledString(value->m_pszString)); - } return true; } } @@ -442,9 +436,7 @@ bool FASTCALL Detour_CEntityIdentity_AcceptInput(CEntityIdentity* pThis, CUtlSym if (const auto pModelEntity = reinterpret_cast(pThis->m_pInstance)->AsBaseModelEntity()) { if ((value->m_type == FIELD_CSTRING || value->m_type == FIELD_STRING) && value->m_pszString) - { pModelEntity->SetModel(value->m_pszString); - } return true; } } @@ -469,7 +461,7 @@ bool FASTCALL Detour_CEntityIdentity_AcceptInput(CEntityIdentity* pThis, CUtlSym VPROF_SCOPE_END(); - return CEntityIdentity_AcceptInput(pThis, pInputName, pActivator, pCaller, value, nOutputID); + return CEntityIdentity_AcceptInput(pThis, pInputName, pActivator, pCaller, value, nOutputID); } bool g_bBlockNavLookup = false; @@ -484,14 +476,14 @@ void* FASTCALL Detour_CNavMesh_GetNearestNavArea(int64_t unk1, float* unk2, unsi return CNavMesh_GetNearestNavArea(unk1, unk2, unk3, unk4, unk5, unk6, unk7, unk8); } -void FASTCALL Detour_ProcessMovement(CCSPlayer_MovementServices *pThis, void *pMove) +void FASTCALL Detour_ProcessMovement(CCSPlayer_MovementServices* pThis, void* pMove) { - CCSPlayerPawn *pPawn = pThis->GetPawn(); + CCSPlayerPawn* pPawn = pThis->GetPawn(); if (!pPawn->IsAlive()) return ProcessMovement(pThis, pMove); - CCSPlayerController *pController = pPawn->GetOriginalController(); + CCSPlayerController* pController = pPawn->GetOriginalController(); if (!pController || !pController->IsConnected()) return ProcessMovement(pThis, pMove); @@ -501,7 +493,6 @@ void FASTCALL Detour_ProcessMovement(CCSPlayer_MovementServices *pThis, void *pM if (flSpeedMod == 1.f) return ProcessMovement(pThis, pMove); - // Yes, this is what source1 does to scale player speed // Scale frametime during the entire movement processing step and revert right after float flStoreFrametime = gpGlobals->frametime; @@ -530,7 +521,7 @@ class CUserCmd #endif }; -void* FASTCALL Detour_ProcessUsercmds(CCSPlayerController *pController, CUserCmd *cmds, int numcmds, bool paused, float margin) +void* FASTCALL Detour_ProcessUsercmds(CCSPlayerController* pController, CUserCmd* cmds, int numcmds, bool paused, float margin) { // Push fix only works properly if subtick movement is also disabled if (!g_bDisableSubtick && !g_bUseOldPush) @@ -558,8 +549,8 @@ void* FASTCALL Detour_ProcessUsercmds(CCSPlayerController *pController, CUserCmd void FASTCALL Detour_CGamePlayerEquip_InputTriggerForAllPlayers(CGamePlayerEquip* pEntity, InputData_t* pInput) { - CGamePlayerEquipHandler::TriggerForAllPlayers(pEntity, pInput); - CGamePlayerEquip_InputTriggerForAllPlayers(pEntity, pInput); + CGamePlayerEquipHandler::TriggerForAllPlayers(pEntity, pInput); + CGamePlayerEquip_InputTriggerForAllPlayers(pEntity, pInput); } void FASTCALL Detour_CGamePlayerEquip_InputTriggerForActivatedPlayer(CGamePlayerEquip* pEntity, InputData_t* pInput) { @@ -592,9 +583,7 @@ float FASTCALL Detour_CCSPlayerPawn_GetMaxSpeed(CCSPlayerPawn* pPawn) const auto pController = reinterpret_cast(pPawn->GetController()); if (const auto pPlayer = pController != nullptr ? pController->GetZEPlayer() : nullptr) - { flMaxSpeed *= pPlayer->GetMaxSpeed(); - } return flMaxSpeed; } @@ -615,7 +604,7 @@ bool FASTCALL Detour_TraceFunc(int64* a1, int* a2, float* a3, uint64 traceMask) { if (g_bPreventUsingPlayers && g_bFindingUseEntity) { - uint64 newMask = traceMask & ( ~(CONTENTS_PLAYER & CONTENTS_NPC) ); + uint64 newMask = traceMask & (~(CONTENTS_PLAYER & CONTENTS_NPC)); return TraceFunc(a1, a2, a3, newMask); } @@ -633,7 +622,6 @@ bool FASTCALL Detour_TraceShape(int64* a1, int64 a2, int64 a3, int64 a4, CTraceF return TraceShape(a1, a2, a3, a4, filter, a6); } - CDetour* CEntityIOOutput_FireOutputInternal = nullptr; std::map> mapIOFunctions{}; void FASTCALL Detour_CEntityIOOutput_FireOutputInternal(const CEntityIOOutput* pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* value, float flDelay) @@ -667,50 +655,50 @@ bool SetupFireOutputInternalDetour() #ifdef PLATFORM_WINDOWS Vector* FASTCALL Detour_CBasePlayerPawn_GetEyePosition(CBasePlayerPawn* pPawn, Vector* pRet) { - if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) - { - const auto& origin = pPawn->GetEyePosition(); - pRet->Init(origin.x, origin.y, origin.z); - return pRet; - } - - return CBasePlayerPawn_GetEyePosition(pPawn, pRet); + if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) + { + const auto& origin = pPawn->GetEyePosition(); + pRet->Init(origin.x, origin.y, origin.z); + return pRet; + } + + return CBasePlayerPawn_GetEyePosition(pPawn, pRet); } QAngle* FASTCALL Detour_CBasePlayerPawn_GetEyeAngles(CBasePlayerPawn* pPawn, QAngle* pRet) { - if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) - { - const auto& angles = pPawn->v_angle(); - pRet->Init(angles.x, angles.y, angles.z); - return pRet; - } - - return CBasePlayerPawn_GetEyeAngles(pPawn, pRet); + if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) + { + const auto& angles = pPawn->v_angle(); + pRet->Init(angles.x, angles.y, angles.z); + return pRet; + } + + return CBasePlayerPawn_GetEyeAngles(pPawn, pRet); } #else Vector FASTCALL Detour_CBasePlayerPawn_GetEyePosition(CBasePlayerPawn* pPawn) { - if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) - { - const auto& origin = pPawn->GetEyePosition(); - return origin; - } + if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) + { + const auto& origin = pPawn->GetEyePosition(); + return origin; + } - return CBasePlayerPawn_GetEyePosition(pPawn); + return CBasePlayerPawn_GetEyePosition(pPawn); } QAngle FASTCALL Detour_CBasePlayerPawn_GetEyeAngles(CBasePlayerPawn* pPawn) { - if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) - { - const auto& angles = pPawn->v_angle(); - return angles; - } + if (pPawn->IsAlive() && CPointViewControlHandler::IsViewControl(reinterpret_cast(pPawn))) + { + const auto& angles = pPawn->v_angle(); + return angles; + } - return CBasePlayerPawn_GetEyeAngles(pPawn); + return CBasePlayerPawn_GetEyeAngles(pPawn); } #endif -bool InitDetours(CGameConfig *gameConfig) +bool InitDetours(CGameConfig* gameConfig) { bool success = true; @@ -718,7 +706,7 @@ bool InitDetours(CGameConfig *gameConfig) { if (!g_vecDetours[i]->CreateDetour(gameConfig)) success = false; - + g_vecDetours[i]->EnableDetour(); } diff --git a/src/detours.h b/src/detours.h index a2df94b7..e3b2ea4e 100644 --- a/src/detours.h +++ b/src/detours.h @@ -19,8 +19,8 @@ #pragma once #include "cdetour.h" -#include #include "cs2_sdk/entityio.h" +#include class CCheckTransmitInfo; class IRecipientFilter; @@ -51,7 +51,7 @@ class CTraceFilter; class Vector; class QAngle; -bool InitDetours(CGameConfig *gameConfig); +bool InitDetours(CGameConfig* gameConfig); void FlushAllDetours(); bool SetupFireOutputInternalDetour(); @@ -59,18 +59,18 @@ bool SetupFireOutputInternalDetour(); // to make it more modular/cleaner than shoving everything into the detour (buttonwatch, entwatch, etc.) extern std::map> mapIOFunctions; -void FASTCALL Detour_UTIL_SayTextFilter(IRecipientFilter &, const char *, CCSPlayerController *, uint64); -void FASTCALL Detour_UTIL_SayText2Filter(IRecipientFilter &, CCSPlayerController *, uint64, const char *, const char *, const char *, const char *, const char *); +void FASTCALL Detour_UTIL_SayTextFilter(IRecipientFilter&, const char*, CCSPlayerController*, uint64); +void FASTCALL Detour_UTIL_SayText2Filter(IRecipientFilter&, CCSPlayerController*, uint64, const char*, const char*, const char*, const char*, const char*); bool FASTCALL Detour_IsHearingClient(void*, int); void FASTCALL Detour_TriggerPush_Touch(CTriggerPush* pPush, CBaseEntity* pOther); -void FASTCALL Detour_CBaseEntity_TakeDamageOld(CBaseEntity *pThis, CTakeDamageInfo *inputInfo); -bool FASTCALL Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices *, CBasePlayerWeapon *); +void FASTCALL Detour_CBaseEntity_TakeDamageOld(CBaseEntity* pThis, CTakeDamageInfo* inputInfo); +bool FASTCALL Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices*, CBasePlayerWeapon*); bool FASTCALL Detour_CEntityIdentity_AcceptInput(CEntityIdentity* pThis, CUtlSymbolLarge* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID); void* FASTCALL Detour_CNavMesh_GetNearestNavArea(int64_t unk1, float* unk2, unsigned int* unk3, unsigned int unk4, int64_t unk5, int64_t unk6, float unk7, int64_t unk8); -void FASTCALL Detour_ProcessMovement(CCSPlayer_MovementServices *pThis, void *pMove); -void *FASTCALL Detour_ProcessUsercmds(CCSPlayerController *pController, CUserCmd *cmds, int numcmds, bool paused, float margin); -void FASTCALL Detour_CGamePlayerEquip_InputTriggerForAllPlayers(CGamePlayerEquip*, InputData_t*); -void FASTCALL Detour_CGamePlayerEquip_InputTriggerForActivatedPlayer(CGamePlayerEquip*, InputData_t*); +void FASTCALL Detour_ProcessMovement(CCSPlayer_MovementServices* pThis, void* pMove); +void* FASTCALL Detour_ProcessUsercmds(CCSPlayerController* pController, CUserCmd* cmds, int numcmds, bool paused, float margin); +void FASTCALL Detour_CGamePlayerEquip_InputTriggerForAllPlayers(CGamePlayerEquip*, InputData_t*); +void FASTCALL Detour_CGamePlayerEquip_InputTriggerForActivatedPlayer(CGamePlayerEquip*, InputData_t*); CServerSideClient* FASTCALL Detour_GetFreeClient(int64_t unk1, const __m128i* unk2, unsigned int unk3, int64_t unk4, char unk5, void* unk6); float FASTCALL Detour_CCSPlayerPawn_GetMaxSpeed(CCSPlayerPawn*); int64 FASTCALL Detour_FindUseEntity(CCSPlayer_UseServices* pThis, float); diff --git a/src/discord.cpp b/src/discord.cpp index 19fcb97d..226c8069 100644 --- a/src/discord.cpp +++ b/src/discord.cpp @@ -17,18 +17,17 @@ * this program. If not, see . */ -#include "common.h" #include "discord.h" #include "KeyValues.h" -#include "interfaces/interfaces.h" +#include "common.h" #include "httpmanager.h" +#include "interfaces/interfaces.h" #include "utlstring.h" #include "vendor/nlohmann/json.hpp" using json = nlohmann::json; - CDiscordBotManager* g_pDiscordBotManager = nullptr; // TODO: CVAR @@ -44,27 +43,26 @@ CON_COMMAND_F(cs2f_debug_discord_messages, "Whether to include debug information void DiscordHttpCallback(HTTPRequestHandle request, json response) { - if (g_bDebugDiscordRequests) { + if (g_bDebugDiscordRequests) Message("Discord post received response: %s\n", response.dump().c_str()); - } } -void CDiscordBotManager::PostDiscordMessage(const char* sDiscordBotName, const char* sMessage) { +void CDiscordBotManager::PostDiscordMessage(const char* sDiscordBotName, const char* sMessage) +{ FOR_EACH_VEC(m_vecDiscordBots, i) { CDiscordBot bot = m_vecDiscordBots[i]; - if (g_bDebugDiscordRequests) { + if (g_bDebugDiscordRequests) Message("The bot at %i is %s with %s webhook and %s avatar.\n", i, bot.GetName(), bot.GetWebhookUrl(), bot.GetAvatarUrl()); - } - if (!V_stricmp(sDiscordBotName, bot.GetName())) { + if (!V_stricmp(sDiscordBotName, bot.GetName())) bot.PostMessage(sMessage); - } } } -void CDiscordBot::PostMessage(const char* sMessage) { +void CDiscordBot::PostMessage(const char* sMessage) +{ json jRequestBody; // Fill up the Json fields @@ -78,9 +76,8 @@ void CDiscordBot::PostMessage(const char* sMessage) { // Send the request std::string sRequestBody = jRequestBody.dump(); - if (g_bDebugDiscordRequests) { + if (g_bDebugDiscordRequests) Message("Sending '%s' to %s.\n", sRequestBody.c_str(), GetWebhookUrl()); - } g_HTTPManager.POST(m_pszWebhookUrl, sRequestBody.c_str(), &DiscordHttpCallback); } diff --git a/src/discord.h b/src/discord.h index 4e998cea..2be0dae5 100644 --- a/src/discord.h +++ b/src/discord.h @@ -43,7 +43,6 @@ class CDiscordBot bool m_bOverrideName; }; - class CDiscordBotManager { public: diff --git a/src/entities.cpp b/src/entities.cpp index df78e41a..147ddf00 100644 --- a/src/entities.cpp +++ b/src/entities.cpp @@ -36,689 +36,656 @@ extern CCSGameRules* g_pGameRules; class InputData_t { public: - CBaseEntity* pActivator; - CBaseEntity* pCaller; - variant_t value; - int nOutputID; + CBaseEntity* pActivator; + CBaseEntity* pCaller; + variant_t value; + int nOutputID; }; inline bool StripPlayer(CCSPlayerPawn* pPawn) { - const auto pItemServices = pPawn->m_pItemServices(); + const auto pItemServices = pPawn->m_pItemServices(); - if (!pItemServices) - return false; + if (!pItemServices) + return false; - pItemServices->StripPlayerWeapons(true); + pItemServices->StripPlayerWeapons(true); - return true; + return true; } // Must be called in GameFramePre inline void DelayInput(CBaseEntity* pCaller, const char* input, const char* param = "") { - const auto eh = pCaller->GetHandle(); + const auto eh = pCaller->GetHandle(); - new CTimer(0.f, false, false, [eh, input, param]() { - if (const auto entity = reinterpret_cast(eh.Get())) - entity->AcceptInput(input, param, nullptr, entity); + new CTimer(0.f, false, false, [eh, input, param]() { + if (const auto entity = reinterpret_cast(eh.Get())) + entity->AcceptInput(input, param, nullptr, entity); - return -1.f; - }); + return -1.f; + }); } // Must be called in GameFramePre inline void DelayInput(CBaseEntity* pCaller, CBaseEntity* pActivator, const char* input, const char* param = "") { - const auto eh = pCaller->GetHandle(); - const auto ph = pActivator->GetHandle(); + const auto eh = pCaller->GetHandle(); + const auto ph = pActivator->GetHandle(); - new CTimer(0.f, false, false, [eh, ph, input, param]() { - const auto player = reinterpret_cast(ph.Get()); - if (const auto entity = reinterpret_cast(eh.Get())) - entity->AcceptInput(input, param, player, entity); + new CTimer(0.f, false, false, [eh, ph, input, param]() { + const auto player = reinterpret_cast(ph.Get()); + if (const auto entity = reinterpret_cast(eh.Get())) + entity->AcceptInput(input, param, player, entity); - return -1.f; - }); + return -1.f; + }); } namespace CGamePlayerEquipHandler { - -void Use(CGamePlayerEquip* pEntity, InputData_t* pInput) -{ - const auto pCaller = pInput->pActivator; - - if (!pCaller || !pCaller->IsPawn()) - return; - - const auto pPawn = reinterpret_cast(pCaller); - - const auto flags = pEntity->m_spawnflags(); - - if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_STRIPFIRST) - { - if (!StripPlayer(pPawn)) - return; - } - else if (flags & ::CGamePlayerEquip::SF_PLAYEREQUIP_ONLYSTRIPSAME) - { - // TODO support strip same flags - } -} - -void TriggerForAllPlayers(CGamePlayerEquip* pEntity, InputData_t* pInput) -{ - const auto flags = pEntity->m_spawnflags(); - - if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_STRIPFIRST) - { - CCSPlayerPawn* pPawn = nullptr; - while ((pPawn = reinterpret_cast(UTIL_FindEntityByClassname(pPawn, "player"))) != nullptr) - { - if (pPawn->IsPawn() && pPawn->IsAlive()) - StripPlayer(pPawn); - } - } - else if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_ONLYSTRIPSAME) - { - // TODO support strip same flags - } -} - -bool TriggerForActivatedPlayer(CGamePlayerEquip* pEntity, InputData_t* pInput) -{ - const auto pCaller = pInput->pActivator; - const auto pszWeapon = ((pInput->value.m_type == FIELD_CSTRING || pInput->value.m_type == FIELD_STRING) && pInput->value.m_pszString) ? pInput->value.m_pszString : nullptr; - - if (!pCaller || !pCaller->IsPawn()) - return true; - - const auto pPawn = reinterpret_cast(pCaller); - const auto flags = pEntity->m_spawnflags(); - - if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_STRIPFIRST) - { - if (!StripPlayer(pPawn)) - return true; - } - else if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_ONLYSTRIPSAME) - { - // TODO - } - - const auto pItemServices = pPawn->m_pItemServices(); - - if (!pItemServices) - return true; - - if (pszWeapon && V_strcmp(pszWeapon, "(null)")) - { - pItemServices->GiveNamedItem(pszWeapon); - // Don't execute game function (we fixed string param) - return false; - } - - return true; -} + void Use(CGamePlayerEquip* pEntity, InputData_t* pInput) + { + const auto pCaller = pInput->pActivator; + + if (!pCaller || !pCaller->IsPawn()) + return; + + const auto pPawn = reinterpret_cast(pCaller); + + const auto flags = pEntity->m_spawnflags(); + + if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_STRIPFIRST) + { + if (!StripPlayer(pPawn)) + return; + } + else if (flags & ::CGamePlayerEquip::SF_PLAYEREQUIP_ONLYSTRIPSAME) + { + // TODO support strip same flags + } + } + + void TriggerForAllPlayers(CGamePlayerEquip* pEntity, InputData_t* pInput) + { + const auto flags = pEntity->m_spawnflags(); + + if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_STRIPFIRST) + { + CCSPlayerPawn* pPawn = nullptr; + while ((pPawn = reinterpret_cast(UTIL_FindEntityByClassname(pPawn, "player"))) != nullptr) + if (pPawn->IsPawn() && pPawn->IsAlive()) + StripPlayer(pPawn); + } + else if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_ONLYSTRIPSAME) + { + // TODO support strip same flags + } + } + + bool TriggerForActivatedPlayer(CGamePlayerEquip* pEntity, InputData_t* pInput) + { + const auto pCaller = pInput->pActivator; + const auto pszWeapon = ((pInput->value.m_type == FIELD_CSTRING || pInput->value.m_type == FIELD_STRING) && pInput->value.m_pszString) ? pInput->value.m_pszString : nullptr; + + if (!pCaller || !pCaller->IsPawn()) + return true; + + const auto pPawn = reinterpret_cast(pCaller); + const auto flags = pEntity->m_spawnflags(); + + if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_STRIPFIRST) + { + if (!StripPlayer(pPawn)) + return true; + } + else if (flags & CGamePlayerEquip::SF_PLAYEREQUIP_ONLYSTRIPSAME) + { + // TODO + } + + const auto pItemServices = pPawn->m_pItemServices(); + + if (!pItemServices) + return true; + + if (pszWeapon && V_strcmp(pszWeapon, "(null)")) + { + pItemServices->GiveNamedItem(pszWeapon); + // Don't execute game function (we fixed string param) + return false; + } + + return true; + } } // namespace CGamePlayerEquipHandler namespace CGameUIHandler { -constexpr uint64 BAD_BUTTONS = ~0; - -struct CGameUIState -{ - CHandle m_pPlayer; - uint64 m_nButtonState; - - CGameUIState() : - m_pPlayer(CBaseHandle()), m_nButtonState(BAD_BUTTONS) {} - CGameUIState(const CGameUIState& other) = delete; - - CGameUIState(CCSPlayerPawn* pawn, uint64 buttons) : - m_pPlayer(pawn), m_nButtonState(buttons) {} - - [[nodiscard]] CCSPlayerPawn* GetPlayer() const { return m_pPlayer.Get(); } - - void UpdateButtons(uint64 buttons) { m_nButtonState = buttons; } -}; - -static std::unordered_map s_repository; - -inline uint64 GetButtons(CPlayer_MovementServices* pMovement) -{ - const auto buttonStates = pMovement->m_nButtons().m_pButtonStates(); - const auto buttons = buttonStates[0]; - return buttons; -} - -inline uint64 GameUIThink(CGameUI* pEntity, CCSPlayerPawn* pPlayer, uint32 lastButtons) -{ - const auto pMovement = pPlayer->m_pMovementServices(); - if (!pMovement) - return BAD_BUTTONS; - - const auto spawnFlags = pEntity->m_spawnflags(); - const auto buttons = GetButtons(pMovement); - - if ((spawnFlags & CGameUI::SF_GAMEUI_JUMP_DEACTIVATE) != 0 && (buttons & IN_JUMP) != 0) - { - DelayInput(pEntity, pPlayer, "Deactivate"); - return BAD_BUTTONS; - } - - const auto nButtonsChanged = buttons ^ lastButtons; - - // W - if ((nButtonsChanged & IN_FORWARD) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_FORWARD) != 0 ? "UnpressedForward" : "PressedForward", pPlayer, pEntity); - } - - // A - if ((nButtonsChanged & IN_MOVELEFT) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_MOVELEFT) != 0 ? "UnpressedMoveLeft" : "PressedMoveLeft", pPlayer, pEntity); - } - - // S - if ((nButtonsChanged & IN_BACK) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_BACK) != 0 ? "UnpressedBack" : "PressedBack", pPlayer, pEntity); - } - - // D - if ((nButtonsChanged & IN_MOVERIGHT) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_MOVERIGHT) != 0 ? "UnpressedMoveRight" : "PressedMoveRight", pPlayer, pEntity); - } - - // Attack - if ((nButtonsChanged & IN_ATTACK) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_ATTACK) != 0 ? "UnpressedAttack" : "PressedAttack", pPlayer, pEntity); - } - - // Attack2 - if ((nButtonsChanged & IN_ATTACK2) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_ATTACK2) != 0 ? "UnpressedAttack2" : "PressedAttack2", pPlayer, pEntity); - } - - // Speed - if ((nButtonsChanged & IN_SPEED) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_SPEED) != 0 ? "UnpressedSpeed" : "PressedSpeed", pPlayer, pEntity); - } - - // Duck - if ((nButtonsChanged & IN_DUCK) != 0) - { - pEntity->AcceptInput("InValue", (lastButtons & IN_DUCK) != 0 ? "UnpressedDuck" : "PressedDuck", pPlayer, pEntity); - } - - return buttons; -} - -// [Kxnrl]: Must be called on game frame pre, and timer done in post! -void RunThink(int tick) -{ - // validate - for (auto it = s_repository.begin(); it != s_repository.end();) - { - const auto entity = CHandle(it->first).Get(); - if (!entity) - { - it = s_repository.erase(it); + constexpr uint64 BAD_BUTTONS = ~0; + + struct CGameUIState + { + CHandle m_pPlayer; + uint64 m_nButtonState; + + CGameUIState() : + m_pPlayer(CBaseHandle()), m_nButtonState(BAD_BUTTONS) {} + CGameUIState(const CGameUIState& other) = delete; + + CGameUIState(CCSPlayerPawn* pawn, uint64 buttons) : + m_pPlayer(pawn), m_nButtonState(buttons) {} + + [[nodiscard]] CCSPlayerPawn* GetPlayer() const { return m_pPlayer.Get(); } + + void UpdateButtons(uint64 buttons) { m_nButtonState = buttons; } + }; + + static std::unordered_map s_repository; + + inline uint64 GetButtons(CPlayer_MovementServices* pMovement) + { + const auto buttonStates = pMovement->m_nButtons().m_pButtonStates(); + const auto buttons = buttonStates[0]; + return buttons; + } + + inline uint64 GameUIThink(CGameUI* pEntity, CCSPlayerPawn* pPlayer, uint32 lastButtons) + { + const auto pMovement = pPlayer->m_pMovementServices(); + if (!pMovement) + return BAD_BUTTONS; + + const auto spawnFlags = pEntity->m_spawnflags(); + const auto buttons = GetButtons(pMovement); + + if ((spawnFlags & CGameUI::SF_GAMEUI_JUMP_DEACTIVATE) != 0 && (buttons & IN_JUMP) != 0) + { + DelayInput(pEntity, pPlayer, "Deactivate"); + return BAD_BUTTONS; + } + + const auto nButtonsChanged = buttons ^ lastButtons; + + // W + if ((nButtonsChanged & IN_FORWARD) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_FORWARD) != 0 ? "UnpressedForward" : "PressedForward", pPlayer, pEntity); + + // A + if ((nButtonsChanged & IN_MOVELEFT) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_MOVELEFT) != 0 ? "UnpressedMoveLeft" : "PressedMoveLeft", pPlayer, pEntity); + + // S + if ((nButtonsChanged & IN_BACK) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_BACK) != 0 ? "UnpressedBack" : "PressedBack", pPlayer, pEntity); + + // D + if ((nButtonsChanged & IN_MOVERIGHT) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_MOVERIGHT) != 0 ? "UnpressedMoveRight" : "PressedMoveRight", pPlayer, pEntity); + + // Attack + if ((nButtonsChanged & IN_ATTACK) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_ATTACK) != 0 ? "UnpressedAttack" : "PressedAttack", pPlayer, pEntity); + + // Attack2 + if ((nButtonsChanged & IN_ATTACK2) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_ATTACK2) != 0 ? "UnpressedAttack2" : "PressedAttack2", pPlayer, pEntity); + + // Speed + if ((nButtonsChanged & IN_SPEED) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_SPEED) != 0 ? "UnpressedSpeed" : "PressedSpeed", pPlayer, pEntity); + + // Duck + if ((nButtonsChanged & IN_DUCK) != 0) + pEntity->AcceptInput("InValue", (lastButtons & IN_DUCK) != 0 ? "UnpressedDuck" : "PressedDuck", pPlayer, pEntity); + + return buttons; + } + + // [Kxnrl]: Must be called on game frame pre, and timer done in post! + void RunThink(int tick) + { + // validate + for (auto it = s_repository.begin(); it != s_repository.end();) + { + const auto entity = CHandle(it->first).Get(); + if (!entity) + { + it = s_repository.erase(it); #ifdef ENTITY_HANDLER_ASSERTION - Message("Remove Entity %d due to invalid.\n", CBaseHandle(it->first).GetEntryIndex()); + Message("Remove Entity %d due to invalid.\n", CBaseHandle(it->first).GetEntryIndex()); #endif - } - else - { - ++it; - } - } - - // think every 4 tick - if ((tick & 4) != 0) - return; - - for (auto& [key, state] : s_repository) - { - const auto entity = CHandle(key).Get(); - const auto player = state.GetPlayer(); - - if (!player || !player->IsPawn()) - { - DelayInput(entity, "Deactivate"); + } + else + { + ++it; + } + } + + // think every 4 tick + if ((tick & 4) != 0) + return; + + for (auto& [key, state] : s_repository) + { + const auto entity = CHandle(key).Get(); + const auto player = state.GetPlayer(); + + if (!player || !player->IsPawn()) + { + DelayInput(entity, "Deactivate"); #ifdef ENTITY_HANDLER_ASSERTION - Message("Deactivate Entity %d due to invalid player.\n", entity->entindex()); + Message("Deactivate Entity %d due to invalid player.\n", entity->entindex()); #endif - continue; - } + continue; + } - if (!player->IsAlive()) - { - DelayInput(entity, player, "Deactivate"); + if (!player->IsAlive()) + { + DelayInput(entity, player, "Deactivate"); #ifdef ENTITY_HANDLER_ASSERTION - Message("Deactivate Entity %d due to player dead.\n", entity->entindex()); + Message("Deactivate Entity %d due to player dead.\n", entity->entindex()); #endif - continue; - } + continue; + } - const auto newButtons = GameUIThink(entity, player, state.m_nButtonState); + const auto newButtons = GameUIThink(entity, player, state.m_nButtonState); - if (newButtons != BAD_BUTTONS) - { - state.UpdateButtons(newButtons); - } - } -} + if (newButtons != BAD_BUTTONS) + state.UpdateButtons(newButtons); + } + } -bool OnActivate(CGameUI* pEntity, CBaseEntity* pActivator) -{ - if (!pActivator || !pActivator->IsPawn()) - return false; + bool OnActivate(CGameUI* pEntity, CBaseEntity* pActivator) + { + if (!pActivator || !pActivator->IsPawn()) + return false; - const auto pPlayer = reinterpret_cast(pActivator); + const auto pPlayer = reinterpret_cast(pActivator); - const auto pMovement = pPlayer->m_pMovementServices(); - if (!pMovement) - return false; + const auto pMovement = pPlayer->m_pMovementServices(); + if (!pMovement) + return false; - if ((pEntity->m_spawnflags() & CGameUI::SF_GAMEUI_FREEZE_PLAYER) != 0) - pPlayer->m_fFlags(pPlayer->m_fFlags() | FL_ATCONTROLS); + if ((pEntity->m_spawnflags() & CGameUI::SF_GAMEUI_FREEZE_PLAYER) != 0) + pPlayer->m_fFlags(pPlayer->m_fFlags() | FL_ATCONTROLS); - const CBaseHandle handle = pEntity->GetHandle(); - const auto key = static_cast(handle.ToInt()); + const CBaseHandle handle = pEntity->GetHandle(); + const auto key = static_cast(handle.ToInt()); - DelayInput(pEntity, pPlayer, "InValue", "PlayerOn"); + DelayInput(pEntity, pPlayer, "InValue", "PlayerOn"); - s_repository[key] = CGameUIState(pPlayer, GetButtons(pMovement) & ~IN_USE); + s_repository[key] = CGameUIState(pPlayer, GetButtons(pMovement) & ~IN_USE); #ifdef ENTITY_HANDLER_ASSERTION - Message("Activate Entity %d<%u> -> %s\n", pEntity->entindex(), key, pPlayer->GetController()->GetPlayerName()); + Message("Activate Entity %d<%u> -> %s\n", pEntity->entindex(), key, pPlayer->GetController()->GetPlayerName()); #endif - return true; -} + return true; + } -bool OnDeactivate(CGameUI* pEntity, CBaseEntity* pActivator) -{ - const CBaseHandle handle = CHandle(pEntity); - const auto key = static_cast(handle.ToInt()); - const auto it = s_repository.find(key); + bool OnDeactivate(CGameUI* pEntity, CBaseEntity* pActivator) + { + const CBaseHandle handle = CHandle(pEntity); + const auto key = static_cast(handle.ToInt()); + const auto it = s_repository.find(key); - if (it == s_repository.end()) - { + if (it == s_repository.end()) + { #ifdef ENTITY_HANDLER_ASSERTION - Message("Deactivate Entity %d -> but does not exists <%u>\n", pEntity->entindex(), key); + Message("Deactivate Entity %d -> but does not exists <%u>\n", pEntity->entindex(), key); #endif - return false; - } + return false; + } - if (const auto pPlayer = it->second.GetPlayer()) - { - if ((pEntity->m_spawnflags() & CGameUI::SF_GAMEUI_FREEZE_PLAYER) != 0) - pPlayer->m_fFlags(pPlayer->m_fFlags() & ~FL_ATCONTROLS); + if (const auto pPlayer = it->second.GetPlayer()) + { + if ((pEntity->m_spawnflags() & CGameUI::SF_GAMEUI_FREEZE_PLAYER) != 0) + pPlayer->m_fFlags(pPlayer->m_fFlags() & ~FL_ATCONTROLS); - DelayInput(pEntity, pPlayer, "InValue", "PlayerOff"); + DelayInput(pEntity, pPlayer, "InValue", "PlayerOff"); #ifdef ENTITY_HANDLER_ASSERTION - Message("Deactivate Entity %d -> %s\n", pEntity->entindex(), pPlayer->GetController()->GetPlayerName()); + Message("Deactivate Entity %d -> %s\n", pEntity->entindex(), pPlayer->GetController()->GetPlayerName()); #endif - } - else - { + } + else + { #ifdef ENTITY_HANDLER_ASSERTION - Message("Deactivate Entity %d -> nullptr\n", pEntity->entindex()); + Message("Deactivate Entity %d -> nullptr\n", pEntity->entindex()); #endif - } + } - s_repository.erase(it); + s_repository.erase(it); - return true; -} + return true; + } } // namespace CGameUIHandler namespace CPointViewControlHandler { -struct ViewControl -{ - CUtlVector> m_players; - std::string m_viewTarget; - std::string m_name; -}; - -static std::unordered_map s_repository; -static constexpr uint INVALID_FOV = 0xFFFFFFFF; -static constexpr uint RESET_FOV = 0xFFFFFFFE; -static CHandle INVALID_HANDLE(0xFFFFFFFF); - -inline void UpdatePlayerState(CCSPlayerPawn* pPawn, const CHandle& target, bool frozen, uint fov = INVALID_FOV, bool disarm = false) -{ - if (!pPawn) - return; - - if (const auto pCameraService = pPawn->GetCameraService()) - { - pCameraService->m_hViewEntity(target); - pCameraService->m_hZoomOwner(INVALID_HANDLE); - - if (fov != INVALID_FOV) - { - if (const auto pController = pPawn->GetController()) - { - if (fov == RESET_FOV) - { - pCameraService->m_iFOV(pController->m_iDesiredFOV()); - } - else - { - pCameraService->m_iFOV(fov); - } - } - } - } - - if (disarm) - { - if (const auto pWeaponService = pPawn->m_pWeaponServices()) - { - if (const auto pActiveWeapon = pWeaponService->m_hActiveWeapon().Get()) - { - pActiveWeapon->Disarm(); - } - } - } - - auto flags = pPawn->m_fFlags(); - - if (g_pGameRules && g_pGameRules->m_bFreezePeriod()) - frozen = true; - - if (frozen) - { - flags |= FL_FROZEN; - } - else - { - flags &= ~FL_FROZEN; - } - - pPawn->m_fFlags(flags); -} - -void OnCreated(CBaseEntity* pEntity) -{ - const auto pViewControl = pEntity->AsPointViewControl(); - if (!pViewControl) - return; - - if (!pViewControl->HasTargetCameraEntity()) - { - Warning("PointViewControl %s has no target camera entity\n", pViewControl->GetName()); - return; - } - - ViewControl vc{}; - vc.m_viewTarget = pViewControl->m_target().String(); - vc.m_name = pViewControl->GetName(); - s_repository[pEntity->GetHandle().ToInt()] = vc; -} -bool OnEnable(CPointViewControl* pEntity, CBaseEntity* pActivator) -{ - if (!pActivator || !pActivator->IsPawn() || !pActivator->IsAlive()) - return false; - - const auto key = pEntity->GetHandle().ToInt(); - const auto it = s_repository.find(key); - if (it == s_repository.end()) - return false; - - const auto pPawn = reinterpret_cast(pActivator); - const auto pController = reinterpret_cast(pPawn->GetController()); - if (!pController) - return false; - - if (pController->IsBot() || pController->m_bIsHLTV()) - { - Warning("PointViewControl %s try enable for bot or HLTV: %s\n", it->second.m_name.c_str(), pController->GetPlayerName()); - return false; - } - - const auto handle = CHandle(pPawn->GetHandle()); - - for (auto& [vk, vc] : s_repository) - { - if (const auto index = vc.m_players.Find(handle); index > -1) - { - if (vk == static_cast(key)) - { - Warning("PointViewControl %s was enabled twice in a row! player: %s\n", vc.m_name.c_str(), pController->GetPlayerName()); - return false; - } - - vc.m_players.Remove(index); - UpdatePlayerState(pPawn, INVALID_HANDLE, false, RESET_FOV); - Warning("PointViewControl %s already enabled for %s\n", vc.m_name.c_str(), pController->GetPlayerName()); - break; - } - } - - return it->second.m_players.AddToTail(handle) >= 0; -} -bool OnDisable(CPointViewControl* pEntity, CBaseEntity* pActivator) -{ - if (!pActivator || !pActivator->IsPawn() || !pActivator->IsAlive()) - return false; - - const auto key = pEntity->GetHandle().ToInt(); - const auto it = s_repository.find(key); - if (it == s_repository.end()) - return false; - - const auto pPawn = reinterpret_cast(pActivator); - const auto pController = reinterpret_cast(pPawn->GetController()); - if (!pController) - return false; - - if (pController->IsBot() || pController->m_bIsHLTV()) - { - Warning("PointViewControl %s try disable for bot or HLTV: %s\n", it->second.m_name.c_str(), pController->GetPlayerName()); - return false; - } - - const auto handle = CHandle(pPawn->GetHandle()); - - UpdatePlayerState(pPawn, INVALID_HANDLE, false, RESET_FOV); - - return it->second.m_players.FindAndRemove(handle); -} -bool OnEnableAll(CPointViewControl* pEntity) -{ - const auto key = pEntity->GetHandle().ToInt(); - const auto it = s_repository.find(key); - if (it == s_repository.end()) - return false; - - for (auto i = 0; i < gpGlobals->maxClients; i++) - { - const auto pController = CCSPlayerController::FromSlot(i); - if (!pController || !pController->IsConnected() || pController->IsBot() || pController->m_bIsHLTV()) - continue; - - const auto pPawn = pController->GetPlayerPawn(); - if (!pPawn || !pPawn->IsAlive()) - continue; - - const auto handle = CHandle(pPawn->GetHandle()); - - for (auto& [vk, vc] : s_repository) - { - if (const auto index = vc.m_players.Find(handle); index > -1) - { - vc.m_players.Remove(index); - if (vk == static_cast(key)) - { - continue; - } - UpdatePlayerState(pPawn, INVALID_HANDLE, false, RESET_FOV); - Warning("PointViewControl %s already enabled for %s\n", vc.m_name.c_str(), pController->GetPlayerName()); - } - } - - it->second.m_players.AddToTail(handle); - } - - return true; -} -bool OnDisableAll(CPointViewControl* pEntity) -{ - const auto key = pEntity->GetHandle().ToInt(); - const auto it = s_repository.find(key); - if (it == s_repository.end()) - return false; - - FOR_EACH_VEC(it->second.m_players, i) - { - const auto& handle = it->second.m_players.Element(i); - - if (const auto player = handle.Get()) - UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); - } - - it->second.m_players.Purge(); - - return true; -} - -void RunThink(int tick) -{ - // validate - for (auto it = s_repository.begin(); it != s_repository.end();) - { - const auto entity = CHandle(it->first).Get(); - if (!entity) - { - FOR_EACH_VEC(it->second.m_players, i) - { - const auto& handle = it->second.m_players.Element(i); - - if (const auto player = handle.Get()) - UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); - } - - it = s_repository.erase(it); - } - else - { - ++it; - } - } - - // think every tick - - for (auto& [vk, vc] : s_repository) - { - const auto entity = CHandle(vk).Get(); - if (!entity) - { - Error("Why invalid entity here?"); - continue; - } - - if (vc.m_players.Count() == 0) - continue; - - const auto pTarget = entity->GetTargetCameraEntity(); - if (!pTarget) - { - FOR_EACH_VEC(vc.m_players, i) - { - const auto& handle = vc.m_players.Element(i); - - if (const auto player = handle.Get()) - UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); - } - vc.m_players.Purge(); - continue; - } - - FOR_EACH_VEC(vc.m_players, i) - { - const auto& handle = vc.m_players.Element(i); - const auto player = handle.Get(); - if (!player) - { - vc.m_players.Remove(i--); - continue; - } - if (!player->IsAlive()) - { - UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); - vc.m_players.Remove(i--); - continue; - } - - UpdatePlayerState(player, pTarget->GetHandle(), entity->HasFrozen(), entity->HasFOV() ? entity->GetFOV() : INVALID_FOV, entity->HasDisarm()); - } - } -} -bool IsViewControl(CCSPlayerPawn* pPawn) -{ - const auto handle = pPawn->GetHandle().ToInt(); - for (const auto& [vk, vc] : s_repository) - { - FOR_EACH_VEC(vc.m_players, i) - { - if (vc.m_players.Element(i).ToInt() == handle) - return true; - } - } - return false; -} -void Shutdown() -{ - for (auto& [vk, vc] : s_repository) - { - FOR_EACH_VEC(vc.m_players, i) - { - const auto& handle = vc.m_players.Element(i); - - if (const auto player = handle.Get()) - UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); - } - vc.m_players.Purge(); - } - s_repository.clear(); -} + struct ViewControl + { + CUtlVector> m_players; + std::string m_viewTarget; + std::string m_name; + }; + + static std::unordered_map s_repository; + static constexpr uint INVALID_FOV = 0xFFFFFFFF; + static constexpr uint RESET_FOV = 0xFFFFFFFE; + static CHandle INVALID_HANDLE(0xFFFFFFFF); + + inline void UpdatePlayerState(CCSPlayerPawn* pPawn, const CHandle& target, bool frozen, uint fov = INVALID_FOV, bool disarm = false) + { + if (!pPawn) + return; + + if (const auto pCameraService = pPawn->GetCameraService()) + { + pCameraService->m_hViewEntity(target); + pCameraService->m_hZoomOwner(INVALID_HANDLE); + + if (fov != INVALID_FOV) + { + if (const auto pController = pPawn->GetController()) + { + if (fov == RESET_FOV) + pCameraService->m_iFOV(pController->m_iDesiredFOV()); + else + pCameraService->m_iFOV(fov); + } + } + } + + if (disarm) + { + if (const auto pWeaponService = pPawn->m_pWeaponServices()) + { + if (const auto pActiveWeapon = pWeaponService->m_hActiveWeapon().Get()) + pActiveWeapon->Disarm(); + } + } + + auto flags = pPawn->m_fFlags(); + + if (g_pGameRules && g_pGameRules->m_bFreezePeriod()) + frozen = true; + + if (frozen) + flags |= FL_FROZEN; + else + flags &= ~FL_FROZEN; + + pPawn->m_fFlags(flags); + } + + void OnCreated(CBaseEntity* pEntity) + { + const auto pViewControl = pEntity->AsPointViewControl(); + if (!pViewControl) + return; + + if (!pViewControl->HasTargetCameraEntity()) + { + Warning("PointViewControl %s has no target camera entity\n", pViewControl->GetName()); + return; + } + + ViewControl vc{}; + vc.m_viewTarget = pViewControl->m_target().String(); + vc.m_name = pViewControl->GetName(); + s_repository[pEntity->GetHandle().ToInt()] = vc; + } + bool OnEnable(CPointViewControl* pEntity, CBaseEntity* pActivator) + { + if (!pActivator || !pActivator->IsPawn() || !pActivator->IsAlive()) + return false; + + const auto key = pEntity->GetHandle().ToInt(); + const auto it = s_repository.find(key); + if (it == s_repository.end()) + return false; + + const auto pPawn = reinterpret_cast(pActivator); + const auto pController = reinterpret_cast(pPawn->GetController()); + if (!pController) + return false; + + if (pController->IsBot() || pController->m_bIsHLTV()) + { + Warning("PointViewControl %s try enable for bot or HLTV: %s\n", it->second.m_name.c_str(), pController->GetPlayerName()); + return false; + } + + const auto handle = CHandle(pPawn->GetHandle()); + + for (auto& [vk, vc] : s_repository) + { + if (const auto index = vc.m_players.Find(handle); index > -1) + { + if (vk == static_cast(key)) + { + Warning("PointViewControl %s was enabled twice in a row! player: %s\n", vc.m_name.c_str(), pController->GetPlayerName()); + return false; + } + + vc.m_players.Remove(index); + UpdatePlayerState(pPawn, INVALID_HANDLE, false, RESET_FOV); + Warning("PointViewControl %s already enabled for %s\n", vc.m_name.c_str(), pController->GetPlayerName()); + break; + } + } + + return it->second.m_players.AddToTail(handle) >= 0; + } + bool OnDisable(CPointViewControl* pEntity, CBaseEntity* pActivator) + { + if (!pActivator || !pActivator->IsPawn() || !pActivator->IsAlive()) + return false; + + const auto key = pEntity->GetHandle().ToInt(); + const auto it = s_repository.find(key); + if (it == s_repository.end()) + return false; + + const auto pPawn = reinterpret_cast(pActivator); + const auto pController = reinterpret_cast(pPawn->GetController()); + if (!pController) + return false; + + if (pController->IsBot() || pController->m_bIsHLTV()) + { + Warning("PointViewControl %s try disable for bot or HLTV: %s\n", it->second.m_name.c_str(), pController->GetPlayerName()); + return false; + } + + const auto handle = CHandle(pPawn->GetHandle()); + + UpdatePlayerState(pPawn, INVALID_HANDLE, false, RESET_FOV); + + return it->second.m_players.FindAndRemove(handle); + } + bool OnEnableAll(CPointViewControl* pEntity) + { + const auto key = pEntity->GetHandle().ToInt(); + const auto it = s_repository.find(key); + if (it == s_repository.end()) + return false; + + for (auto i = 0; i < gpGlobals->maxClients; i++) + { + const auto pController = CCSPlayerController::FromSlot(i); + if (!pController || !pController->IsConnected() || pController->IsBot() || pController->m_bIsHLTV()) + continue; + + const auto pPawn = pController->GetPlayerPawn(); + if (!pPawn || !pPawn->IsAlive()) + continue; + + const auto handle = CHandle(pPawn->GetHandle()); + + for (auto& [vk, vc] : s_repository) + { + if (const auto index = vc.m_players.Find(handle); index > -1) + { + vc.m_players.Remove(index); + if (vk == static_cast(key)) + continue; + UpdatePlayerState(pPawn, INVALID_HANDLE, false, RESET_FOV); + Warning("PointViewControl %s already enabled for %s\n", vc.m_name.c_str(), pController->GetPlayerName()); + } + } + + it->second.m_players.AddToTail(handle); + } + + return true; + } + bool OnDisableAll(CPointViewControl* pEntity) + { + const auto key = pEntity->GetHandle().ToInt(); + const auto it = s_repository.find(key); + if (it == s_repository.end()) + return false; + + FOR_EACH_VEC(it->second.m_players, i) + { + const auto& handle = it->second.m_players.Element(i); + + if (const auto player = handle.Get()) + UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); + } + + it->second.m_players.Purge(); + + return true; + } + + void RunThink(int tick) + { + // validate + for (auto it = s_repository.begin(); it != s_repository.end();) + { + const auto entity = CHandle(it->first).Get(); + if (!entity) + { + FOR_EACH_VEC(it->second.m_players, i) + { + const auto& handle = it->second.m_players.Element(i); + + if (const auto player = handle.Get()) + UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); + } + + it = s_repository.erase(it); + } + else + { + ++it; + } + } + + // think every tick + + for (auto& [vk, vc] : s_repository) + { + const auto entity = CHandle(vk).Get(); + if (!entity) + { + Error("Why invalid entity here?"); + continue; + } + + if (vc.m_players.Count() == 0) + continue; + + const auto pTarget = entity->GetTargetCameraEntity(); + if (!pTarget) + { + FOR_EACH_VEC(vc.m_players, i) + { + const auto& handle = vc.m_players.Element(i); + + if (const auto player = handle.Get()) + UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); + } + vc.m_players.Purge(); + continue; + } + + FOR_EACH_VEC(vc.m_players, i) + { + const auto& handle = vc.m_players.Element(i); + const auto player = handle.Get(); + if (!player) + { + vc.m_players.Remove(i--); + continue; + } + if (!player->IsAlive()) + { + UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); + vc.m_players.Remove(i--); + continue; + } + + UpdatePlayerState(player, pTarget->GetHandle(), entity->HasFrozen(), entity->HasFOV() ? entity->GetFOV() : INVALID_FOV, entity->HasDisarm()); + } + } + } + bool IsViewControl(CCSPlayerPawn* pPawn) + { + const auto handle = pPawn->GetHandle().ToInt(); + for (const auto& [vk, vc] : s_repository) + { + FOR_EACH_VEC(vc.m_players, i) + { + if (vc.m_players.Element(i).ToInt() == handle) + return true; + } + } + return false; + } + void Shutdown() + { + for (auto& [vk, vc] : s_repository) + { + FOR_EACH_VEC(vc.m_players, i) + { + const auto& handle = vc.m_players.Element(i); + + if (const auto player = handle.Get()) + UpdatePlayerState(player, INVALID_HANDLE, false, RESET_FOV); + } + vc.m_players.Purge(); + } + s_repository.clear(); + } } // namespace CPointViewControlHandler void EntityHandler_OnGameFramePre(bool simulate, int tick) { - if (!simulate) - return; + if (!simulate) + return; - CGameUIHandler::RunThink(tick); - CPointViewControlHandler::RunThink(tick); + CGameUIHandler::RunThink(tick); + CPointViewControlHandler::RunThink(tick); } void EntityHandler_OnGameFramePost(bool simulate, int tick) { - if (!simulate) - return; + if (!simulate) + return; } void EntityHandler_OnRoundRestart() { - CPointViewControlHandler::Shutdown(); + CPointViewControlHandler::Shutdown(); } void EntityHandler_OnEntitySpawned(CBaseEntity* pEntity) { - CPointViewControlHandler::OnCreated(pEntity); + CPointViewControlHandler::OnCreated(pEntity); } \ No newline at end of file diff --git a/src/entities.h b/src/entities.h index 07fad8f9..e0477cf9 100644 --- a/src/entities.h +++ b/src/entities.h @@ -28,25 +28,25 @@ class CCSPlayerPawn; namespace CGamePlayerEquipHandler { -void Use(CGamePlayerEquip* pEntity, InputData_t* pInput); -void TriggerForAllPlayers(CGamePlayerEquip* pEntity, InputData_t* pInput); -bool TriggerForActivatedPlayer(CGamePlayerEquip* pEntity, InputData_t* pInput); + void Use(CGamePlayerEquip* pEntity, InputData_t* pInput); + void TriggerForAllPlayers(CGamePlayerEquip* pEntity, InputData_t* pInput); + bool TriggerForActivatedPlayer(CGamePlayerEquip* pEntity, InputData_t* pInput); } // namespace CGamePlayerEquipHandler namespace CGameUIHandler { -bool OnActivate(CGameUI* pEntity, CBaseEntity* pActivator); -bool OnDeactivate(CGameUI* pEntity, CBaseEntity* pActivator); -void RunThink(int tick); + bool OnActivate(CGameUI* pEntity, CBaseEntity* pActivator); + bool OnDeactivate(CGameUI* pEntity, CBaseEntity* pActivator); + void RunThink(int tick); } // namespace CGameUIHandler namespace CPointViewControlHandler { -bool OnEnable(CPointViewControl* pEntity, CBaseEntity* pActivator); -bool OnDisable(CPointViewControl* pEntity, CBaseEntity* pActivator); -bool OnEnableAll(CPointViewControl* pEntity); -bool OnDisableAll(CPointViewControl* pEntity); -bool IsViewControl(CCSPlayerPawn*); + bool OnEnable(CPointViewControl* pEntity, CBaseEntity* pActivator); + bool OnDisable(CPointViewControl* pEntity, CBaseEntity* pActivator); + bool OnEnableAll(CPointViewControl* pEntity); + bool OnDisableAll(CPointViewControl* pEntity); + bool IsViewControl(CCSPlayerPawn*); } // namespace CPointViewControlHandler void EntityHandler_OnGameFramePre(bool simulate, int tick); diff --git a/src/entitylistener.cpp b/src/entitylistener.cpp index 4cc4df6f..912c93de 100644 --- a/src/entitylistener.cpp +++ b/src/entitylistener.cpp @@ -26,16 +26,16 @@ #include "gameconfig.h" #include "plat.h" -extern CGameConfig *g_GameConfig; +extern CGameConfig* g_GameConfig; extern CCSGameRules* g_pGameRules; bool g_bGrenadeNoBlock = false; FAKE_BOOL_CVAR(cs2f_noblock_grenades, "Whether to use noblock on grenade projectiles", g_bGrenadeNoBlock, false, false) -void Patch_GetHammerUniqueId(CEntityInstance *pEntity) +void Patch_GetHammerUniqueId(CEntityInstance* pEntity) { static int offset = g_GameConfig->GetOffset("GetHammerUniqueId"); - void **vtable = *(void ***)pEntity; + void** vtable = *(void***)pEntity; // xor al, al -> mov al, 1 // so it always returns true and allows hammerid to be copied into the schema prop @@ -50,9 +50,7 @@ void CEntityListener::OnEntitySpawned(CEntityInstance* pEntity) #endif if (g_bGrenadeNoBlock && V_stristr(pEntity->GetClassname(), "_projectile")) - { reinterpret_cast(pEntity)->SetCollisionGroup(COLLISION_GROUP_DEBRIS); - } EntityHandler_OnEntitySpawned(reinterpret_cast(pEntity)); } diff --git a/src/entitylistener.h b/src/entitylistener.h index 77eb53dd..275de2ff 100644 --- a/src/entitylistener.h +++ b/src/entitylistener.h @@ -24,8 +24,8 @@ extern CGameEntitySystem* g_pEntitySystem; class CEntityListener : public IEntityListener { - void OnEntitySpawned(CEntityInstance* pEntity) override; - void OnEntityCreated(CEntityInstance* pEntity) override; - void OnEntityDeleted(CEntityInstance* pEntity) override; - void OnEntityParentChanged(CEntityInstance* pEntity, CEntityInstance* pNewParent) override; + void OnEntitySpawned(CEntityInstance* pEntity) override; + void OnEntityCreated(CEntityInstance* pEntity) override; + void OnEntityDeleted(CEntityInstance* pEntity) override; + void OnEntityParentChanged(CEntityInstance* pEntity, CEntityInstance* pNewParent) override; }; \ No newline at end of file diff --git a/src/eventlistener.h b/src/eventlistener.h index 1d7c612a..5df05671 100644 --- a/src/eventlistener.h +++ b/src/eventlistener.h @@ -19,20 +19,21 @@ #pragma once #include "common.h" +#include "igameevents.h" #include "utlstring.h" #include "utlvector.h" -#include "igameevents.h" -typedef void (*FnEventListenerCallback)(IGameEvent *event); +typedef void (*FnEventListenerCallback)(IGameEvent* event); class CGameEventListener; -extern CUtlVector g_vecEventListeners; +extern CUtlVector g_vecEventListeners; class CGameEventListener : public IGameEventListener2 { public: - CGameEventListener(FnEventListenerCallback callback, const char *pszEventName) : m_Callback(callback), m_pszEventName(pszEventName) + CGameEventListener(FnEventListenerCallback callback, const char* pszEventName) : + m_Callback(callback), m_pszEventName(pszEventName) { g_vecEventListeners.AddToTail(this); } @@ -43,22 +44,22 @@ class CGameEventListener : public IGameEventListener2 // FireEvent is called by EventManager if event just occured // KeyValue memory will be freed by manager if not needed anymore - void FireGameEvent(IGameEvent *event) override + void FireGameEvent(IGameEvent* event) override { m_Callback(event); } - const char *GetEventName() { return m_pszEventName; } + const char* GetEventName() { return m_pszEventName; } private: FnEventListenerCallback m_Callback; - const char *m_pszEventName; + const char* m_pszEventName; }; void RegisterEventListeners(); void UnregisterEventListeners(); -#define GAME_EVENT_F(_event) \ - void _event##_callback(IGameEvent*); \ - CGameEventListener _event##_listener(_event##_callback, #_event); \ - void _event##_callback(IGameEvent *pEvent) \ No newline at end of file +#define GAME_EVENT_F(_event) \ + void _event##_callback(IGameEvent*); \ + CGameEventListener _event##_listener(_event##_callback, #_event); \ + void _event##_callback(IGameEvent* pEvent) \ No newline at end of file diff --git a/src/events.cpp b/src/events.cpp index c494c79b..f6204d32 100644 --- a/src/events.cpp +++ b/src/events.cpp @@ -17,33 +17,33 @@ * this program. If not, see . */ -#include "common.h" #include "KeyValues.h" #include "commands.h" +#include "common.h" #include "ctimer.h" #include "entities.h" -#include "eventlistener.h" -#include "networkstringtabledefs.h" #include "entity/cbaseplayercontroller.h" #include "entity/cgamerules.h" -#include "zombiereborn.h" -#include "votemanager.h" +#include "eventlistener.h" #include "leader.h" -#include "recipientfilters.h" +#include "networkstringtabledefs.h" #include "panoramavote.h" +#include "recipientfilters.h" +#include "votemanager.h" +#include "zombiereborn.h" #include "tier0/memdbgon.h" -extern IGameEventManager2 *g_gameEventManager; -extern IServerGameClients *g_pSource2GameClients; -extern CGameEntitySystem *g_pEntitySystem; -extern CGlobalVars *gpGlobals; -extern CCSGameRules *g_pGameRules; +extern IGameEventManager2* g_gameEventManager; +extern IServerGameClients* g_pSource2GameClients; +extern CGameEntitySystem* g_pEntitySystem; +extern CGlobalVars* gpGlobals; +extern CCSGameRules* g_pGameRules; extern IVEngineServer2* g_pEngineServer2; extern int g_iRoundNum; -CUtlVector g_vecEventListeners; +CUtlVector g_vecEventListeners; void RegisterEventListeners() { @@ -84,7 +84,7 @@ GAME_EVENT_F(round_prestart) if (g_bPurgeEntityNames) { - INetworkStringTable *pEntityNames = g_pNetworkStringTableServer->FindTable("EntityNames"); + INetworkStringTable* pEntityNames = g_pNetworkStringTableServer->FindTable("EntityNames"); if (pEntityNames) { @@ -95,9 +95,9 @@ GAME_EVENT_F(round_prestart) // Vauff: Not fixing cubemap fog in my testing // This also breaks round start particle resets, so disabling for now - //pEntityNames->SetTick(-1, nullptr); + // pEntityNames->SetTick(-1, nullptr); - //FullUpdateAllClients(); + // FullUpdateAllClients(); } } @@ -130,7 +130,7 @@ FAKE_BOOL_CVAR(cs2f_noblock_enable, "Whether to use player noblock, which sets d GAME_EVENT_F(player_spawn) { - CCSPlayerController *pController = (CCSPlayerController *)pEvent->GetPlayerController("userid"); + CCSPlayerController* pController = (CCSPlayerController*)pEvent->GetPlayerController("userid"); if (!pController) return; @@ -150,9 +150,8 @@ GAME_EVENT_F(player_spawn) CHandle hController = pController->GetHandle(); // Gotta do this on the next frame... - new CTimer(0.0f, false, false, [hController]() - { - CCSPlayerController *pController = hController.Get(); + new CTimer(0.0f, false, false, [hController]() { + CCSPlayerController* pController = hController.Get(); if (!pController) return -1.0f; @@ -163,7 +162,7 @@ GAME_EVENT_F(player_spawn) if (!pController->m_bPawnIsAlive()) return -1.0f; - CBasePlayerPawn *pPawn = pController->GetPawn(); + CBasePlayerPawn* pPawn = pController->GetPawn(); // Just in case somehow there's health but the player is, say, an observer if (!g_bNoblock || !pPawn || !pPawn->IsAlive()) @@ -175,8 +174,7 @@ GAME_EVENT_F(player_spawn) }); // And this needs even more delay..? Don't even know if this is enough, bug can't be reproduced - new CTimer(0.1f, false, false, [hController]() - { + new CTimer(0.1f, false, false, [hController]() { CCSPlayerController* pController = hController.Get(); if (!pController) @@ -207,8 +205,8 @@ GAME_EVENT_F(player_hurt) if (!g_bEnableTopDefender) return; - CCSPlayerController *pAttacker = (CCSPlayerController*)pEvent->GetPlayerController("attacker"); - CCSPlayerController *pVictim = (CCSPlayerController*)pEvent->GetPlayerController("userid"); + CCSPlayerController* pAttacker = (CCSPlayerController*)pEvent->GetPlayerController("attacker"); + CCSPlayerController* pVictim = (CCSPlayerController*)pEvent->GetPlayerController("userid"); // Ignore Ts/zombies and CTs hurting themselves if (!pAttacker || pAttacker->m_iTeamNum() != CS_TEAM_CT || pAttacker->m_iTeamNum() == pVictim->m_iTeamNum()) @@ -231,10 +229,10 @@ GAME_EVENT_F(player_death) if (!g_bEnableTopDefender) return; - CCSPlayerController *pAttacker = (CCSPlayerController*)pEvent->GetPlayerController("attacker"); - CCSPlayerController *pVictim = (CCSPlayerController*)pEvent->GetPlayerController("userid"); - - //Ignore Ts/zombie kills and ignore CT teamkilling or suicide + CCSPlayerController* pAttacker = (CCSPlayerController*)pEvent->GetPlayerController("attacker"); + CCSPlayerController* pVictim = (CCSPlayerController*)pEvent->GetPlayerController("userid"); + + // Ignore Ts/zombie kills and ignore CT teamkilling or suicide if (!pAttacker || !pVictim || pAttacker->m_iTeamNum != CS_TEAM_CT || pAttacker->m_iTeamNum == pVictim->m_iTeamNum) return; @@ -287,9 +285,9 @@ GAME_EVENT_F(round_end) // CONVAR_TODO // HACK: values is actually the cvar value itself, hence this ugly cast. - float flTimelimit = *(float *)&cvar->values; + float flTimelimit = *(float*)&cvar->values; - int iTimeleft = (int) ((g_pGameRules->m_flGameStartTime + flTimelimit * 60.0f) - gpGlobals->curtime); + int iTimeleft = (int)((g_pGameRules->m_flGameStartTime + flTimelimit * 60.0f) - gpGlobals->curtime); // check for end of last round if (iTimeleft <= 0) @@ -302,7 +300,7 @@ GAME_EVENT_F(round_end) if (!g_bEnableTopDefender) return; - CUtlVector sortedPlayers; + CUtlVector sortedPlayers; for (int i = 0; i < gpGlobals->maxClients; i++) { @@ -313,7 +311,7 @@ GAME_EVENT_F(round_end) CCSPlayerController* pController = CCSPlayerController::FromSlot(pPlayer->GetPlayerSlot()); - if(!pController) + if (!pController) continue; sortedPlayers.AddToTail(pPlayer); @@ -322,14 +320,13 @@ GAME_EVENT_F(round_end) if (sortedPlayers.Count() == 0) return; - sortedPlayers.Sort([](ZEPlayer *const *a, ZEPlayer *const *b) -> int - { + sortedPlayers.Sort([](ZEPlayer* const* a, ZEPlayer* const* b) -> int { return (*a)->GetTotalDamage() < (*b)->GetTotalDamage(); }); ClientPrintAll(HUD_PRINTTALK, " \x09TOP DEFENDERS"); - char colorMap[] = { '\x10', '\x08', '\x09', '\x0B'}; + char colorMap[] = {'\x10', '\x08', '\x09', '\x0B'}; for (int i = 0; i < sortedPlayers.Count(); i++) { @@ -340,7 +337,7 @@ GAME_EVENT_F(round_end) ClientPrintAll(HUD_PRINTTALK, " %c%i. %s \x01- \x07%i DMG \x05(%i HITS & %i KILLS)", colorMap[MIN(i, 3)], i + 1, pController->GetPlayerName(), pPlayer->GetTotalDamage(), pPlayer->GetTotalHits(), pPlayer->GetTotalKills()); else ClientPrint(pController, HUD_PRINTTALK, " \x0C%i. %s \x01- \x07%i DMG \x05(%i HITS & %i KILLS)", i + 1, pController->GetPlayerName(), pPlayer->GetTotalDamage(), pPlayer->GetTotalHits(), pPlayer->GetTotalKills()); - + pPlayer->SetTotalDamage(0); pPlayer->SetTotalHits(0); pPlayer->SetTotalKills(0); diff --git a/src/gameconfig.cpp b/src/gameconfig.cpp index 13203cbd..f60fe575 100644 --- a/src/gameconfig.cpp +++ b/src/gameconfig.cpp @@ -13,7 +13,7 @@ CGameConfig::~CGameConfig() delete m_pKeyValues; } -bool CGameConfig::Init(IFileSystem *filesystem, char *conf_error, int conf_error_size) +bool CGameConfig::Init(IFileSystem* filesystem, char* conf_error, int conf_error_size) { if (!m_pKeyValues->LoadFromFile(filesystem, m_szPath.c_str(), nullptr)) { @@ -39,7 +39,7 @@ bool CGameConfig::Init(IFileSystem *filesystem, char *conf_error, int conf_error } } - KeyValues *signatures = game->FindKey("Signatures", false); + KeyValues* signatures = game->FindKey("Signatures", false); if (signatures) { FOR_EACH_SUBKEY(signatures, it) @@ -49,7 +49,7 @@ bool CGameConfig::Init(IFileSystem *filesystem, char *conf_error, int conf_error } } - KeyValues *patches = game->FindKey("Patches", false); + KeyValues* patches = game->FindKey("Patches", false); if (patches) { FOR_EACH_SUBKEY(patches, it) @@ -71,23 +71,19 @@ const std::string CGameConfig::GetPath() return m_szPath; } -const char *CGameConfig::GetSignature(const std::string& name) +const char* CGameConfig::GetSignature(const std::string& name) { auto it = m_umSignatures.find(name); if (it == m_umSignatures.end()) - { return nullptr; - } return it->second.c_str(); } -const char *CGameConfig::GetPatch(const std::string& name) +const char* CGameConfig::GetPatch(const std::string& name) { auto it = m_umPatches.find(name); if (it == m_umPatches.end()) - { return nullptr; - } return it->second.c_str(); } @@ -95,25 +91,21 @@ int CGameConfig::GetOffset(const std::string& name) { auto it = m_umOffsets.find(name); if (it == m_umOffsets.end()) - { return -1; - } return it->second; } -const char *CGameConfig::GetLibrary(const std::string& name) +const char* CGameConfig::GetLibrary(const std::string& name) { auto it = m_umLibraries.find(name); if (it == m_umLibraries.end()) - { return nullptr; - } return it->second.c_str(); } -CModule **CGameConfig::GetModule(const char *name) +CModule** CGameConfig::GetModule(const char* name) { - const char *library = this->GetLibrary(name); + const char* library = this->GetLibrary(name); if (!library) return nullptr; @@ -138,9 +130,9 @@ CModule **CGameConfig::GetModule(const char *name) return nullptr; } -bool CGameConfig::IsSymbol(const char *name) +bool CGameConfig::IsSymbol(const char* name) { - const char *sigOrSymbol = this->GetSignature(name); + const char* sigOrSymbol = this->GetSignature(name); if (!sigOrSymbol || strlen(sigOrSymbol) <= 0) { Panic("Missing signature or symbol\n", name); @@ -149,9 +141,9 @@ bool CGameConfig::IsSymbol(const char *name) return sigOrSymbol[0] == '@'; } -const char* CGameConfig::GetSymbol(const char *name) +const char* CGameConfig::GetSymbol(const char* name) { - const char *symbol = this->GetSignature(name); + const char* symbol = this->GetSignature(name); if (!symbol || strlen(symbol) <= 1) { @@ -161,19 +153,19 @@ const char* CGameConfig::GetSymbol(const char *name) return symbol + 1; } -void *CGameConfig::ResolveSignature(const char *name) +void* CGameConfig::ResolveSignature(const char* name) { - CModule **module = this->GetModule(name); + CModule** module = this->GetModule(name); if (!module || !(*module)) { Panic("Invalid Module %s\n", name); return nullptr; } - void *address = nullptr; + void* address = nullptr; if (this->IsSymbol(name)) { - const char *symbol = this->GetSymbol(name); + const char* symbol = this->GetSymbol(name); if (!symbol) { Panic("Invalid symbol for %s\n", name); @@ -183,7 +175,7 @@ void *CGameConfig::ResolveSignature(const char *name) } else { - const char *signature = this->GetSignature(name); + const char* signature = this->GetSignature(name); if (!signature) { Panic("Failed to find signature for %s\n", name); @@ -191,7 +183,7 @@ void *CGameConfig::ResolveSignature(const char *name) } size_t iLength = 0; - byte *pSignature = HexToByte(signature, iLength); + byte* pSignature = HexToByte(signature, iLength); if (!pSignature) return nullptr; @@ -212,44 +204,46 @@ void *CGameConfig::ResolveSignature(const char *name) } // Static functions -std::string CGameConfig::GetDirectoryName(const std::string &directoryPathInput) +std::string CGameConfig::GetDirectoryName(const std::string& directoryPathInput) { - std::string directoryPath = std::string(directoryPathInput); - - size_t found = std::string(directoryPath).find_last_of("/\\"); - if (found != std::string::npos) - { - return std::string(directoryPath, found + 1); - } - return ""; + std::string directoryPath = std::string(directoryPathInput); + + size_t found = std::string(directoryPath).find_last_of("/\\"); + if (found != std::string::npos) + return std::string(directoryPath, found + 1); + return ""; } int CGameConfig::HexStringToUint8Array(const char* hexString, uint8_t* byteArray, size_t maxBytes) { - if (!hexString) { - printf("Invalid hex string.\n"); + if (!hexString) + { + printf("Invalid hex string.\n"); return -1; } - size_t hexStringLength = strlen(hexString); - size_t byteCount = hexStringLength / 4; // Each "\\x" represents one byte. + size_t hexStringLength = strlen(hexString); + size_t byteCount = hexStringLength / 4; // Each "\\x" represents one byte. - if (hexStringLength % 4 != 0 || byteCount == 0 || byteCount > maxBytes) { - printf("Invalid hex string format or byte count.\n"); - return -1; // Return an error code. - } + if (hexStringLength % 4 != 0 || byteCount == 0 || byteCount > maxBytes) + { + printf("Invalid hex string format or byte count.\n"); + return -1; // Return an error code. + } - for (size_t i = 0; i < hexStringLength; i += 4) { - if (sscanf(hexString + i, "\\x%2hhX", &byteArray[i / 4]) != 1) { - printf("Failed to parse hex string at position %zu.\n", i); - return -1; // Return an error code. - } - } + for (size_t i = 0; i < hexStringLength; i += 4) + { + if (sscanf(hexString + i, "\\x%2hhX", &byteArray[i / 4]) != 1) + { + printf("Failed to parse hex string at position %zu.\n", i); + return -1; // Return an error code. + } + } - return byteCount; // Return the number of bytes successfully converted. + return byteCount; // Return the number of bytes successfully converted. } -byte *CGameConfig::HexToByte(const char *src, size_t &length) +byte* CGameConfig::HexToByte(const char* src, size_t& length) { if (!src || strlen(src) <= 0) { @@ -258,12 +252,12 @@ byte *CGameConfig::HexToByte(const char *src, size_t &length) } length = strlen(src) / 4; - uint8_t *dest = new uint8_t[length]; + uint8_t* dest = new uint8_t[length]; int byteCount = HexStringToUint8Array(src, dest, length); if (byteCount <= 0) { Panic("Invalid hex format %s\n", src); return nullptr; } - return (byte *)dest; + return (byte*)dest; } diff --git a/src/gameconfig.h b/src/gameconfig.h index a6747154..f6085ae7 100644 --- a/src/gameconfig.h +++ b/src/gameconfig.h @@ -14,20 +14,20 @@ class CGameConfig CGameConfig(const std::string& gameDir, const std::string& path); ~CGameConfig(); - bool Init(IFileSystem *filesystem, char *conf_error, int conf_error_size); + bool Init(IFileSystem* filesystem, char* conf_error, int conf_error_size); const std::string GetPath(); - const char *GetLibrary(const std::string& name); - const char *GetSignature(const std::string& name); - const char* GetSymbol(const char *name); - const char *GetPatch(const std::string& name); + const char* GetLibrary(const std::string& name); + const char* GetSignature(const std::string& name); + const char* GetSymbol(const char* name); + const char* GetPatch(const std::string& name); int GetOffset(const std::string& name); - void* GetAddress(const std::string& name, void *engine, void *server, char *error, int maxlen); - CModule **GetModule(const char *name); - bool IsSymbol(const char *name); - void *ResolveSignature(const char *name); - static std::string GetDirectoryName(const std::string &directoryPathInput); + void* GetAddress(const std::string& name, void* engine, void* server, char* error, int maxlen); + CModule** GetModule(const char* name); + bool IsSymbol(const char* name); + void* ResolveSignature(const char* name); + static std::string GetDirectoryName(const std::string& directoryPathInput); static int HexStringToUint8Array(const char* hexString, uint8_t* byteArray, size_t maxBytes); - static byte *HexToByte(const char *src, size_t &length); + static byte* HexToByte(const char* src, size_t& length); private: std::string m_szGameDir; diff --git a/src/gamesystem.cpp b/src/gamesystem.cpp index 28884660..3f01b144 100644 --- a/src/gamesystem.cpp +++ b/src/gamesystem.cpp @@ -17,33 +17,33 @@ * this program. If not, see . */ -#include "common.h" -#include "gameconfig.h" -#include "addresses.h" #include "gamesystem.h" -#include "zombiereborn.h" -#include "playermanager.h" -#include "leader.h" +#include "addresses.h" #include "adminsystem.h" +#include "common.h" #include "entities.h" -#include "tier0/vprof.h" +#include "gameconfig.h" #include "idlemanager.h" +#include "leader.h" +#include "playermanager.h" +#include "tier0/vprof.h" +#include "zombiereborn.h" #include "tier0/memdbgon.h" extern CGlobalVars* gpGlobals; -extern CGameConfig *g_GameConfig; +extern CGameConfig* g_GameConfig; -CBaseGameSystemFactory **CBaseGameSystemFactory::sm_pFirst = nullptr; +CBaseGameSystemFactory** CBaseGameSystemFactory::sm_pFirst = nullptr; CGameSystem g_GameSystem; -IGameSystemFactory *CGameSystem::sm_Factory = nullptr; +IGameSystemFactory* CGameSystem::sm_Factory = nullptr; // This mess is needed to get the pointer to sm_pFirst so we can insert game systems bool InitGameSystems() { // This signature directly points to the instruction referencing sm_pFirst, and the opcode is 3 bytes so we skip those - uint8 *ptr = (uint8*)g_GameConfig->ResolveSignature("IGameSystem_InitAllSystems_pFirst") + 3; + uint8* ptr = (uint8*)g_GameConfig->ResolveSignature("IGameSystem_InitAllSystems_pFirst") + 3; if (!ptr) { @@ -58,7 +58,7 @@ bool InitGameSystems() ptr += 4; // Now grab our pointer - CBaseGameSystemFactory::sm_pFirst = (CBaseGameSystemFactory **)(ptr + offset); + CBaseGameSystemFactory::sm_pFirst = (CBaseGameSystemFactory**)(ptr + offset); // And insert the game system(s) CGameSystem::sm_Factory = new CGameSystemStaticFactory("CS2Fixes_GameSystem", &g_GameSystem); @@ -72,7 +72,7 @@ GS_EVENT_MEMBER(CGameSystem, BuildGameSessionManifest) { Message("CGameSystem::BuildGameSessionManifest\n"); - IEntityResourceManifest *pResourceManifest = msg->m_pResourceManifest; + IEntityResourceManifest* pResourceManifest = msg->m_pResourceManifest; // This takes any resource type, model or not // Any resource adding MUST be done here, the resource manifest is not long-lived diff --git a/src/gamesystem.h b/src/gamesystem.h index 27ce3f0b..43574ed5 100644 --- a/src/gamesystem.h +++ b/src/gamesystem.h @@ -30,14 +30,14 @@ class CGameSystem : public CBaseGameSystem GS_EVENT(BuildGameSessionManifest); GS_EVENT(ServerPreEntityThink); GS_EVENT(ServerPostEntityThink); - + void Shutdown() override { Message("CGameSystem::Shutdown\n"); delete sm_Factory; } - void SetGameSystemGlobalPtrs(void *pValue) override + void SetGameSystemGlobalPtrs(void* pValue) override { if (sm_Factory) sm_Factory->SetGlobalPtr(pValue); @@ -48,7 +48,7 @@ class CGameSystem : public CBaseGameSystem return sm_Factory->ShouldAutoAdd(); } - static IGameSystemFactory *sm_Factory; + static IGameSystemFactory* sm_Factory; }; // Quick and dirty definition diff --git a/src/httpmanager.cpp b/src/httpmanager.cpp index 75ed29d1..ed3a47d6 100644 --- a/src/httpmanager.cpp +++ b/src/httpmanager.cpp @@ -27,8 +27,8 @@ #include "httpmanager.h" #include "common.h" -#include #include "vendor/nlohmann/json.hpp" +#include extern ISteamHTTP* g_http; @@ -115,25 +115,23 @@ void HTTPManager::POST(const char* pszUrl, const char* pszText, CompletedCallbac void HTTPManager::GenerateRequest(EHTTPMethod method, const char* pszUrl, const char* pszText, CompletedCallback callback, std::vector* headers) { - //Message("Sending HTTP:\n%s\n", pszText); + // Message("Sending HTTP:\n%s\n", pszText); auto hReq = g_http->CreateHTTPRequest(method, pszUrl); int size = strlen(pszText); - //Message("HTTP request: %p\n", hReq); + // Message("HTTP request: %p\n", hReq); if (method == k_EHTTPMethodPOST && !g_http->SetHTTPRequestRawPostBody(hReq, "application/json", (uint8*)pszText, size)) { - //Message("Failed to SetHTTPRequestRawPostBody\n"); + // Message("Failed to SetHTTPRequestRawPostBody\n"); return; } // Prevent HTTP error 411 (probably not necessary?) - //g_http->SetHTTPRequestHeaderValue(hReq, "Content-Length", std::to_string(size).c_str()); + // g_http->SetHTTPRequestHeaderValue(hReq, "Content-Length", std::to_string(size).c_str()); if (headers != nullptr) - { for (HTTPHeader header : *headers) g_http->SetHTTPRequestHeaderValue(hReq, header.GetName(), header.GetValue()); - } SteamAPICall_t hCall; g_http->SendHTTPRequest(hReq, &hCall); diff --git a/src/httpmanager.h b/src/httpmanager.h index c7a47919..057ab5c6 100644 --- a/src/httpmanager.h +++ b/src/httpmanager.h @@ -32,8 +32,8 @@ #include "vendor/nlohmann/json_fwd.hpp" #include -#include #include +#include using json = nlohmann::json; @@ -52,6 +52,7 @@ class HTTPHeader } const char* GetName() { return m_strName.c_str(); } const char* GetValue() { return m_strValue.c_str(); } + private: std::string m_strName; std::string m_strValue; @@ -71,6 +72,7 @@ class HTTPManager TrackedRequest(const TrackedRequest& req) = delete; TrackedRequest(HTTPRequestHandle hndl, SteamAPICall_t hCall, std::string strUrl, std::string strText, CompletedCallback callback); ~TrackedRequest(); + private: void OnHTTPRequestCompleted(HTTPRequestCompleted_t* arg, bool bFailed); @@ -80,6 +82,7 @@ class HTTPManager std::string m_strText; CompletedCallback m_callback; }; + private: std::vector m_PendingRequests; void GenerateRequest(EHTTPMethod method, const char* pszUrl, const char* pszText, CompletedCallback callback, std::vector* headers); diff --git a/src/idlemanager.cpp b/src/idlemanager.cpp index 616edae9..2e38a3e2 100644 --- a/src/idlemanager.cpp +++ b/src/idlemanager.cpp @@ -1,28 +1,28 @@ /** -* ============================================================================= -* CS2Fixes -* Copyright (C) 2023-2024 Source2ZE -* ============================================================================= -* -* This program is free software; you can redistribute it and/or modify it under -* the terms of the GNU General Public License, version 3.0, as published by the -* Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, but WITHOUT -* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -* details. -* -* You should have received a copy of the GNU General Public License along with -* this program. If not, see . -*/ + * ============================================================================= + * CS2Fixes + * Copyright (C) 2023-2024 Source2ZE + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ #include "idlemanager.h" #include "commands.h" #include -extern IVEngineServer2 *g_pEngineServer2; -extern CGlobalVars *gpGlobals; +extern IVEngineServer2* g_pEngineServer2; +extern CGlobalVars* gpGlobals; extern CPlayerManager* g_playerManager; CIdleSystem* g_pIdleSystem = nullptr; diff --git a/src/idlemanager.h b/src/idlemanager.h index 0e938d70..5b1961f8 100644 --- a/src/idlemanager.h +++ b/src/idlemanager.h @@ -1,21 +1,21 @@ /** -* ============================================================================= -* CS2Fixes -* Copyright (C) 2023-2024 Source2ZE -* ============================================================================= -* -* This program is free software; you can redistribute it and/or modify it under -* the terms of the GNU General Public License, version 3.0, as published by the -* Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, but WITHOUT -* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -* details. -* -* You should have received a copy of the GNU General Public License along with -* this program. If not, see . -*/ + * ============================================================================= + * CS2Fixes + * Copyright (C) 2023-2024 Source2ZE + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ #pragma once @@ -29,8 +29,9 @@ class CIdleSystem void UpdateIdleTimes(); void PauseIdleChecks() { m_bPaused = true; } void Reset(); + private: bool m_bPaused = false; }; -extern CIdleSystem *g_pIdleSystem; \ No newline at end of file +extern CIdleSystem* g_pIdleSystem; \ No newline at end of file diff --git a/src/leader.cpp b/src/leader.cpp index e3ddf4bf..bc06b89d 100644 --- a/src/leader.cpp +++ b/src/leader.cpp @@ -18,11 +18,11 @@ */ #include "leader.h" -#include "common.h" #include "commands.h" +#include "common.h" #include "gameevents.pb.h" -#include "zombiereborn.h" #include "networksystem/inetworkmessages.h" +#include "zombiereborn.h" #include "tier0/memdbgon.h" @@ -32,6 +32,7 @@ extern CGlobalVars* gpGlobals; extern IGameEventManager2* g_gameEventManager; // All colors MUST have 255 alpha +// clang-format off std::map mapColorPresets = { {"darkred", ColorPreset("\x02", Color(255, 0, 0, 255), true)}, {"red", ColorPreset("\x07", Color(255, 64, 64, 255), true)}, @@ -49,6 +50,7 @@ std::map mapColorPresets = { {"white", ColorPreset("\x01", Color(255, 255, 255, 255), true)}, {"pink", ColorPreset( "", Color(255, 192, 203, 255), false)} }; +// clang-format on CUtlVector g_vecLeaders; @@ -76,7 +78,7 @@ FAKE_STRING_CVAR(cs2f_leader_model_path, "Path to player model to be used for le FAKE_STRING_CVAR(cs2f_leader_defend_particle, "Path to defend particle to be used with c_defend", g_strDefendParticlePath, false) FAKE_STRING_CVAR(cs2f_leader_mark_particle, "Path to particle to be used when a ct leader using player_ping", g_strMarkParticlePath, false) FAKE_BOOL_CVAR(cs2f_leader_can_target_players, "Whether a leader can target other players with leader commands (not including c_leader)", g_bLeaderCanTargetPlayers, false, false) -FAKE_BOOL_CVAR(cs2f_leader_vote_multiple , "If true, players can vote up to cs2f_max_leaders leaders. If false, they may vote for a single leader", g_bLeaderVoteMultiple, true, false) +FAKE_BOOL_CVAR(cs2f_leader_vote_multiple, "If true, players can vote up to cs2f_max_leaders leaders. If false, they may vote for a single leader", g_bLeaderVoteMultiple, true, false) static int g_iMaxLeaders = 3; static int g_iMaxMarkers = 6; @@ -94,7 +96,7 @@ bool Leader_SetNewLeader(ZEPlayer* zpLeader, std::string strColor = "") { CCSPlayerController* pLeader = CCSPlayerController::FromSlot(zpLeader->GetPlayerSlot()); CCSPlayerPawn* pawnLeader = (CCSPlayerPawn*)pLeader->GetPawn(); - + if (zpLeader->IsLeader()) return false; @@ -142,7 +144,7 @@ Color Leader_GetColor(std::string strColor, ZEPlayer* zpUser = nullptr, CCSPlaye return zpUser->GetLeaderColor(); else if (pTarget && pTarget->m_iTeamNum == CS_TEAM_T) return mapColorPresets["orange"].color; - + return mapColorPresets["blue"].color; } @@ -159,10 +161,10 @@ std::pair GetLeaders() g_vecLeaders.Remove(i); continue; } - CCSPlayerController* pController = CCSPlayerController::FromSlot((CPlayerSlot) pLeader->GetPlayerSlot()); + CCSPlayerController* pController = CCSPlayerController::FromSlot((CPlayerSlot)pLeader->GetPlayerSlot()); if (!pController) continue; - + iLeaders++; strLeaders.append(pController->GetPlayerName()); strLeaders.append(", "); @@ -277,8 +279,7 @@ bool Leader_CreateDefendMarker(ZEPlayer* pPlayer, Color clrTint, int iDuration) g_iMarkerCount++; - new CTimer(iDuration, false, false, []() - { + new CTimer(iDuration, false, false, []() { if (g_iMarkerCount > 0) g_iMarkerCount--; @@ -312,7 +313,7 @@ void Leader_PostEventAbstract_Source1LegacyGameEvent(const uint64* clients, cons return; auto pPBData = pData->ToPB(); - + static int player_ping_id = g_gameEventManager->LookupEventId("player_ping"); if (pPBData->eventid() != player_ping_id) @@ -468,18 +469,14 @@ CON_COMMAND_CHAT_LEADER(glow, "[name] [color] - Toggle glow highlight on a playe ZEPlayer* pPlayerTarget = pTarget->GetZEPlayer(); if (iNumClients == 1 && player == pTarget) - { ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "%s glow on yourself.", pPlayerTarget->GetGlowModel() ? "Disabled" : "Enabled"); - } else if (iNumClients == 1) - { ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s %s %s glow on %s.", bIsAdmin ? "Admin" : "Leader", pszCommandPlayerName, pPlayerTarget->GetGlowModel() ? "disabled" : "enabled", pTarget->GetPlayerName()); - } if (!pPlayerTarget->GetGlowModel()) { @@ -526,7 +523,7 @@ CON_COMMAND_CHAT(vl, " - Vote for a player to become a leader") ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Leader voting is not open yet."); return; } - + if (GetLeaders().first > 0 && !g_bLeaderVoteMultiple) { ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "There is already an active leader."); @@ -572,7 +569,7 @@ CON_COMMAND_CHAT(vl, " - Vote for a player to become a leader") } int iLeaderVoteCount = pPlayerTarget->GetLeaderVoteCount(); - int iNeededLeaderVoteCount = (int)(g_playerManager->GetOnlinePlayerCount(false) * g_flLeaderVoteRatio) + 1;; + int iNeededLeaderVoteCount = (int)(g_playerManager->GetOnlinePlayerCount(false) * g_flLeaderVoteRatio) + 1; pPlayer->SetLeaderVoteTime(gpGlobals->curtime); @@ -586,8 +583,8 @@ CON_COMMAND_CHAT(vl, " - Vote for a player to become a leader") } pPlayerTarget->AddLeaderVote(pPlayer); - ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s wants %s to become a Leader (%i/%i votes).",\ - player->GetPlayerName(), pTarget->GetPlayerName(), iLeaderVoteCount+1, iNeededLeaderVoteCount); + ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s wants %s to become a Leader (%i/%i votes).", + player->GetPlayerName(), pTarget->GetPlayerName(), iLeaderVoteCount + 1, iNeededLeaderVoteCount); } CON_COMMAND_CHAT_LEADER(defend, "[name|duration] [duration] - Place a defend marker on the target player") @@ -604,7 +601,7 @@ CON_COMMAND_CHAT_LEADER(defend, "[name|duration] [duration] - Place a defend mar if ((args.ArgC() >= 2 || (args.ArgC() == 2 && iDuration == -1)) && (bIsAdmin || g_bLeaderCanTargetPlayers)) pszTarget = args[1]; iDuration = (iDuration < 1) ? 30 : MIN(iDuration, 60); - + if (!g_playerManager->CanTargetPlayers(player, pszTarget, iNumClients, pSlots, NO_MULTIPLE | NO_DEAD | NO_TERRORIST | NO_IMMUNITY, nType)) return; @@ -616,11 +613,9 @@ CON_COMMAND_CHAT_LEADER(defend, "[name|duration] [duration] - Place a defend mar if (player == pTarget) ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Placed a defend marker on your position lasting %i seconds.", iDuration); else - { ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s %s placed a defend marker on %s's position lasting %i seconds.", bIsAdmin ? "Admin" : "Leader", pszCommandPlayerName, pTarget->GetPlayerName(), iDuration); - } } } @@ -648,10 +643,8 @@ CON_COMMAND_CHAT_LEADER(tracer, "[name] [color] - Toggle projectile tracers on a if (pTarget == player) ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Disabled tracers for yourself.", pTarget->GetPlayerName()); else - { ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s %s disabled tracers for %s.", bIsAdmin ? "Admin" : "Leader", pszCommandPlayerName, pTarget->GetPlayerName()); - } pPlayerTarget->SetTracerColor(Color(0, 0, 0, 0)); return; } @@ -662,10 +655,8 @@ CON_COMMAND_CHAT_LEADER(tracer, "[name] [color] - Toggle projectile tracers on a if (pTarget == player) ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Enabled tracers for yourself.", pTarget->GetPlayerName()); else - { ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s %s enabled tracers for %s.", bIsAdmin ? "Admin" : "Leader", pszCommandPlayerName, pTarget->GetPlayerName()); - } } CON_COMMAND_CHAT(tracers, "- List all active player tracers") @@ -703,18 +694,14 @@ CON_COMMAND_CHAT_LEADER(beacon, "[name] [color] - Toggle beacon on a player") ZEPlayer* pPlayerTarget = pTarget->GetZEPlayer(); if (iNumClients == 1 && player == pTarget) - { ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "%s beacon on yourself.", pPlayerTarget->GetBeaconParticle() ? "Disabled" : "Enabled"); - } else if (iNumClients == 1) - { ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s %s %s beacon on %s.", bIsAdmin ? "Admin" : "Leader", pszCommandPlayerName, pPlayerTarget->GetBeaconParticle() ? "disabled" : "enabled", pTarget->GetPlayerName()); - } if (!pPlayerTarget->GetBeaconParticle()) { @@ -835,9 +822,7 @@ CON_COMMAND_CHAT(leadercolor, "[color] - List leader colors in chat or change yo std::string strColors = ""; for (auto const& [strColorName, colorPreset] : mapColorPresets) - { strColors.append(colorPreset.strChatColor + strColorName + "\x01, "); - } if (strColors.length() > 2) strColors = strColors.substr(0, strColors.length() - 2); @@ -873,10 +858,8 @@ CON_COMMAND_CHAT_LEADER(leader, "[name] [color] - Force leader status on a playe if (!Leader_SetNewLeader(pPlayerTarget, args.ArgC() < 3 ? "" : args[2])) ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "%s is already a leader.", pTarget->GetPlayerName()); else - { ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "%s %s set %s as a leader.", bIsAdmin ? "Admin" : "Leader", pszCommandPlayerName, pTarget->GetPlayerName()); - } } CON_COMMAND_CHAT_FLAGS(removeleader, "[name] - Remove leader status from a player", ADMFLAG_GENERIC) diff --git a/src/leader.h b/src/leader.h index e1dce7a4..97933e00 100644 --- a/src/leader.h +++ b/src/leader.h @@ -18,15 +18,15 @@ */ #pragma once -#include "utils/entity.h" -#include "playermanager.h" +#include "adminsystem.h" #include "gamesystem.h" #include "igameevents.h" -#include "adminsystem.h" +#include "playermanager.h" +#include "utils/entity.h" - // Inside IsAdminFlagSet, checks for ADMFLAG_GENERIC. - // Inside command permissions, checks for if leader system is enabled and player is leader - // OR if player has ADMFLAG_GENERIC +// Inside IsAdminFlagSet, checks for ADMFLAG_GENERIC. +// Inside command permissions, checks for if leader system is enabled and player is leader +// OR if player has ADMFLAG_GENERIC #define FLAG_LEADER (ADMFLAG_GENERIC | 1 << 31) struct ColorPreset @@ -43,8 +43,8 @@ extern bool g_bEnableLeader; extern bool g_bLeaderActionsHumanOnly; extern std::string g_strMarkParticlePath; -void Leader_ApplyLeaderVisuals(CCSPlayerPawn *pPawn); -void Leader_PostEventAbstract_Source1LegacyGameEvent(const uint64 *clients, const CNetMessage *pData); -void Leader_OnRoundStart(IGameEvent *pEvent); -void Leader_BulletImpact(IGameEvent *pEvent); -void Leader_Precache(IEntityResourceManifest *pResourceManifest); \ No newline at end of file +void Leader_ApplyLeaderVisuals(CCSPlayerPawn* pPawn); +void Leader_PostEventAbstract_Source1LegacyGameEvent(const uint64* clients, const CNetMessage* pData); +void Leader_OnRoundStart(IGameEvent* pEvent); +void Leader_BulletImpact(IGameEvent* pEvent); +void Leader_Precache(IEntityResourceManifest* pResourceManifest); \ No newline at end of file diff --git a/src/map_votes.cpp b/src/map_votes.cpp index 0afa51ac..4dfbb2b1 100644 --- a/src/map_votes.cpp +++ b/src/map_votes.cpp @@ -1,4 +1,4 @@ - /** +/** * ============================================================================= * CS2Fixes * Copyright (C) 2023-2024 Source2ZE @@ -21,19 +21,19 @@ #include "commands.h" #include "common.h" #include "ctimer.h" -#include "eventlistener.h" #include "entity/cgamerules.h" +#include "eventlistener.h" #include "idlemanager.h" -#include "strtools.h" -#include #include "playermanager.h" -#include +#include "steam/steam_gameserver.h" +#include "strtools.h" #include "utlstring.h" #include "utlvector.h" #include "votemanager.h" -#include "steam/steam_gameserver.h" +#include +#include -extern CGlobalVars *gpGlobals; +extern CGlobalVars* gpGlobals; extern CCSGameRules* g_pGameRules; extern IVEngineServer2* g_pEngineServer2; extern CSteamGameServerAPIContext g_steamAPI; @@ -72,14 +72,16 @@ CON_COMMAND_CHAT_FLAGS(reload_map_list, "- Reload map list, also reloads current CON_COMMAND_F(cs2f_vote_maps_cooldown, "Default number of maps to wait until a map can be voted / nominated again i.e. cooldown.", FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY) { - if (!g_pMapVoteSystem) { + if (!g_pMapVoteSystem) + { Message("The map vote subsystem is not enabled.\n"); return; } if (args.ArgC() < 2) Message("%s %d\n", args[0], g_pMapVoteSystem->GetDefaultMapCooldown()); - else { + else + { int iCurrentCooldown = g_pMapVoteSystem->GetDefaultMapCooldown(); g_pMapVoteSystem->SetDefaultMapCooldown(V_StringToInt32(args[1], iCurrentCooldown)); } @@ -87,20 +89,22 @@ CON_COMMAND_F(cs2f_vote_maps_cooldown, "Default number of maps to wait until a m CON_COMMAND_F(cs2f_vote_max_nominations, "Number of nominations to include per vote, out of a maximum of 10.", FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY) { - if (!g_pMapVoteSystem) { + if (!g_pMapVoteSystem) + { Message("The map vote subsystem is not enabled.\n"); return; } if (args.ArgC() < 2) Message("%s %d\n", args[0], g_pMapVoteSystem->GetMaxNominatedMaps()); - else { + else + { int iMaxNominatedMaps = g_pMapVoteSystem->GetMaxNominatedMaps(); g_pMapVoteSystem->SetMaxNominatedMaps(V_StringToInt32(args[1], iMaxNominatedMaps)); } } -//TODO: workshop id support for rcon admins? +// TODO: workshop id support for rcon admins? CON_COMMAND_CHAT_FLAGS(setnextmap, "[mapname] - Force next map (empty to clear forced next map)", ADMFLAG_CHANGEMAP) { if (!g_bVoteManagerEnable) @@ -133,7 +137,7 @@ CON_COMMAND_CHAT_FLAGS(setnextmap, "[mapname] - Force next map (empty to clear f } } -static int __cdecl OrderStringsLexicographically(const MapIndexPair *a, const MapIndexPair *b) +static int __cdecl OrderStringsLexicographically(const MapIndexPair* a, const MapIndexPair* b) { return V_strcasecmp(a->name, b->name); } @@ -149,7 +153,8 @@ CON_COMMAND_CHAT(nominate, "[mapname] - Nominate a map (empty to clear nominatio if (!pPlayer) return; - switch (response.first) { + switch (response.first) + { case NominationReturnCodes::VOTE_STARTED: ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Nominations are currently disabled because the vote has already started."); break; @@ -257,7 +262,8 @@ CON_COMMAND_CHAT(nomlist, "- List the list of nominations") return; ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Current nominations:"); - for (int i = 0; i < g_pMapVoteSystem->GetMapListSize(); i++) { + for (int i = 0; i < g_pMapVoteSystem->GetMapListSize(); i++) + { if (!g_pMapVoteSystem->IsMapIndexEnabled(i)) continue; int iNumNominations = g_pMapVoteSystem->GetTotalNominations(i); if (iNumNominations == 0) continue; @@ -272,11 +278,11 @@ CON_COMMAND_CHAT(mapcooldowns, "- List the maps currently in cooldown") return; int iMapCount = g_pMapVoteSystem->GetMapListSize(); - std::vector > vecCooldowns; + std::vector> vecCooldowns; ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "The list of maps in cooldown will be shown in console."); ClientPrint(player, HUD_PRINTCONSOLE, "The list of maps in cooldown is:"); - + for (int iMapIndex = 0; iMapIndex < iMapCount; iMapIndex++) { int iCooldown = g_pMapVoteSystem->GetCooldownMap(iMapIndex); @@ -330,8 +336,7 @@ void CMapVoteSystem::OnLevelInit(const char* pMapName) ClearPlayerInfo(i); // Delay one tick to override any .cfg's - new CTimer(0.02f, false, true, []() - { + new CTimer(0.02f, false, true, []() { g_pEngineServer2->ServerCommand("mp_match_end_changelevel 0"); return -1.0f; @@ -340,7 +345,7 @@ void CMapVoteSystem::OnLevelInit(const char* pMapName) SetCurrentMapIndex(GetMapIndexFromString(pMapName)); } -void CMapVoteSystem::StartVote() +void CMapVoteSystem::StartVote() { m_bIsVoteOngoing = true; @@ -356,8 +361,7 @@ void CMapVoteSystem::StartVote() for (int i = 0; i < 10; i++) g_pGameRules->m_nEndMatchMapGroupVoteOptions[i] = m_iForcedNextMapIndex; - new CTimer(6.0f, false, true, []() - { + new CTimer(6.0f, false, true, []() { g_pMapVoteSystem->FinishVote(); return -1.0f; }); @@ -372,14 +376,16 @@ void CMapVoteSystem::StartVote() CUtlVector vecPossibleMaps; CUtlVector vecIncludedMaps; GetNominatedMapsForVote(vecIncludedMaps); - for (int i = 0; i < m_vecMapList.Count(); i++) { + for (int i = 0; i < m_vecMapList.Count(); i++) + { if (!IsMapIndexEnabled(i)) continue; if (vecIncludedMaps.HasElement(i)) continue; vecPossibleMaps.AddToTail(i); } // Print all available maps out to console - FOR_EACH_VEC(vecPossibleMaps, i) { + FOR_EACH_VEC(vecPossibleMaps, i) + { int iPossibleMapIndex = vecPossibleMaps[i]; Message("The %d-th possible map index %d is %s\n", i, iPossibleMapIndex, m_vecMapList[iPossibleMapIndex].GetName()); } @@ -387,32 +393,38 @@ void CMapVoteSystem::StartVote() // Set the maps in the vote: merge nominated and possible maps, then randomly sort int iNumMapsInVote = vecPossibleMaps.Count() + vecIncludedMaps.Count(); if (iNumMapsInVote >= 10) iNumMapsInVote = 10; - while (vecIncludedMaps.Count() < iNumMapsInVote && vecPossibleMaps.Count() > 0) { + while (vecIncludedMaps.Count() < iNumMapsInVote && vecPossibleMaps.Count() > 0) + { int iMapToAdd = vecPossibleMaps[rand() % vecPossibleMaps.Count()]; vecIncludedMaps.AddToTail(iMapToAdd); vecPossibleMaps.FindAndRemove(iMapToAdd); } // Randomly sort the chosen maps - for (int i = 0; i < 10; i++) { - if (i < iNumMapsInVote) { + for (int i = 0; i < 10; i++) + { + if (i < iNumMapsInVote) + { int iMapToAdd = vecIncludedMaps[rand() % vecIncludedMaps.Count()]; g_pGameRules->m_nEndMatchMapGroupVoteOptions[i] = iMapToAdd; vecIncludedMaps.FindAndRemove(iMapToAdd); - } else { + } + else + { g_pGameRules->m_nEndMatchMapGroupVoteOptions[i] = -1; } } // Print the maps chosen in the vote to console - for (int i = 0; i < iNumMapsInVote; i++) { + for (int i = 0; i < iNumMapsInVote; i++) + { int iMapIndex = g_pGameRules->m_nEndMatchMapGroupVoteOptions[i]; Message("The %d-th chosen map index %d is %s\n", i, iMapIndex, m_vecMapList[iMapIndex].GetName()); } // Start the end-of-vote timer to finish the vote ConVar* cvar = g_pCVar->GetConVar(g_pCVar->FindConVar("mp_endmatch_votenextleveltime")); - float flVoteTime = *(float *)&cvar->values; + float flVoteTime = *(float*)&cvar->values; new CTimer(flVoteTime, false, true, []() { g_pMapVoteSystem->FinishVote(); return -1.0; @@ -422,11 +434,11 @@ void CMapVoteSystem::StartVote() int CMapVoteSystem::GetTotalNominations(int iMapIndex) { int iNumNominations = 0; - for (int i = 0; i < gpGlobals->maxClients; i++) { + for (int i = 0; i < gpGlobals->maxClients; i++) + { auto pController = CCSPlayerController::FromSlot(i); - if (pController && pController->IsConnected() && m_arrPlayerNominations[i] == iMapIndex) { + if (pController && pController->IsConnected() && m_arrPlayerNominations[i] == iMapIndex) iNumNominations++; - } } return iNumNominations; } @@ -444,7 +456,8 @@ void CMapVoteSystem::FinishVote() // If we are forcing the map, show different text bool bIsNextMapForced = m_iForcedNextMapIndex != -1; - if (bIsNextMapForced) { + if (bIsNextMapForced) + { iNextMapVoteIndex = 0; g_pGameRules->m_nEndMatchMapGroupVoteOptions[0] = m_iForcedNextMapIndex; g_pGameRules->m_nEndMatchMapVoteWinner = iNextMapVoteIndex; @@ -456,30 +469,28 @@ void CMapVoteSystem::FinishVote() int iWinningMap = g_pGameRules->m_nEndMatchMapGroupVoteOptions[iNextMapVoteIndex]; char buffer[256]; - if (bIsNextMapVoted) { + if (bIsNextMapVoted) V_snprintf(buffer, sizeof(buffer), "The vote has ended. \x06%s\x01 will be the next map!\n", GetMapName(iWinningMap)); - } - else if (bIsNextMapForced) { + else if (bIsNextMapForced) V_snprintf(buffer, sizeof(buffer), "The vote was overriden. \x06%s\x01 will be the next map!\n", GetMapName(iWinningMap)); - } - else { + else V_snprintf(buffer, sizeof(buffer), "No map was chosen. \x06%s\x01 will be the next map!\n", GetMapName(iWinningMap)); - } ClientPrintAll(HUD_PRINTTALK, buffer); Message(buffer); // Print vote result information: how many votes did each map get? - int arrMapVotes[10] = { 0 }; + int arrMapVotes[10] = {0}; Message("Map vote result --- total votes per map:\n"); - for (int i = 0; i < gpGlobals->maxClients; i++) { + for (int i = 0; i < gpGlobals->maxClients; i++) + { auto pController = CCSPlayerController::FromSlot(i); int iPlayerVotedIndex = m_arrPlayerVotes[i]; - if (pController && pController->IsConnected() && iPlayerVotedIndex >= 0) { + if (pController && pController->IsConnected() && iPlayerVotedIndex >= 0) arrMapVotes[iPlayerVotedIndex]++; - } } - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { int iMapIndex = g_pGameRules->m_nEndMatchMapGroupVoteOptions[i]; const char* sIsWinner = (i == iNextMapVoteIndex) ? "(WINNER)" : ""; Message("- %s got %d votes\n", GetMapName(iMapIndex), arrMapVotes[i]); @@ -538,7 +549,8 @@ bool CMapVoteSystem::RegisterPlayerVote(CPlayerSlot iPlayerSlot, int iVoteOption bool CMapVoteSystem::UpdateWinningMap() { int iWinningMapIndex = WinningMapIndex(); - if (iWinningMapIndex >= 0) { + if (iWinningMapIndex >= 0) + { g_pGameRules->m_nEndMatchMapVoteWinner = iWinningMapIndex; return true; } @@ -549,30 +561,30 @@ int CMapVoteSystem::WinningMapIndex() { // Count the votes of every player int arrMapVotes[10] = {0}; - for (int i = 0; i < gpGlobals->maxClients; i++) { + for (int i = 0; i < gpGlobals->maxClients; i++) + { auto pController = CCSPlayerController::FromSlot(i); - if (pController && pController->IsConnected() && m_arrPlayerVotes[i] >= 0) { + if (pController && pController->IsConnected() && m_arrPlayerVotes[i] >= 0) arrMapVotes[m_arrPlayerVotes[i]]++; - } } // Identify the max. number of votes int iMaxVotes = 0; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) iMaxVotes = (arrMapVotes[i] > iMaxVotes) ? arrMapVotes[i] : iMaxVotes; - } - // Identify how many maps are tied with the max number of votes + // Identify how many maps are tied with the max number of votes int iMapsWithMaxVotes = 0; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) if (arrMapVotes[i] == iMaxVotes) iMapsWithMaxVotes++; - } // Break ties: 'random' map with the most votes int iWinningMapTieBreak = m_iRandomWinnerShift % iMapsWithMaxVotes; int iWinningMapCount = 0; - for (int i = 0; i < 10; i++) { - if (arrMapVotes[i] == iMaxVotes) { + for (int i = 0; i < 10; i++) + { + if (arrMapVotes[i] == iMaxVotes) + { if (iWinningMapCount == iWinningMapTieBreak) return i; iWinningMapCount++; } @@ -584,14 +596,15 @@ void CMapVoteSystem::GetNominatedMapsForVote(CUtlVector& vecChosenNominated { int iNumDistinctMaps = 0; CUtlVector vecAvailableNominatedMaps; - for (int i = 0; i < gpGlobals->maxClients; i++) { + for (int i = 0; i < gpGlobals->maxClients; i++) + { int iNominatedMapIndex = m_arrPlayerNominations[i]; // Introduce nominated map indexes and count the total number - if (iNominatedMapIndex != -1) { - if (!vecAvailableNominatedMaps.HasElement(iNominatedMapIndex)) { + if (iNominatedMapIndex != -1) + { + if (!vecAvailableNominatedMaps.HasElement(iNominatedMapIndex)) iNumDistinctMaps++; - } vecAvailableNominatedMaps.AddToTail(iNominatedMapIndex); } } @@ -599,12 +612,12 @@ void CMapVoteSystem::GetNominatedMapsForVote(CUtlVector& vecChosenNominated // Randomly select maps out of the set of nominated maps // weighting by number of nominations, and returning a random order int iMapsToIncludeInNominate = (iNumDistinctMaps < m_iMaxNominatedMaps) ? iNumDistinctMaps : m_iMaxNominatedMaps; - while (vecChosenNominatedMaps.Count() < iMapsToIncludeInNominate) { + while (vecChosenNominatedMaps.Count() < iMapsToIncludeInNominate) + { int iMapToAdd = vecAvailableNominatedMaps[rand() % vecAvailableNominatedMaps.Count()]; vecChosenNominatedMaps.AddToTail(iMapToAdd); - while (vecAvailableNominatedMaps.HasElement(iMapToAdd)) { + while (vecAvailableNominatedMaps.HasElement(iMapToAdd)) vecAvailableNominatedMaps.FindAndRemove(iMapToAdd); - } } } @@ -735,7 +748,8 @@ static int __cdecl OrderMapsByWorkshopId(const CMapInfo* a, const CMapInfo* b) return -1; else if (valueA == valueB) return 0; - else return 1; + else + return 1; } void CMapVoteSystem::PrintDownloadProgress() @@ -758,7 +772,7 @@ void CMapVoteSystem::PrintDownloadProgress() Message("Downloading map %lli: %.2f/%.2f MB (%.2f%%)\n", m_DownloadQueue.Head(), flMBDownloaded, flTotalMB, flProgress); } -void CMapVoteSystem::OnMapDownloaded(DownloadItemResult_t *pResult) +void CMapVoteSystem::OnMapDownloaded(DownloadItemResult_t* pResult) { if (!m_DownloadQueue.Check(pResult->m_nPublishedFileId)) return; @@ -791,8 +805,9 @@ bool CMapVoteSystem::LoadMapList() KeyValues* pKV = new KeyValues("maplist"); KeyValues::AutoDelete autoDelete(pKV); - const char *pszPath = "addons/cs2fixes/configs/maplist.cfg"; - if (!pKV->LoadFromFile(g_pFullFileSystem, pszPath)) { + const char* pszPath = "addons/cs2fixes/configs/maplist.cfg"; + if (!pKV->LoadFromFile(g_pFullFileSystem, pszPath)) + { Panic("Failed to load %s\n", pszPath); return false; } @@ -800,10 +815,9 @@ bool CMapVoteSystem::LoadMapList() // Load map cooldowns from file KeyValues* pKVcooldowns = new KeyValues("cooldowns"); KeyValues::AutoDelete autoDeleteKVcooldowns(pKVcooldowns); - const char *pszCooldownFilePath = "addons/cs2fixes/data/cooldowns.txt"; - if (!pKVcooldowns->LoadFromFile(g_pFullFileSystem, pszCooldownFilePath)) { + const char* pszCooldownFilePath = "addons/cs2fixes/data/cooldowns.txt"; + if (!pKVcooldowns->LoadFromFile(g_pFullFileSystem, pszCooldownFilePath)) Message("Failed to load cooldown file at %s - resetting all cooldowns to 0\n", pszCooldownFilePath); - } // KV1 has some funny behaviour with capitalization, to ensure consistency we can't directly lookup case-sensitive key names std::unordered_map mapCooldowns; @@ -819,7 +833,8 @@ bool CMapVoteSystem::LoadMapList() mapCooldowns[sMapName] = iCooldown; } - for (KeyValues* pKey = pKV->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey()) { + for (KeyValues* pKey = pKV->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey()) + { const char* pszName = pKey->GetName(); std::string sName = pszName; @@ -840,8 +855,7 @@ bool CMapVoteSystem::LoadMapList() m_vecMapList.AddToTail(CMapInfo(pszName, iWorkshopId, bIsEnabled, iMinPlayers, iMaxPlayers, iBaseCooldown, iCurrentCooldown)); } - new CTimer(0.f, true, true, []() - { + new CTimer(0.f, true, true, []() { if (g_pMapVoteSystem->m_DownloadQueue.Count() == 0) return -1.f; @@ -854,13 +868,14 @@ bool CMapVoteSystem::LoadMapList() m_vecMapList.Sort(OrderMapsByWorkshopId); // Print all the maps to show the order - FOR_EACH_VEC(m_vecMapList, i) { + FOR_EACH_VEC(m_vecMapList, i) + { CMapInfo map = m_vecMapList[i]; if (map.GetWorkshopId() == 0) ConMsg("Map %d is %s, which is %s. MinPlayers: %d MaxPlayers: %d Cooldown: %d\n", i, map.GetName(), map.IsEnabled() ? "enabled" : "disabled", map.GetMinPlayers(), map.GetMaxPlayers(), map.GetBaseCooldown()); else - ConMsg("Map %d is %s with workshop id %llu, which is %s. MinPlayers: %d MaxPlayers: %d Cooldown: %d\n", i, map.GetName(), map.GetWorkshopId(), map.IsEnabled()? "enabled" : "disabled", map.GetMinPlayers(), map.GetMaxPlayers(), map.GetBaseCooldown()); + ConMsg("Map %d is %s with workshop id %llu, which is %s. MinPlayers: %d MaxPlayers: %d Cooldown: %d\n", i, map.GetName(), map.GetWorkshopId(), map.IsEnabled() ? "enabled" : "disabled", map.GetMinPlayers(), map.GetMaxPlayers(), map.GetBaseCooldown()); } m_bMapListLoaded = true; @@ -896,7 +911,7 @@ void CMapVoteSystem::DecrementAllMapCooldowns() { FOR_EACH_VEC(m_vecMapList, i) { - CMapInfo * pMap = &m_vecMapList[i]; + CMapInfo* pMap = &m_vecMapList[i]; pMap->DecrementCooldown(); } } @@ -906,7 +921,7 @@ bool CMapVoteSystem::WriteMapCooldownsToFile() KeyValues* pKV = new KeyValues("cooldowns"); KeyValues::AutoDelete autoDelete(pKV); - const char *pszPath = "addons/cs2fixes/data/cooldowns.txt"; + const char* pszPath = "addons/cs2fixes/data/cooldowns.txt"; FOR_EACH_VEC(m_vecMapList, i) { @@ -934,7 +949,8 @@ void CMapVoteSystem::ClearInvalidNominations() if (!g_bVoteManagerEnable || m_bIsVoteOngoing) return; - for (int i = 0; i < gpGlobals->maxClients; i++) { + for (int i = 0; i < gpGlobals->maxClients; i++) + { int iNominatedMapIndex = m_arrPlayerNominations[i]; // Ignore unset nominations (negative index) diff --git a/src/map_votes.h b/src/map_votes.h index 81075cde..92dea857 100644 --- a/src/map_votes.h +++ b/src/map_votes.h @@ -17,155 +17,160 @@ * this program. If not, see . */ +#include "KeyValues.h" #include "common.h" -#include +#include "steam/isteamugc.h" +#include "steam/steam_api_common.h" +#include "utlqueue.h" #include "utlstring.h" #include "utlvector.h" -#include "utlqueue.h" -#include "KeyValues.h" -#include "steam/steam_api_common.h" -#include "steam/isteamugc.h" +#include #include #include - // Nomination constants, used as return codes for nomination commands #ifndef NOMINATION_CONSTANTS_H -#define NOMINATION_CONSTANTS_H + #define NOMINATION_CONSTANTS_H namespace NominationReturnCodes { - static const int VOTE_STARTED = -100; - static const int NOMINATION_DISABLED = -101; - static const int NOMINATION_RESET = -102; - static const int NOMINATION_RESET_FAILED = -103; - static const int MAP_NOT_FOUND = -104; - static const int MAP_MULTIPLE = -105; - static const int MAP_DISABLED = -106; - static const int MAP_CURRENT = -107; - static const int MAP_COOLDOWN = -108; - static const int MAP_MINPLAYERS = -109; - static const int MAP_MAXPLAYERS = -110; - static const int MAP_NOMINATED = -111; -} + static const int VOTE_STARTED = -100; + static const int NOMINATION_DISABLED = -101; + static const int NOMINATION_RESET = -102; + static const int NOMINATION_RESET_FAILED = -103; + static const int MAP_NOT_FOUND = -104; + static const int MAP_MULTIPLE = -105; + static const int MAP_DISABLED = -106; + static const int MAP_CURRENT = -107; + static const int MAP_COOLDOWN = -108; + static const int MAP_MINPLAYERS = -109; + static const int MAP_MAXPLAYERS = -110; + static const int MAP_NOMINATED = -111; +} // namespace NominationReturnCodes #endif - class CMapInfo { public: - CMapInfo(const char* pszName, uint64 iWorkshopId, bool bIsEnabled, int iMinPlayers, int iMaxPlayers, int iBaseCooldown, int iCurrentCooldown) - { - V_strcpy(m_pszName, pszName); - m_iWorkshopId = iWorkshopId; - m_bIsEnabled = bIsEnabled; - m_iBaseCooldown = iBaseCooldown; - m_iCurrentCooldown = iCurrentCooldown; - m_iMinPlayers = iMinPlayers; - m_iMaxPlayers = iMaxPlayers; - } + CMapInfo(const char* pszName, uint64 iWorkshopId, bool bIsEnabled, int iMinPlayers, int iMaxPlayers, int iBaseCooldown, int iCurrentCooldown) + { + V_strcpy(m_pszName, pszName); + m_iWorkshopId = iWorkshopId; + m_bIsEnabled = bIsEnabled; + m_iBaseCooldown = iBaseCooldown; + m_iCurrentCooldown = iCurrentCooldown; + m_iMinPlayers = iMinPlayers; + m_iMaxPlayers = iMaxPlayers; + } - const char* GetName() { return (const char*)m_pszName; }; - uint64 GetWorkshopId() const { return m_iWorkshopId; }; - bool IsEnabled() { return m_bIsEnabled; }; - int GetBaseCooldown() { return m_iBaseCooldown; }; - int GetCooldown() { return m_iCurrentCooldown; }; - void ResetCooldownToBase() { m_iCurrentCooldown = m_iBaseCooldown; }; - void DecrementCooldown() { m_iCurrentCooldown = MAX(0, (m_iCurrentCooldown - 1)); } - int GetMinPlayers() { return m_iMinPlayers; }; - int GetMaxPlayers() { return m_iMaxPlayers; }; + const char* GetName() { return (const char*)m_pszName; }; + uint64 GetWorkshopId() const { return m_iWorkshopId; }; + bool IsEnabled() { return m_bIsEnabled; }; + int GetBaseCooldown() { return m_iBaseCooldown; }; + int GetCooldown() { return m_iCurrentCooldown; }; + void ResetCooldownToBase() { m_iCurrentCooldown = m_iBaseCooldown; }; + void DecrementCooldown() { m_iCurrentCooldown = MAX(0, (m_iCurrentCooldown - 1)); } + int GetMinPlayers() { return m_iMinPlayers; }; + int GetMaxPlayers() { return m_iMaxPlayers; }; private: - char m_pszName[64]; - uint64 m_iWorkshopId; - bool m_bIsEnabled; - int m_iMinPlayers; - int m_iMaxPlayers; - int m_iBaseCooldown; - int m_iCurrentCooldown; + char m_pszName[64]; + uint64 m_iWorkshopId; + bool m_bIsEnabled; + int m_iMinPlayers; + int m_iMaxPlayers; + int m_iBaseCooldown; + int m_iCurrentCooldown; }; - typedef struct { - const char* name; - int index; + const char* name; + int index; } MapIndexPair; - class CMapVoteSystem { public: - CMapVoteSystem() - { - // Initialize the nomination / vote arrays to -1 - for (int i = 0; i < MAXPLAYERS; i++) { - m_arrPlayerNominations[i] = -1; - m_arrPlayerVotes[i] = -1; - } - } - bool LoadMapList(); - void OnLevelInit(const char* pMapName); - void StartVote(); - void FinishVote(); - bool RegisterPlayerVote(CPlayerSlot iPlayerSlot, int iVoteOption); - std::vector GetMapIndexesFromSubstring(const char* sMapSubstring); - int GetMapIndexFromString(const char* sMapString); - int GetCooldownMap(int iMapIndex) { return m_vecMapList[iMapIndex].GetCooldown(); }; - void PutMapOnCooldown(int iMapIndex) { m_vecMapList[iMapIndex].ResetCooldownToBase(); }; - void DecrementAllMapCooldowns(); - void SetMaxNominatedMaps(int iMaxNominatedMaps) { m_iMaxNominatedMaps = iMaxNominatedMaps; }; - int GetMaxNominatedMaps() { return m_iMaxNominatedMaps; }; - std::pair> AddMapNomination(CPlayerSlot iPlayerSlot, const char* sMapSubstring); - bool IsMapIndexEnabled(int iMapIndex); - int GetTotalNominations(int iMapIndex); - std::pair> ForceNextMap(const char* sMapSubstring); - int GetMapListSize() { return m_vecMapList.Count(); }; - const char* GetMapName(int iMapIndex) { return m_vecMapList[iMapIndex].GetName(); }; - uint64 GetMapWorkshopId(int iMapIndex) { return m_vecMapList[iMapIndex].GetWorkshopId(); }; - void ClearPlayerInfo(int iSlot); - bool IsVoteOngoing() { return m_bIsVoteOngoing; } - bool IsIntermissionAllowed(); - bool IsMapListLoaded() { return m_bMapListLoaded; } - CUtlStringList CreateWorkshopMapGroup(); - void QueueMapDownload(PublishedFileId_t iWorkshopId); - void PrintDownloadProgress(); - void SetCurrentWorkshopMap(uint64 iCurrentWorkshopMap) { m_iCurrentWorkshopMap = iCurrentWorkshopMap; m_strCurrentMap = ""; } - void SetCurrentMap(std::string strCurrentMap) { m_iCurrentWorkshopMap = 0; m_strCurrentMap = strCurrentMap; } - uint64 GetCurrentWorkshopMap() { return m_iCurrentWorkshopMap; } - const char* GetCurrentMap() { return m_strCurrentMap.c_str(); } - int GetDownloadQueueSize() { return m_DownloadQueue.Count(); } - int GetCurrentMapIndex() { return m_iCurrentMapIndex; } - void SetCurrentMapIndex(int iMapIndex) { m_iCurrentMapIndex = iMapIndex; } - int GetMapMinPlayers(int iMapIndex) { return m_vecMapList[iMapIndex].GetMinPlayers(); } - int GetMapMaxPlayers(int iMapIndex) { return m_vecMapList[iMapIndex].GetMaxPlayers(); } - bool GetMapEnabledStatus(int iMapIndex) { return m_vecMapList[iMapIndex].IsEnabled(); } - int GetDefaultMapCooldown() { return m_iDefaultMapCooldown; } - void SetDefaultMapCooldown(int iMapCooldown) { m_iDefaultMapCooldown = iMapCooldown; } - void ClearInvalidNominations(); - int GetForcedNextMap() { return m_iForcedNextMapIndex; } + CMapVoteSystem() + { + // Initialize the nomination / vote arrays to -1 + for (int i = 0; i < MAXPLAYERS; i++) + { + m_arrPlayerNominations[i] = -1; + m_arrPlayerVotes[i] = -1; + } + } + bool LoadMapList(); + void OnLevelInit(const char* pMapName); + void StartVote(); + void FinishVote(); + bool RegisterPlayerVote(CPlayerSlot iPlayerSlot, int iVoteOption); + std::vector GetMapIndexesFromSubstring(const char* sMapSubstring); + int GetMapIndexFromString(const char* sMapString); + int GetCooldownMap(int iMapIndex) { return m_vecMapList[iMapIndex].GetCooldown(); }; + void PutMapOnCooldown(int iMapIndex) { m_vecMapList[iMapIndex].ResetCooldownToBase(); }; + void DecrementAllMapCooldowns(); + void SetMaxNominatedMaps(int iMaxNominatedMaps) { m_iMaxNominatedMaps = iMaxNominatedMaps; }; + int GetMaxNominatedMaps() { return m_iMaxNominatedMaps; }; + std::pair> AddMapNomination(CPlayerSlot iPlayerSlot, const char* sMapSubstring); + bool IsMapIndexEnabled(int iMapIndex); + int GetTotalNominations(int iMapIndex); + std::pair> ForceNextMap(const char* sMapSubstring); + int GetMapListSize() { return m_vecMapList.Count(); }; + const char* GetMapName(int iMapIndex) { return m_vecMapList[iMapIndex].GetName(); }; + uint64 GetMapWorkshopId(int iMapIndex) { return m_vecMapList[iMapIndex].GetWorkshopId(); }; + void ClearPlayerInfo(int iSlot); + bool IsVoteOngoing() { return m_bIsVoteOngoing; } + bool IsIntermissionAllowed(); + bool IsMapListLoaded() { return m_bMapListLoaded; } + CUtlStringList CreateWorkshopMapGroup(); + void QueueMapDownload(PublishedFileId_t iWorkshopId); + void PrintDownloadProgress(); + void SetCurrentWorkshopMap(uint64 iCurrentWorkshopMap) + { + m_iCurrentWorkshopMap = iCurrentWorkshopMap; + m_strCurrentMap = ""; + } + void SetCurrentMap(std::string strCurrentMap) + { + m_iCurrentWorkshopMap = 0; + m_strCurrentMap = strCurrentMap; + } + uint64 GetCurrentWorkshopMap() { return m_iCurrentWorkshopMap; } + const char* GetCurrentMap() { return m_strCurrentMap.c_str(); } + int GetDownloadQueueSize() { return m_DownloadQueue.Count(); } + int GetCurrentMapIndex() { return m_iCurrentMapIndex; } + void SetCurrentMapIndex(int iMapIndex) { m_iCurrentMapIndex = iMapIndex; } + int GetMapMinPlayers(int iMapIndex) { return m_vecMapList[iMapIndex].GetMinPlayers(); } + int GetMapMaxPlayers(int iMapIndex) { return m_vecMapList[iMapIndex].GetMaxPlayers(); } + bool GetMapEnabledStatus(int iMapIndex) { return m_vecMapList[iMapIndex].IsEnabled(); } + int GetDefaultMapCooldown() { return m_iDefaultMapCooldown; } + void SetDefaultMapCooldown(int iMapCooldown) { m_iDefaultMapCooldown = iMapCooldown; } + void ClearInvalidNominations(); + int GetForcedNextMap() { return m_iForcedNextMapIndex; } private: - int WinningMapIndex(); - bool UpdateWinningMap(); - void GetNominatedMapsForVote(CUtlVector& vecChosenNominatedMaps); - bool WriteMapCooldownsToFile(); + int WinningMapIndex(); + bool UpdateWinningMap(); + void GetNominatedMapsForVote(CUtlVector& vecChosenNominatedMaps); + bool WriteMapCooldownsToFile(); - STEAM_GAMESERVER_CALLBACK_MANUAL(CMapVoteSystem, OnMapDownloaded, DownloadItemResult_t, m_CallbackDownloadItemResult); - CUtlQueue m_DownloadQueue; + STEAM_GAMESERVER_CALLBACK_MANUAL(CMapVoteSystem, OnMapDownloaded, DownloadItemResult_t, m_CallbackDownloadItemResult); + CUtlQueue m_DownloadQueue; - CUtlVector m_vecMapList; - int m_arrPlayerNominations[MAXPLAYERS]; - int m_iForcedNextMapIndex = -1; - int m_iDefaultMapCooldown = 10; - int m_iMaxNominatedMaps = 10; - int m_iRandomWinnerShift = 0; - int m_arrPlayerVotes[MAXPLAYERS]; - int m_iCurrentMapIndex; - bool m_bIsVoteOngoing = false; - bool m_bMapListLoaded = false; - bool m_bIntermissionStarted = false; - uint64 m_iCurrentWorkshopMap = 0; - std::string m_strCurrentMap = ""; + CUtlVector m_vecMapList; + int m_arrPlayerNominations[MAXPLAYERS]; + int m_iForcedNextMapIndex = -1; + int m_iDefaultMapCooldown = 10; + int m_iMaxNominatedMaps = 10; + int m_iRandomWinnerShift = 0; + int m_arrPlayerVotes[MAXPLAYERS]; + int m_iCurrentMapIndex; + bool m_bIsVoteOngoing = false; + bool m_bMapListLoaded = false; + bool m_bIntermissionStarted = false; + uint64 m_iCurrentWorkshopMap = 0; + std::string m_strCurrentMap = ""; }; extern CMapVoteSystem* g_pMapVoteSystem; \ No newline at end of file diff --git a/src/mempatch.cpp b/src/mempatch.cpp index 4dc6c506..3b4b94c4 100644 --- a/src/mempatch.cpp +++ b/src/mempatch.cpp @@ -19,13 +19,13 @@ #include "mempatch.h" #include "common.h" -#include "utils/module.h" #include "tier0/dbg.h" #include "tier1/strtools.h" +#include "utils/module.h" #include "tier0/memdbgon.h" -bool CMemPatch::PerformPatch(CGameConfig *gameConfig) +bool CMemPatch::PerformPatch(CGameConfig* gameConfig) { // If we already have an address, no need to look for it again if (!m_pPatchAddress) @@ -36,7 +36,7 @@ bool CMemPatch::PerformPatch(CGameConfig *gameConfig) return false; } - const char *patch = gameConfig->GetPatch(m_pszName); + const char* patch = gameConfig->GetPatch(m_pszName); if (!patch) { Panic("Failed to find patch for %s\n", m_pszName); diff --git a/src/mempatch.h b/src/mempatch.h index 09160d69..33b65b93 100644 --- a/src/mempatch.h +++ b/src/mempatch.h @@ -19,14 +19,14 @@ #pragma once +#include "gameconfig.h" #include "platform.h" #include "utils/module.h" -#include "gameconfig.h" class CMemPatch { public: - CMemPatch(const char *pSignatureName, const char *pszName ,const char *pOffsetName = "") : + CMemPatch(const char* pSignatureName, const char* pszName, const char* pOffsetName = "") : m_pSignatureName(pSignatureName), m_pszName(pszName), m_pOffsetName(pOffsetName) { m_pModule = nullptr; @@ -38,19 +38,19 @@ class CMemPatch m_iOffset = 0; } - bool PerformPatch(CGameConfig *gameConfig); + bool PerformPatch(CGameConfig* gameConfig); void UndoPatch(); uintptr_t GetPatchAddress() { return m_pPatchAddress; } private: - CModule **m_pModule; - const byte *m_pSignature; - const byte *m_pPatch; - byte *m_pOriginalBytes; - const char *m_pSignatureName; - const char *m_pszName; - const char *m_pOffsetName; + CModule** m_pModule; + const byte* m_pSignature; + const byte* m_pPatch; + byte* m_pOriginalBytes; + const char* m_pSignatureName; + const char* m_pszName; + const char* m_pOffsetName; int m_iOffset; size_t m_iPatchLength; uintptr_t m_pPatchAddress; diff --git a/src/netmessages.h b/src/netmessages.h index ec291f7a..f0dc9762 100644 --- a/src/netmessages.h +++ b/src/netmessages.h @@ -2,12 +2,12 @@ #define NETMESSAGES_H #ifdef _WIN32 -#pragma once + #pragma once #endif -#include #include #include +#include #include class CNETMsg_Tick_t : public CNetMessagePB diff --git a/src/panoramavote.cpp b/src/panoramavote.cpp index f4657f24..8ca12eb7 100644 --- a/src/panoramavote.cpp +++ b/src/panoramavote.cpp @@ -19,23 +19,23 @@ #include "cstrike15_usermessages.pb.h" -#include "utlstring.h" +#include "commands.h" #include "common.h" #include "cs2fixes.h" -#include "panoramavote.h" -#include "commands.h" +#include "ctimer.h" #include "engine/igameeventsystem.h" +#include "entity/cvotecontroller.h" #include "networksystem/inetworkmessages.h" +#include "panoramavote.h" #include "recipientfilters.h" #include "utils/entity.h" -#include "entity/cvotecontroller.h" -#include "ctimer.h" +#include "utlstring.h" #include "tier0/memdbgon.h" extern IGameEventManager2* g_gameEventManager; -extern IGameEventSystem *g_gameEventSystem; -extern INetworkMessages *g_pNetworkMessages; +extern IGameEventSystem* g_gameEventSystem; +extern INetworkMessages* g_pNetworkMessages; CPanoramaVoteHandler* g_pPanoramaVoteHandler = nullptr; @@ -56,9 +56,7 @@ void CPanoramaVoteHandler::Init() CVoteController* pVoteController = nullptr; while (nullptr != (pVoteController = (CVoteController*)UTIL_FindEntityByClassname(pVoteController, "vote_controller"))) - { hVoteController = pVoteController->GetHandle(); - } } // Called by vote_cast event @@ -75,8 +73,8 @@ void CPanoramaVoteHandler::VoteCast(IGameEvent* pEvent) } CheckForEarlyVoteClose(); - - //ClientPrintAll(HUD_PRINTTALK, "VOTE CAST: slot:%d option:%d", pVoter->GetPlayerSlot(), pEvent->GetInt("vote_option")); + + // ClientPrintAll(HUD_PRINTTALK, "VOTE CAST: slot:%d option:%d", pVoter->GetPlayerSlot(), pEvent->GetInt("vote_option")); } void CPanoramaVoteHandler::RemovePlayerFromVote(int iSlot) @@ -86,16 +84,10 @@ void CPanoramaVoteHandler::RemovePlayerFromVote(int iSlot) bool found = false; for (int i = 0; i < m_iVoterCount; i++) - { if (m_iVoters[i] == iSlot) - { found = true; - } else if (found) - { m_iVoters[i - 1] = m_iVoters[i]; - } - } if (found) { @@ -113,12 +105,8 @@ bool CPanoramaVoteHandler::IsPlayerInVotePool(int iSlot) return false; for (int i = 0; i < m_iVoterCount; i++) - { if (m_iVoters[i] == iSlot) - { return true; - } - } return false; } @@ -141,7 +129,7 @@ bool CPanoramaVoteHandler::RedrawVoteToClient(int iSlot) CRecipientFilter pFilter; pFilter.AddRecipient(CPlayerSlot(iSlot)); SendVoteStartUM(&pFilter); - + return true; } @@ -167,7 +155,7 @@ bool CPanoramaVoteHandler::IsVoteInProgress() return m_bIsVoteInProgress; } -bool CPanoramaVoteHandler::SendYesNoVote(float flDuration, int iCaller, const char* sVoteTitle, const char* sDetailStr, IRecipientFilter *pFilter, YesNoVoteResult resultCallback, YesNoVoteHandler handler = nullptr) +bool CPanoramaVoteHandler::SendYesNoVote(float flDuration, int iCaller, const char* sVoteTitle, const char* sDetailStr, IRecipientFilter* pFilter, YesNoVoteResult resultCallback, YesNoVoteHandler handler = nullptr) { if (!hVoteController.Get() || m_bIsVoteInProgress) return false; @@ -189,7 +177,7 @@ bool CPanoramaVoteHandler::SendYesNoVote(float flDuration, int iCaller, const ch hVoteController->m_iActiveIssueIndex = 2; hVoteController->m_iOnlyTeamToVote = -1; // use the recipient filter param to handle who votes - + m_VoteResult = resultCallback; m_VoteHandler = handler; @@ -202,20 +190,16 @@ bool CPanoramaVoteHandler::SendYesNoVote(float flDuration, int iCaller, const ch SendVoteStartUM(pFilter); if (m_VoteHandler != nullptr) - { (m_VoteHandler)(YesNoVoteAction::VoteAction_Start, 0, 0); - } - + int voteNum = m_iVoteCount; - new CTimer(flDuration, false, true, [voteNum]() - { - // Ensure we dont end the wrong vote - if(voteNum == g_pPanoramaVoteHandler->m_iVoteCount) - g_pPanoramaVoteHandler->EndVote(YesNoVoteEndReason::VoteEnd_TimeUp); - return -1.0; - } - ); - + new CTimer(flDuration, false, true, [voteNum]() { + // Ensure we dont end the wrong vote + if (voteNum == g_pPanoramaVoteHandler->m_iVoteCount) + g_pPanoramaVoteHandler->EndVote(YesNoVoteEndReason::VoteEnd_TimeUp); + return -1.0; + }); + return true; } @@ -227,9 +211,9 @@ bool CPanoramaVoteHandler::SendYesNoVoteToAll(float flDuration, int iCaller, con return SendYesNoVote(flDuration, iCaller, sVoteTitle, sDetailStr, &filter, resultCallback, handler); } -void CPanoramaVoteHandler::SendVoteStartUM(IRecipientFilter *pFilter) +void CPanoramaVoteHandler::SendVoteStartUM(IRecipientFilter* pFilter) { - INetworkMessageInternal *pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("VoteStart"); + INetworkMessageInternal* pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("VoteStart"); auto data = pNetMsg->AllocateMessage()->ToPB(); data->set_team(-1); @@ -244,7 +228,7 @@ void CPanoramaVoteHandler::SendVoteStartUM(IRecipientFilter *pFilter) delete data; } -void CPanoramaVoteHandler::InitVoters(IRecipientFilter *pFilter) +void CPanoramaVoteHandler::InitVoters(IRecipientFilter* pFilter) { // Clear any old info m_iVoterCount = 0; @@ -256,7 +240,7 @@ void CPanoramaVoteHandler::InitVoters(IRecipientFilter *pFilter) for (int i = 0; i < VOTE_UNCAST; i++) hVoteController->m_nVoteOptionCount[i] = 0; - + m_iVoterCount = pFilter->GetRecipientCount(); for (int i = 0, j = 0; i < m_iVoterCount; i++) { @@ -278,12 +262,10 @@ void CPanoramaVoteHandler::CheckForEarlyVoteClose() if (votes >= m_iVoterCount) { // Do this next frame to prevent a crash - new CTimer(0.0, false, true, []() - { - g_pPanoramaVoteHandler->EndVote(YesNoVoteEndReason::VoteEnd_AllVotes); - return -1.0; - } - ); + new CTimer(0.0, false, true, []() { + g_pPanoramaVoteHandler->EndVote(YesNoVoteEndReason::VoteEnd_AllVotes); + return -1.0; + }); } } @@ -296,25 +278,25 @@ void CPanoramaVoteHandler::EndVote(YesNoVoteEndReason reason) switch (reason) { - case VoteEnd_AllVotes: - Message("[Vote Ending] [id:%d] All possible players voted.", m_iVoteCount); - break; - case VoteEnd_TimeUp: - Message("[Vote Ending] [id:%d] Time ran out.", m_iVoteCount); - break; - case VoteEnd_Cancelled: - Message("[Vote Ending] [id:%d] The vote has been cancelled.", m_iVoteCount); - break; + case VoteEnd_AllVotes: + Message("[Vote Ending] [id:%d] All possible players voted.", m_iVoteCount); + break; + case VoteEnd_TimeUp: + Message("[Vote Ending] [id:%d] Time ran out.", m_iVoteCount); + break; + case VoteEnd_Cancelled: + Message("[Vote Ending] [id:%d] The vote has been cancelled.", m_iVoteCount); + break; } // Cycle global vote counter - if (m_iVoteCount == 99) m_iVoteCount = 0; - else m_iVoteCount++; - + if (m_iVoteCount == 99) + m_iVoteCount = 0; + else + m_iVoteCount++; + if (m_VoteHandler != nullptr) - { (m_VoteHandler)(YesNoVoteAction::VoteAction_End, reason, 0); - } if (!hVoteController.Get()) { @@ -334,7 +316,7 @@ void CPanoramaVoteHandler::EndVote(YesNoVoteEndReason reason) info.yes_votes = hVoteController->m_nVoteOptionCount[VOTE_OPTION1]; info.no_votes = hVoteController->m_nVoteOptionCount[VOTE_OPTION2]; info.num_votes = info.yes_votes + info.no_votes; - + for (int i = 0; i < MAXPLAYERS; i++) { if (i < m_iVoterCount) @@ -350,20 +332,16 @@ void CPanoramaVoteHandler::EndVote(YesNoVoteEndReason reason) } bool passed = (m_VoteResult)(info); - //TODO usermessage correctly + // TODO usermessage correctly if (passed) - { SendVotePassed(); - } else - { SendVoteFailed(); - } } void CPanoramaVoteHandler::SendVoteFailed() { - INetworkMessageInternal *pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("VoteFailed"); + INetworkMessageInternal* pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("VoteFailed"); auto data = pNetMsg->AllocateMessage()->ToPB(); diff --git a/src/panoramavote.h b/src/panoramavote.h index 2bf81115..76be16f5 100644 --- a/src/panoramavote.h +++ b/src/panoramavote.h @@ -20,18 +20,18 @@ #pragma once #include "common.h" +#include "entity/cvotecontroller.h" #include "eventlistener.h" #include "irecipientfilter.h" #include "utils/entity.h" -#include "entity/cvotecontroller.h" #define VOTE_CALLER_SERVER 99 enum CastVote { VOTE_NOTINCLUDED = -1, - VOTE_OPTION1, // Use this for Yes - VOTE_OPTION2, // Use this for No + VOTE_OPTION1, // Use this for Yes + VOTE_OPTION2, // Use this for No VOTE_OPTION3, VOTE_OPTION4, VOTE_OPTION5, @@ -40,28 +40,28 @@ enum CastVote enum YesNoVoteEndReason { - VoteEnd_AllVotes, // All possible votes were cast - VoteEnd_TimeUp, // Time ran out - VoteEnd_Cancelled, // The vote got cancelled + VoteEnd_AllVotes, // All possible votes were cast + VoteEnd_TimeUp, // Time ran out + VoteEnd_Cancelled, // The vote got cancelled }; enum YesNoVoteAction { VoteAction_Start, // nothing passed VoteAction_Vote, // param1 = client slot, param2 = choice (VOTE_OPTION1=yes, VOTE_OPTION2=no) - VoteAction_End, // param1 = YesNoVoteEndReason reason why the vote ended + VoteAction_End, // param1 = YesNoVoteEndReason reason why the vote ended }; #define VOTEINFO_CLIENT_SLOT 0 #define VOTEINFO_CLIENT_ITEM 1 struct YesNoVoteInfo { - int num_votes; // Number of votes tallied in total - int yes_votes; // Number of votes for yes - int no_votes; // Number of votes for no - int num_clients; // Number of clients who could vote - int clientInfo[MAXPLAYERS][2]; // Client voting info, user VOTEINFO_CLIENT_ defines - // Anything >= [num_clients] is VOTE_NOTINCLUDED, VOTE_UNCAST = client didn't vote + int num_votes; // Number of votes tallied in total + int yes_votes; // Number of votes for yes + int no_votes; // Number of votes for no + int num_clients; // Number of clients who could vote + int clientInfo[MAXPLAYERS][2]; // Client voting info, user VOTEINFO_CLIENT_ defines + // Anything >= [num_clients] is VOTE_NOTINCLUDED, VOTE_UNCAST = client didn't vote }; // Used to handle events relating to the vote menu @@ -96,34 +96,34 @@ class CPanoramaVoteHandler // Removes a client's vote and redraws the vote // True if client was in the vote, false if no ongoing vote bool RedrawVoteToClient(int iSlot); - + /* Returns true if a vote is in progress, false otherwise */ bool IsVoteInProgress(); - + // Ends the ongoing vote with the specified reason void EndVote(YesNoVoteEndReason reason); /* Start a new Yes/No vote - * - * @param flDuration Maximum time to leave vote active for - * @param iCaller Player slot of the vote caller. Use VOTE_CALLER_SERVER for 'Server'. - * @param sVoteTitle Translation string to use as the vote message. (Only '#SFUI_vote' or '#Panorama_vote' strings) - * @param sDetailStr Extra string used in some vote translation strings. - * @param pFilter Recipient filter with all the clients who are allowed to participate in the vote. - * @param handler Called when a menu action is completed. - * @param callback Called when the vote has finished. - */ - bool SendYesNoVote(float flDuration, int iCaller, const char* sVoteTitle, const char* sDetailStr, IRecipientFilter *pFilter, YesNoVoteResult resultCallback, YesNoVoteHandler handler); + * + * @param flDuration Maximum time to leave vote active for + * @param iCaller Player slot of the vote caller. Use VOTE_CALLER_SERVER for 'Server'. + * @param sVoteTitle Translation string to use as the vote message. (Only '#SFUI_vote' or '#Panorama_vote' strings) + * @param sDetailStr Extra string used in some vote translation strings. + * @param pFilter Recipient filter with all the clients who are allowed to participate in the vote. + * @param handler Called when a menu action is completed. + * @param callback Called when the vote has finished. + */ + bool SendYesNoVote(float flDuration, int iCaller, const char* sVoteTitle, const char* sDetailStr, IRecipientFilter* pFilter, YesNoVoteResult resultCallback, YesNoVoteHandler handler); /* Start a new Yes/No vote with all players included - * - * @param flDuration Maximum time to leave vote active for - * @param iCaller Player slot of the vote caller. Use VOTE_CALLER_SERVER for 'Server'. - * @param sVoteTitle Translation string to use as the vote message. (Only '#SFUI_vote' or '#Panorama_vote' strings) - * @param sDetailStr Extra string used in some vote translation strings. - * @param handler Called when a menu action is completed. - * @param callback Called when the vote has finished. - */ + * + * @param flDuration Maximum time to leave vote active for + * @param iCaller Player slot of the vote caller. Use VOTE_CALLER_SERVER for 'Server'. + * @param sVoteTitle Translation string to use as the vote message. (Only '#SFUI_vote' or '#Panorama_vote' strings) + * @param sDetailStr Extra string used in some vote translation strings. + * @param handler Called when a menu action is completed. + * @param callback Called when the vote has finished. + */ bool SendYesNoVoteToAll(float flDuration, int iCaller, const char* sVoteTitle, const char* sDetailStr, YesNoVoteResult resultCallback, YesNoVoteHandler handler); void SendVoteFailed(); @@ -147,4 +147,4 @@ class CPanoramaVoteHandler void UpdateVoteCounts(); }; -extern CPanoramaVoteHandler *g_pPanoramaVoteHandler; +extern CPanoramaVoteHandler* g_pPanoramaVoteHandler; diff --git a/src/patches.cpp b/src/patches.cpp index 6b772755..a6479d29 100644 --- a/src/patches.cpp +++ b/src/patches.cpp @@ -17,49 +17,49 @@ * this program. If not, see . */ +#include "patches.h" +#include "addresses.h" #include "common.h" -#include "mempatch.h" -#include "icvar.h" -#include "irecipientfilter.h" +#include "entity/cbasemodelentity.h" #include "entity/ccsplayercontroller.h" #include "entity/ccsplayerpawn.h" -#include "entity/cbasemodelentity.h" -#include "addresses.h" -#include "patches.h" +#include "icvar.h" +#include "irecipientfilter.h" +#include "mempatch.h" #include "tier0/memdbgon.h" -extern CGameConfig *g_GameConfig; +extern CGameConfig* g_GameConfig; CMemPatch g_CommonPatches[] = -{ - CMemPatch("ServerMovementUnlock", "ServerMovementUnlock"), - CMemPatch("CheckJumpButtonWater", "FixWaterFloorJump"), - CMemPatch("WaterLevelGravity", "WaterLevelGravity"), - CMemPatch("CPhysBox_Use", "CPhysBox_Use"), - CMemPatch("BotNavIgnore", "BotNavIgnore"), + { + CMemPatch("ServerMovementUnlock", "ServerMovementUnlock"), + CMemPatch("CheckJumpButtonWater", "FixWaterFloorJump"), + CMemPatch("WaterLevelGravity", "WaterLevelGravity"), + CMemPatch("CPhysBox_Use", "CPhysBox_Use"), + CMemPatch("BotNavIgnore", "BotNavIgnore"), #ifndef _WIN32 - // Linux checks for the nav mesh in each bot_add command, so we patch 3 times - CMemPatch("BotNavIgnore", "BotNavIgnore"), - CMemPatch("BotNavIgnore", "BotNavIgnore"), + // Linux checks for the nav mesh in each bot_add command, so we patch 3 times + CMemPatch("BotNavIgnore", "BotNavIgnore"), + CMemPatch("BotNavIgnore", "BotNavIgnore"), #endif }; CMemPatch g_ClientPatches[] = -{ - CMemPatch("ClientMovementUnlock", "ClientMovementUnlock"), + { + CMemPatch("ClientMovementUnlock", "ClientMovementUnlock"), }; #ifdef _WIN32 CMemPatch g_ToolsPatches[] = -{ - // Remove some -nocustomermachine checks without needing -nocustomermachine itself - // as it can break stuff like the asset browser. This is mainly to enable device selection in compiles - // And yes, it's the exact same signature appearing 4 times, each unhides a certain hammer compile option - CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), - CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), - CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), - CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), + { + // Remove some -nocustomermachine checks without needing -nocustomermachine itself + // as it can break stuff like the asset browser. This is mainly to enable device selection in compiles + // And yes, it's the exact same signature appearing 4 times, each unhides a certain hammer compile option + CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), + CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), + CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), + CMemPatch("HammerNoCustomerMachine", "HammerNoCustomerMachine"), }; #endif @@ -88,23 +88,19 @@ CON_COMMAND_F(cs2f_movement_unlocker_enable, "Whether to enable movement unlocke } } -bool InitPatches(CGameConfig *g_GameConfig) +bool InitPatches(CGameConfig* g_GameConfig) { bool success = true; for (int i = 0; i < sizeof(g_CommonPatches) / sizeof(*g_CommonPatches); i++) - { if (!g_CommonPatches[i].PerformPatch(g_GameConfig)) success = false; - } // Dedicated servers don't load client if (!CommandLine()->HasParm("-dedicated")) { for (int i = 0; i < sizeof(g_ClientPatches) / sizeof(*g_ClientPatches); i++) - { if (!g_ClientPatches[i].PerformPatch(g_GameConfig)) success = false; - } } #ifdef _WIN32 @@ -122,16 +118,12 @@ void UndoPatches() g_CommonPatches[i].UndoPatch(); if (!CommandLine()->HasParm("-dedicated")) - { for (int i = 0; i < sizeof(g_ClientPatches) / sizeof(*g_ClientPatches); i++) g_ClientPatches[i].UndoPatch(); - } #ifdef _WIN32 if (CommandLine()->HasParm("-tools")) - { for (int i = 0; i < sizeof(g_ToolsPatches) / sizeof(*g_ToolsPatches); i++) g_ToolsPatches[i].UndoPatch(); - } #endif } diff --git a/src/patches.h b/src/patches.h index 255b64b4..54485b4e 100644 --- a/src/patches.h +++ b/src/patches.h @@ -2,5 +2,5 @@ #include "gameconfig.h" -bool InitPatches(CGameConfig *gameConfig); +bool InitPatches(CGameConfig* gameConfig); void UndoPatches(); diff --git a/src/playermanager.cpp b/src/playermanager.cpp index 93553abb..ab97e01a 100644 --- a/src/playermanager.cpp +++ b/src/playermanager.cpp @@ -17,31 +17,30 @@ * this program. If not, see . */ -#include <../cs2fixes.h> -#include "utlstring.h" #include "playermanager.h" #include "adminsystem.h" #include "commands.h" +#include "ctime" +#include "ctimer.h" +#include "engine/igameeventsystem.h" +#include "entity/ccsplayercontroller.h" +#include "leader.h" #include "map_votes.h" -#include "user_preferences.h" +#include "networksystem/inetworkmessages.h" #include "panoramavote.h" -#include "entity/ccsplayercontroller.h" -#include "utils/entity.h" -#include "serversideclient.h" #include "recipientfilters.h" -#include "ctimer.h" -#include "ctime" -#include "leader.h" +#include "serversideclient.h" #include "tier0/vprof.h" -#include "networksystem/inetworkmessages.h" -#include "engine/igameeventsystem.h" +#include "user_preferences.h" +#include "utils/entity.h" +#include "utlstring.h" +#include <../cs2fixes.h> #include "tier0/memdbgon.h" - -extern IVEngineServer2 *g_pEngineServer2; -extern CGameEntitySystem *g_pEntitySystem; -extern CGlobalVars *gpGlobals; +extern IVEngineServer2* g_pEngineServer2; +extern CGameEntitySystem* g_pEntitySystem; +extern CGlobalVars* gpGlobals; extern IGameEventSystem* g_gameEventSystem; extern CUtlVector* GetClientList(); @@ -51,7 +50,8 @@ static bool g_bEnableMapSteamIds = false; FAKE_INT_CVAR(cs2f_admin_immunity, "Mode for which admin immunity system targetting allows: 0 - strictly lower, 1 - equal to or lower, 2 - ignore immunity levels", g_iAdminImmunityTargetting, 0, false) FAKE_BOOL_CVAR(cs2f_map_steamids_enable, "Whether to make Steam ID's available to maps", g_bEnableMapSteamIds, false, 0) -ZEPlayerHandle::ZEPlayerHandle() : m_Index(INVALID_ZEPLAYERHANDLE_INDEX) {}; +ZEPlayerHandle::ZEPlayerHandle() : + m_Index(INVALID_ZEPLAYERHANDLE_INDEX){}; ZEPlayerHandle::ZEPlayerHandle(CPlayerSlot slot) { @@ -59,27 +59,27 @@ ZEPlayerHandle::ZEPlayerHandle(CPlayerSlot slot) m_Parts.m_Serial = ++iZEPlayerHandleSerial; } -ZEPlayerHandle::ZEPlayerHandle(const ZEPlayerHandle &other) +ZEPlayerHandle::ZEPlayerHandle(const ZEPlayerHandle& other) { m_Index = other.m_Index; } -ZEPlayerHandle::ZEPlayerHandle(ZEPlayer *pZEPlayer) +ZEPlayerHandle::ZEPlayerHandle(ZEPlayer* pZEPlayer) { Set(pZEPlayer); } -bool ZEPlayerHandle::operator==(ZEPlayer *pZEPlayer) const +bool ZEPlayerHandle::operator==(ZEPlayer* pZEPlayer) const { return Get() == pZEPlayer; } -bool ZEPlayerHandle::operator!=(ZEPlayer *pZEPlayer) const +bool ZEPlayerHandle::operator!=(ZEPlayer* pZEPlayer) const { return Get() != pZEPlayer; } -void ZEPlayerHandle::Set(ZEPlayer *pZEPlayer) +void ZEPlayerHandle::Set(ZEPlayer* pZEPlayer) { if (pZEPlayer) m_Index = pZEPlayer->GetHandle().m_Index; @@ -87,16 +87,16 @@ void ZEPlayerHandle::Set(ZEPlayer *pZEPlayer) m_Index = INVALID_ZEPLAYERHANDLE_INDEX; } -ZEPlayer *ZEPlayerHandle::Get() const +ZEPlayer* ZEPlayerHandle::Get() const { - ZEPlayer *pZEPlayer = g_playerManager->GetPlayer((CPlayerSlot) m_Parts.m_PlayerSlot); + ZEPlayer* pZEPlayer = g_playerManager->GetPlayer((CPlayerSlot)m_Parts.m_PlayerSlot); if (!pZEPlayer) return nullptr; - + if (pZEPlayer->GetHandle().m_Index != m_Index) return nullptr; - + return pZEPlayer; } @@ -171,14 +171,15 @@ FAKE_FLOAT_CVAR(cs2f_flashlight_brightness, "How bright should flashlights be", FAKE_FLOAT_CVAR(cs2f_flashlight_distance, "How far flashlights should be from the player's head", g_flFlashLightDistance, 54.0f, false) FAKE_COLOR_CVAR(cs2f_flashlight_color, "What color to use for flashlights", g_clrFlashLightColor, false) FAKE_STRING_CVAR(cs2f_flashlight_attachment, "Which attachment to parent a flashlight to. " - "If the player model is not properly setup, you might have to use clip_limit here instead", g_sFlashLightAttachment, false) + "If the player model is not properly setup, you might have to use clip_limit here instead", + g_sFlashLightAttachment, false) void ZEPlayer::SpawnFlashLight() { if (GetFlashLight()) return; - CCSPlayerPawn *pPawn = (CCSPlayerPawn *)CCSPlayerController::FromSlot(GetPlayerSlot())->GetPawn(); + CCSPlayerPawn* pPawn = (CCSPlayerPawn*)CCSPlayerController::FromSlot(GetPlayerSlot())->GetPawn(); Vector origin = pPawn->GetAbsOrigin(); Vector forward; @@ -187,7 +188,7 @@ void ZEPlayer::SpawnFlashLight() origin.z += 64.0f; origin += forward * g_flFlashLightDistance; - CBarnLight *pLight = CreateEntityByName("light_barn"); + CBarnLight* pLight = CreateEntityByName("light_barn"); pLight->m_bEnabled = true; pLight->m_Color->SetColor(g_clrFlashLightColor[0], g_clrFlashLightColor[1], g_clrFlashLightColor[2]); @@ -203,7 +204,7 @@ void ZEPlayer::SpawnFlashLight() pLight->Teleport(&origin, &pPawn->m_angEyeAngles(), nullptr); // Have to use keyvalues for this since the schema prop is a resource handle - CEntityKeyValues *pKeyValues = new CEntityKeyValues(); + CEntityKeyValues* pKeyValues = new CEntityKeyValues(); pKeyValues->SetString("lightcookie", "materials/effects/lightcookies/flashlight.vtex"); pLight->DispatchSpawn(pKeyValues); @@ -220,7 +221,7 @@ void ZEPlayer::ToggleFlashLight() CSingleRecipientFilter filter(GetPlayerSlot()); CCSPlayerController::FromSlot(GetPlayerSlot())->EmitSoundFilter(filter, "HudChat.Message"); - CBarnLight *pLight = GetFlashLight(); + CBarnLight* pLight = GetFlashLight(); // Create a flashlight if we don't have one, and don't bother with the input since it spawns enabled if (!pLight) @@ -261,7 +262,7 @@ bool ZEPlayer::IsFlooding() m_iFloodTokens++; } } - else if(m_iFloodTokens > 0) + else if (m_iFloodTokens > 0) { // Remove one flood token when player chats within time limit (slow decay) m_iFloodTokens--; @@ -276,7 +277,7 @@ void PrecacheBeaconParticle(IEntityResourceManifest* pResourceManifest) pResourceManifest->AddResource(g_sBeaconParticle.c_str()); } -void ZEPlayer::StartBeacon(Color color, ZEPlayerHandle hGiver/* = 0*/) +void ZEPlayer::StartBeacon(Color color, ZEPlayerHandle hGiver /* = 0*/) { SetBeaconColor(color); @@ -307,18 +308,17 @@ void ZEPlayer::StartBeacon(Color color, ZEPlayerHandle hGiver/* = 0*/) int iTeamNum = pPlayer->m_iTeamNum; bool bLeaderBeacon = false; - ZEPlayer *pGiver = hGiver.Get(); + ZEPlayer* pGiver = hGiver.Get(); if (pGiver && pGiver->IsLeader()) bLeaderBeacon = true; - new CTimer(1.0f, false, false, [hPlayer, hParticle, hGiver, iTeamNum, bLeaderBeacon]() - { - CParticleSystem *pParticle = hParticle.Get(); + new CTimer(1.0f, false, false, [hPlayer, hParticle, hGiver, iTeamNum, bLeaderBeacon]() { + CParticleSystem* pParticle = hParticle.Get(); if (!hPlayer.IsValid() || !pParticle) return -1.0f; - CCSPlayerController *pPlayer = CCSPlayerController::FromSlot((CPlayerSlot) hPlayer.GetPlayerSlot()); + CCSPlayerController* pPlayer = CCSPlayerController::FromSlot((CPlayerSlot)hPlayer.GetPlayerSlot()); if (pPlayer->m_iTeamNum < CS_TEAM_T || !pPlayer->m_hPlayerPawn->IsAlive() || pPlayer->m_iTeamNum != iTeamNum) { @@ -329,7 +329,7 @@ void ZEPlayer::StartBeacon(Color color, ZEPlayerHandle hGiver/* = 0*/) if (!bLeaderBeacon) return 1.0f; - ZEPlayer *pBeaconGiver = hGiver.Get(); + ZEPlayer* pBeaconGiver = hGiver.Get(); // Continue beacon, leader is not on the server. No reason to remove the beacon if (!pBeaconGiver) @@ -350,7 +350,7 @@ void ZEPlayer::EndBeacon() { SetBeaconColor(Color(0, 0, 0, 0)); - CParticleSystem *pParticle = m_hBeaconParticle.Get(); + CParticleSystem* pParticle = m_hBeaconParticle.Get(); if (pParticle) addresses::UTIL_Remove(pParticle); @@ -365,7 +365,7 @@ void ZEPlayer::CreateMark(float fDuration, Vector vecOrigin) UTIL_AddEntityIOEvent(m_handleMark.Get(), "DestroyImmediately", nullptr, nullptr, "", 0); UTIL_AddEntityIOEvent(m_handleMark.Get(), "Kill", nullptr, nullptr, "", 0.02f); } - + if (fDuration <= 0) return; @@ -391,17 +391,15 @@ int ZEPlayer::GetLeaderVoteCount() int iValidVoteCount = 0; for (int i = m_vecLeaderVotes.Count() - 1; i >= 0; i--) - { if (m_vecLeaderVotes[i].IsValid()) iValidVoteCount++; else m_vecLeaderVotes.Remove(i); - } return iValidVoteCount; } -bool ZEPlayer::HasPlayerVotedLeader(ZEPlayer *pPlayer) +bool ZEPlayer::HasPlayerVotedLeader(ZEPlayer* pPlayer) { FOR_EACH_VEC(m_vecLeaderVotes, i) { @@ -425,20 +423,20 @@ void ZEPlayer::PurgeLeaderVotes() void ZEPlayer::StartGlow(Color color, int duration) { SetGlowColor(color); - CCSPlayerController *pController = CCSPlayerController::FromSlot(m_slot); - CCSPlayerPawn *pPawn = (CCSPlayerPawn*)pController->GetPawn(); - - const char *pszModelName = pPawn->GetModelName(); - - CBaseModelEntity *pModelGlow = CreateEntityByName("prop_dynamic"); - CBaseModelEntity *pModelRelay = CreateEntityByName("prop_dynamic"); - CEntityKeyValues *pKeyValuesRelay = new CEntityKeyValues(); - + CCSPlayerController* pController = CCSPlayerController::FromSlot(m_slot); + CCSPlayerPawn* pPawn = (CCSPlayerPawn*)pController->GetPawn(); + + const char* pszModelName = pPawn->GetModelName(); + + CBaseModelEntity* pModelGlow = CreateEntityByName("prop_dynamic"); + CBaseModelEntity* pModelRelay = CreateEntityByName("prop_dynamic"); + CEntityKeyValues* pKeyValuesRelay = new CEntityKeyValues(); + pKeyValuesRelay->SetString("model", pszModelName); pKeyValuesRelay->SetInt64("spawnflags", 256U); pKeyValuesRelay->SetInt("rendermode", kRenderNone); - CEntityKeyValues *pKeyValuesGlow = new CEntityKeyValues(); + CEntityKeyValues* pKeyValuesGlow = new CEntityKeyValues(); pKeyValuesGlow->SetString("model", pszModelName); pKeyValuesGlow->SetInt64("spawnflags", 256U); pKeyValuesGlow->SetColor("glowcolor", color); @@ -453,32 +451,31 @@ void ZEPlayer::StartGlow(Color color, int duration) pModelGlow->AcceptInput("FollowEntity", "!activator", pModelRelay); m_hGlowModel.Set(pModelGlow); - + CHandle hGlowModel = m_hGlowModel; CHandle hPawn = pPawn->GetHandle(); int iTeamNum = hPawn->m_iTeamNum(); // check if player's team or model changed - new CTimer(0.5f, false, false, [hGlowModel, hPawn, iTeamNum]() - { - CBaseModelEntity *pModel = hGlowModel.Get(); - CCSPlayerPawn *pawn = hPawn.Get(); + new CTimer(0.5f, false, false, [hGlowModel, hPawn, iTeamNum]() { + CBaseModelEntity* pModel = hGlowModel.Get(); + CCSPlayerPawn* pawn = hPawn.Get(); if (!pawn || !pModel) return -1.0f; if (pawn->m_iTeamNum != iTeamNum || strcmp(pModel->GetModelName(), pawn->GetModelName())) { - CGameSceneNode *pParentSceneNode = pModel->m_CBodyComponent()->m_pSceneNode()->m_pParent(); + CGameSceneNode* pParentSceneNode = pModel->m_CBodyComponent()->m_pSceneNode()->m_pParent(); if (!pParentSceneNode) return -1.0f; - CBaseModelEntity *pModelParent = (CBaseModelEntity*)pParentSceneNode->m_pOwner(); + CBaseModelEntity* pModelParent = (CBaseModelEntity*)pParentSceneNode->m_pOwner(); if (pModelParent) addresses::UTIL_Remove(pModelParent); - + return -1.0f; } @@ -488,20 +485,19 @@ void ZEPlayer::StartGlow(Color color, int duration) // kill glow after duration, if provided if (duration < 1) return; - - new CTimer((float)duration, false, false, [hGlowModel]() - { - CBaseModelEntity *pModel = hGlowModel.Get(); + + new CTimer((float)duration, false, false, [hGlowModel]() { + CBaseModelEntity* pModel = hGlowModel.Get(); if (!pModel) return -1.0f; - CGameSceneNode *pParentSceneNode = pModel->m_CBodyComponent()->m_pSceneNode()->m_pParent(); + CGameSceneNode* pParentSceneNode = pModel->m_CBodyComponent()->m_pSceneNode()->m_pParent(); if (!pParentSceneNode) return -1.0f; - CBaseModelEntity *pModelParent = (CBaseModelEntity*)pParentSceneNode->m_pOwner(); + CBaseModelEntity* pModelParent = (CBaseModelEntity*)pParentSceneNode->m_pOwner(); if (pModelParent) addresses::UTIL_Remove(pModelParent); @@ -514,17 +510,17 @@ void ZEPlayer::EndGlow() { SetGlowColor(Color(0, 0, 0, 0)); - CBaseModelEntity *pGlowModel = m_hGlowModel.Get(); + CBaseModelEntity* pGlowModel = m_hGlowModel.Get(); if (!pGlowModel) return; - CGameSceneNode *pParentSceneNode = pGlowModel->m_CBodyComponent()->m_pSceneNode()->m_pParent(); + CGameSceneNode* pParentSceneNode = pGlowModel->m_CBodyComponent()->m_pSceneNode()->m_pParent(); if (!pParentSceneNode) return; - CBaseModelEntity *pModelParent = (CBaseModelEntity*)pParentSceneNode->m_pOwner(); + CBaseModelEntity* pModelParent = (CBaseModelEntity*)pParentSceneNode->m_pOwner(); if (pModelParent) addresses::UTIL_Remove(pModelParent); @@ -594,7 +590,7 @@ bool CPlayerManager::OnClientConnected(CPlayerSlot slot, uint64 xuid, const char Message("%d connected\n", slot.Get()); - ZEPlayer *pPlayer = new ZEPlayer(slot); + ZEPlayer* pPlayer = new ZEPlayer(slot); pPlayer->SetUnauthenticatedSteamId(new CSteamID(xuid)); std::string ip(pszNetworkID); @@ -629,7 +625,7 @@ bool CPlayerManager::OnClientConnected(CPlayerSlot slot, uint64 xuid, const char g_pMapVoteSystem->ClearPlayerInfo(slot.Get()); g_pMapVoteSystem->ClearInvalidNominations(); - + return true; } @@ -679,20 +675,20 @@ void CPlayerManager::OnSteamAPIActivated() int g_iDelayAuthFailKick = 0; FAKE_INT_CVAR(cs2f_delay_auth_fail_kick, "How long in seconds to delay kicking players when their Steam authentication fails, use with sv_steamauth_enforce 0", g_iDelayAuthFailKick, 0, false); -void CPlayerManager::OnValidateAuthTicket(ValidateAuthTicketResponse_t *pResponse) +void CPlayerManager::OnValidateAuthTicket(ValidateAuthTicketResponse_t* pResponse) { uint64 iSteamId = pResponse->m_SteamID.ConvertToUint64(); Message("%s: SteamID=%llu Response=%d\n", __func__, iSteamId, pResponse->m_eAuthSessionResponse); - ZEPlayer *pPlayer = nullptr; + ZEPlayer* pPlayer = nullptr; - for (ZEPlayer *pPlayer : m_vecPlayers) + for (ZEPlayer* pPlayer : m_vecPlayers) { if (!pPlayer || pPlayer->IsFakeClient() || !(pPlayer->GetUnauthenticatedSteamId64() == iSteamId)) continue; - CCSPlayerController *pController = CCSPlayerController::FromSlot(pPlayer->GetPlayerSlot()); + CCSPlayerController* pController = CCSPlayerController::FromSlot(pPlayer->GetPlayerSlot()); switch (pResponse->m_eAuthSessionResponse) { @@ -721,8 +717,7 @@ void CPlayerManager::OnValidateAuthTicket(ValidateAuthTicketResponse_t *pRespons ClientPrint(pController, HUD_PRINTTALK, " \7WARNING: You will be kicked in %i seconds due to failed Steam authentication.\n", g_iDelayAuthFailKick); ZEPlayerHandle hPlayer = pPlayer->GetHandle(); - new CTimer(g_iDelayAuthFailKick, true, true, [hPlayer]() - { + new CTimer(g_iDelayAuthFailKick, true, true, [hPlayer]() { if (!hPlayer.IsValid()) return -1.f; @@ -760,12 +755,12 @@ void CPlayerManager::FlashLightThink() for (int i = 0; i < gpGlobals->maxClients; i++) { - CCSPlayerController *pPlayer = CCSPlayerController::FromSlot(i); + CCSPlayerController* pPlayer = CCSPlayerController::FromSlot(i); if (!pPlayer || !pPlayer->m_bPawnIsAlive()) continue; - uint64 *pButtons = pPlayer->GetPawn()->m_pMovementServices->m_nButtons().m_pButtonStates(); + uint64* pButtons = pPlayer->GetPawn()->m_pMovementServices->m_nButtons().m_pButtonStates(); // Check both to make sure flashlight is only toggled when the player presses the key if ((pButtons[0] & IN_LOOK_AT_WEAPON) && (pButtons[1] & IN_LOOK_AT_WEAPON)) @@ -823,26 +818,23 @@ void CPlayerManager::CheckHideDistances() // TODO: Unhide dead pawns if/when valve fixes the crash if (pTargetPawn && (!g_bHideTeammatesOnly || pTargetController->m_iTeamNum == team)) - { player->SetTransmit(j, pTargetPawn->GetAbsOrigin().DistToSqr(vecPosition) <= hideDistance * hideDistance); - } } } } } -static const char *g_szPlayerStates[] = -{ - "STATE_ACTIVE", - "STATE_WELCOME", - "STATE_PICKINGTEAM", - "STATE_PICKINGCLASS", - "STATE_DEATH_ANIM", - "STATE_DEATH_WAIT_FOR_KEY", - "STATE_OBSERVER_MODE", - "STATE_GUNGAME_RESPAWN", - "STATE_DORMANT" -}; +static const char* g_szPlayerStates[] = + { + "STATE_ACTIVE", + "STATE_WELCOME", + "STATE_PICKINGTEAM", + "STATE_PICKINGCLASS", + "STATE_DEATH_ANIM", + "STATE_DEATH_WAIT_FOR_KEY", + "STATE_OBSERVER_MODE", + "STATE_GUNGAME_RESPAWN", + "STATE_DORMANT"}; extern bool g_bEnableHide; @@ -850,12 +842,12 @@ void CPlayerManager::UpdatePlayerStates() { for (int i = 0; i < gpGlobals->maxClients; i++) { - ZEPlayer *pPlayer = GetPlayer(i); + ZEPlayer* pPlayer = GetPlayer(i); if (!pPlayer) continue; - CCSPlayerController *pController = CCSPlayerController::FromSlot(i); + CCSPlayerController* pController = CCSPlayerController::FromSlot(i); if (!pController) continue; @@ -873,7 +865,7 @@ void CPlayerManager::UpdatePlayerStates() // Send full update to people going in/out of spec as a mitigation for hide crashes if (g_bEnableHide && (iCurrentPlayerState == STATE_OBSERVER_MODE || iPreviousPlayerState == STATE_OBSERVER_MODE)) { - CServerSideClient *pClient = GetClientBySlot(i); + CServerSideClient* pClient = GetClientBySlot(i); if (pClient) pClient->ForceFullUpdate(); @@ -887,8 +879,7 @@ FAKE_BOOL_CVAR(cs2f_infinite_reserve_ammo, "Whether to enable infinite reserve a void CPlayerManager::SetupInfiniteAmmo() { - new CTimer(5.0f, false, true, []() - { + new CTimer(5.0f, false, true, []() { if (!g_bInfiniteAmmo) return 5.0f; @@ -908,7 +899,7 @@ void CPlayerManager::SetupInfiniteAmmo() CCSPlayer_WeaponServices* pWeaponServices = pPawn->m_pWeaponServices; - // it can sometimes be null when player joined on the very first round? + // it can sometimes be null when player joined on the very first round? if (!pWeaponServices) continue; @@ -966,8 +957,8 @@ ETargetError GetTargetError(CCSPlayerController* pPlayer, CCSPlayerController* p else if (iBlockedFlags & NO_UNAUTHENTICATED && !zpTarget->IsAuthenticated()) return ETargetError::UNAUTHENTICATED; else if (zpPlayer && !(iBlockedFlags & NO_IMMUNITY) - && ((g_iAdminImmunityTargetting == 0 && zpTarget->GetAdminImmunity() > zpPlayer->GetAdminImmunity()) - || (g_iAdminImmunityTargetting == 1 && zpTarget->GetAdminImmunity() <= zpPlayer->GetAdminImmunity() && pTarget != pPlayer))) + && ((g_iAdminImmunityTargetting == 0 && zpTarget->GetAdminImmunity() > zpPlayer->GetAdminImmunity()) + || (g_iAdminImmunityTargetting == 1 && zpTarget->GetAdminImmunity() <= zpPlayer->GetAdminImmunity() && pTarget != pPlayer))) return ETargetError::INSUFFICIENT_IMMUNITY_LEVEL; return ETargetError::NO_ERRORS; @@ -982,7 +973,7 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, bool bTargetMultiple = false; bool bTargetRandom = false; uint64 iInverseFlags = NO_TARGET_BLOCKS; - + if (!V_stricmp(pszTarget, "@me")) { nType = ETargetType::SELF; @@ -1022,7 +1013,6 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, bTargetMultiple = true; iBlockedFlags |= NO_COUNTER_TERRORIST | NO_SPECTATOR; - } else if (!V_stricmp(pszTarget, "@!t")) { @@ -1055,7 +1045,6 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, bTargetMultiple = true; iBlockedFlags |= NO_COUNTER_TERRORIST; - } else if (!V_stricmp(pszTarget, "@spec")) { @@ -1102,7 +1091,7 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, else if (!V_stricmp(pszTarget, "@randomt")) { nType = ETargetType::RANDOM_T; - + if (iBlockedFlags & NO_TERRORIST) return ETargetError::TERRORIST; else if (iBlockedFlags & NO_RANDOM) @@ -1114,7 +1103,7 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, else if (!V_stricmp(pszTarget, "@!randomt")) { nType = ETargetType::ALL_BUT_RANDOM_T; - + if (iBlockedFlags & NO_RANDOM) return ETargetError::RANDOM; @@ -1123,7 +1112,7 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, else if (!V_stricmp(pszTarget, "@randomct")) { nType = ETargetType::RANDOM_CT; - + if (iBlockedFlags & NO_COUNTER_TERRORIST) return ETargetError::COUNTER_TERRORIST; else if (iBlockedFlags & NO_RANDOM) @@ -1135,7 +1124,7 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, else if (!V_stricmp(pszTarget, "@!randomct")) { nType = ETargetType::RANDOM_CT; - + if (iBlockedFlags & NO_RANDOM) return ETargetError::RANDOM; @@ -1175,7 +1164,7 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, bTargetMultiple = true; iBlockedFlags |= NO_ALIVE; - } + } else if (!V_stricmp(pszTarget, "@alive") || !V_stricmp(pszTarget, "@!dead")) { nType = ETargetType::ALIVE; @@ -1212,7 +1201,7 @@ ETargetError CPlayerManager::GetPlayersFromString(CCSPlayerController* pPlayer, bTargetMultiple = true; iBlockedFlags |= NO_BOT; } - + // We have setup what we need and given custom errors if needed for group targetting. // Now we actually get the target(s). if (nType == ETargetType::SELF) @@ -1506,7 +1495,7 @@ bool CPlayerManager::CanTargetPlayers(CCSPlayerController* pPlayer, const char* return CanTargetPlayers(pPlayer, pszTarget, iNumClients, rgiClients, iBlockedFlags, nUselessVariable); } -ZEPlayer *CPlayerManager::GetPlayer(CPlayerSlot slot) +ZEPlayer* CPlayerManager::GetPlayer(CPlayerSlot slot) { if (slot.Get() < 0 || slot.Get() >= gpGlobals->maxClients) return nullptr; @@ -1520,7 +1509,7 @@ CPlayerSlot CPlayerManager::GetSlotFromUserId(uint16 userid) return CPlayerSlot(userid & 0xFF); } -ZEPlayer *CPlayerManager::GetPlayerFromUserId(uint16 userid) +ZEPlayer* CPlayerManager::GetPlayerFromUserId(uint16 userid) { uint8 index = userid & 0xFF; @@ -1533,10 +1522,8 @@ ZEPlayer *CPlayerManager::GetPlayerFromUserId(uint16 userid) ZEPlayer* CPlayerManager::GetPlayerFromSteamId(uint64 steamid) { for (ZEPlayer* player : m_vecPlayers) - { if (player && player->IsAuthenticated() && player->GetSteamId64() == steamid) return player; - } return nullptr; } @@ -1553,8 +1540,8 @@ void CPlayerManager::SetPlayerStopSound(int slot, bool set) if (!pPlayer) return; uint64 iSlotMask = (uint64)1 << slot; - int iStopPreferenceStatus = (m_nUsingStopSound & iSlotMask)?1:0; - int iSilencePreferenceStatus = (m_nUsingSilenceSound & iSlotMask)?2:0; + int iStopPreferenceStatus = (m_nUsingStopSound & iSlotMask) ? 1 : 0; + int iSilencePreferenceStatus = (m_nUsingSilenceSound & iSlotMask) ? 2 : 0; g_pUserPreferencesSystem->SetPreferenceInt(slot, SOUND_STATUS_PREF_KEY_NAME, iStopPreferenceStatus + iSilencePreferenceStatus); } @@ -1570,8 +1557,8 @@ void CPlayerManager::SetPlayerSilenceSound(int slot, bool set) if (!pPlayer) return; uint64 iSlotMask = (uint64)1 << slot; - int iStopPreferenceStatus = (m_nUsingStopSound & iSlotMask)?1:0; - int iSilencePreferenceStatus = (m_nUsingSilenceSound & iSlotMask)?2:0; + int iStopPreferenceStatus = (m_nUsingStopSound & iSlotMask) ? 1 : 0; + int iSilencePreferenceStatus = (m_nUsingSilenceSound & iSlotMask) ? 2 : 0; g_pUserPreferencesSystem->SetPreferenceInt(slot, SOUND_STATUS_PREF_KEY_NAME, iStopPreferenceStatus + iSilencePreferenceStatus); } @@ -1587,7 +1574,7 @@ void CPlayerManager::SetPlayerStopDecals(int slot, bool set) if (!pPlayer) return; uint64 iSlotMask = (uint64)1 << slot; - int iDecalPreferenceStatus = (m_nUsingStopDecals & iSlotMask)?1:0; + int iDecalPreferenceStatus = (m_nUsingStopDecals & iSlotMask) ? 1 : 0; g_pUserPreferencesSystem->SetPreferenceInt(slot, DECAL_PREF_KEY_NAME, iDecalPreferenceStatus); } @@ -1603,7 +1590,7 @@ void CPlayerManager::SetPlayerNoShake(int slot, bool set) if (!pPlayer) return; uint64 iSlotMask = (uint64)1 << slot; - int iNoShakePreferenceStatus = (m_nUsingNoShake & iSlotMask)?1:0; + int iNoShakePreferenceStatus = (m_nUsingNoShake & iSlotMask) ? 1 : 0; g_pUserPreferencesSystem->SetPreferenceInt(slot, NO_SHAKE_PREF_KEY_NAME, iNoShakePreferenceStatus); } diff --git a/src/playermanager.h b/src/playermanager.h index f3563c10..10553511 100644 --- a/src/playermanager.h +++ b/src/playermanager.h @@ -18,30 +18,30 @@ */ #pragma once +#include "bitvec.h" #include "common.h" -#include "utlvector.h" +#include "entity/cparticlesystem.h" +#include "entity/lights.h" +#include "gamesystem.h" +#include "steam/isteamuser.h" #include "steam/steam_api_common.h" #include "steam/steamclientpublic.h" -#include "steam/isteamuser.h" +#include "utlvector.h" #include -#include "bitvec.h" -#include "entity/lights.h" -#include "entity/cparticlesystem.h" -#include "gamesystem.h" -#define NO_TARGET_BLOCKS (0) -#define NO_RANDOM (1 << 1) -#define NO_MULTIPLE (1 << 2) -#define NO_SELF (1 << 3) -#define NO_BOT (1 << 4) -#define NO_HUMAN (1 << 5) -#define NO_UNAUTHENTICATED (1 << 6) -#define NO_DEAD (1 << 7) -#define NO_ALIVE (1 << 8) -#define NO_TERRORIST (1 << 9) -#define NO_COUNTER_TERRORIST (1 << 10) -#define NO_SPECTATOR (1 << 11) -#define NO_IMMUNITY (1 << 12) +#define NO_TARGET_BLOCKS (0) +#define NO_RANDOM (1 << 1) +#define NO_MULTIPLE (1 << 2) +#define NO_SELF (1 << 3) +#define NO_BOT (1 << 4) +#define NO_HUMAN (1 << 5) +#define NO_UNAUTHENTICATED (1 << 6) +#define NO_DEAD (1 << 7) +#define NO_ALIVE (1 << 8) +#define NO_TERRORIST (1 << 9) +#define NO_COUNTER_TERRORIST (1 << 10) +#define NO_SPECTATOR (1 << 11) +#define NO_IMMUNITY (1 << 12) #define DECAL_PREF_KEY_NAME "hide_decals" #define HIDE_DISTANCE_PREF_KEY_NAME "hide_distance" @@ -52,7 +52,8 @@ static uint32 iZEPlayerHandleSerial = 0u; // this should actually be 3 bytes large, but no way enough players join in servers lifespan for this to be an issue -enum class ETargetType { +enum class ETargetType +{ NONE, PLAYER, SELF, @@ -110,7 +111,7 @@ class ZEPlayerHandle ZEPlayerHandle(); ZEPlayerHandle(CPlayerSlot slot); // used for initialization inside ZEPlayer constructor ZEPlayerHandle(const ZEPlayerHandle& other); - ZEPlayerHandle(ZEPlayer *pZEPlayer); + ZEPlayerHandle(ZEPlayer* pZEPlayer); bool IsValid() const { return static_cast(Get()); } @@ -118,16 +119,16 @@ class ZEPlayerHandle uint32 GetPlayerSlot() const { return m_Parts.m_PlayerSlot; } uint32 GetSerial() const { return m_Parts.m_Serial; } - bool operator==(const ZEPlayerHandle &other) const { return other.m_Index == m_Index; } - bool operator!=(const ZEPlayerHandle &other) const { return other.m_Index != m_Index; } - bool operator==(ZEPlayer *pZEPlayer) const; - bool operator!=(ZEPlayer *pZEPlayer) const; + bool operator==(const ZEPlayerHandle& other) const { return other.m_Index == m_Index; } + bool operator!=(const ZEPlayerHandle& other) const { return other.m_Index != m_Index; } + bool operator==(ZEPlayer* pZEPlayer) const; + bool operator!=(ZEPlayer* pZEPlayer) const; + + void operator=(const ZEPlayerHandle& other) { m_Index = other.m_Index; } + void operator=(ZEPlayer* pZEPlayer) { Set(pZEPlayer); } + void Set(ZEPlayer* pZEPlayer); - void operator=(const ZEPlayerHandle &other) { m_Index = other.m_Index; } - void operator=(ZEPlayer *pZEPlayer) { Set(pZEPlayer); } - void Set(ZEPlayer *pZEPlayer); - - ZEPlayer *Get() const; + ZEPlayer* Get() const; private: union @@ -144,8 +145,9 @@ class ZEPlayerHandle class ZEPlayer { public: - ZEPlayer(CPlayerSlot slot, bool m_bFakeClient = false): m_slot(slot), m_bFakeClient(m_bFakeClient), m_Handle(slot) - { + ZEPlayer(CPlayerSlot slot, bool m_bFakeClient = false) : + m_slot(slot), m_bFakeClient(m_bFakeClient), m_Handle(slot) + { m_bAuthenticated = false; m_iAdminFlags = 0; m_iAdminImmunity = 0; @@ -186,7 +188,7 @@ class ZEPlayer ~ZEPlayer() { - CBarnLight *pFlashLight = m_hFlashLight.Get(); + CBarnLight* pFlashLight = m_hFlashLight.Get(); if (pFlashLight) pFlashLight->Remove(); @@ -201,7 +203,7 @@ class ZEPlayer const CSteamID* GetSteamId() { return m_SteamID; } bool IsAdminFlagSet(uint64 iFlag); bool IsFlooding(); - + void SetConnected() { m_bConnected = true; } void SetUnauthenticatedSteamId(const CSteamID* steamID) { m_UnauthenticatedSteamID = steamID; } void SetSteamId(const CSteamID* steamID) { m_SteamID = steamID; } @@ -225,17 +227,17 @@ class ZEPlayer void SetInGame(bool bInGame) { m_bInGame = bInGame; } void SetImmunity(int iMZImmunity) { m_iMZImmunity = iMZImmunity; } void SetNominateTime(float flCurtime) { m_flNominateTime = flCurtime; } - void SetFlashLight(CBarnLight *pLight) { m_hFlashLight.Set(pLight); } - void SetBeaconParticle(CParticleSystem *pParticle) { m_hBeaconParticle.Set(pParticle); } + void SetFlashLight(CBarnLight* pLight) { m_hFlashLight.Set(pLight); } + void SetBeaconParticle(CParticleSystem* pParticle) { m_hBeaconParticle.Set(pParticle); } void SetPlayerState(uint32 iPlayerState) { m_iPlayerState = iPlayerState; } void SetLeader(bool bIsLeader) { m_bIsLeader = bIsLeader; } void CreateMark(float fDuration, Vector vecOrigin); - void SetLeaderColor(Color colorLeader) {m_colorLeader = colorLeader;} + void SetLeaderColor(Color colorLeader) { m_colorLeader = colorLeader; } void SetTracerColor(Color colorTracer) { m_colorTracer = colorTracer; } void SetGlowColor(Color colorGlow) { m_colorGlow = colorGlow; } void SetBeaconColor(Color colorBeacon) { m_colorBeacon = colorBeacon; } void SetLeaderVoteTime(float flCurtime) { m_flLeaderVoteTime = flCurtime; } - void SetGlowModel(CBaseModelEntity *pModel) { m_hGlowModel.Set(pModel); } + void SetGlowModel(CBaseModelEntity* pModel) { m_hGlowModel.Set(pModel); } void SetSpeedMod(float flSpeedMod) { m_flSpeedMod = flSpeedMod; } void SetLastInputs(uint64 iLastInputs) { m_iLastInputs = iLastInputs; } void UpdateLastInputTime() { m_iLastInputTime = std::time(0); } @@ -264,8 +266,8 @@ class ZEPlayer bool IsInGame() { return m_bInGame; } int GetImmunity() { return m_iMZImmunity; } float GetNominateTime() { return m_flNominateTime; } - CBarnLight *GetFlashLight() { return m_hFlashLight.Get(); } - CParticleSystem *GetBeaconParticle() { return m_hBeaconParticle.Get(); } + CBarnLight* GetFlashLight() { return m_hFlashLight.Get(); } + CParticleSystem* GetBeaconParticle() { return m_hBeaconParticle.Get(); } ZEPlayerHandle GetHandle() { return m_Handle; } uint32 GetPlayerState() { return m_iPlayerState; } bool IsLeader() { return m_bIsLeader; } @@ -276,7 +278,7 @@ class ZEPlayer int GetLeaderVoteCount(); bool HasPlayerVotedLeader(ZEPlayer* pPlayer); float GetLeaderVoteTime() { return m_flLeaderVoteTime; } - CBaseModelEntity *GetGlowModel() { return m_hGlowModel.Get(); } + CBaseModelEntity* GetGlowModel() { return m_hGlowModel.Get(); } float GetSpeedMod() { return m_flSpeedMod; } float GetMaxSpeed() { return m_flMaxSpeed; } uint64 GetLastInputs() { return m_iLastInputs; } @@ -284,7 +286,7 @@ class ZEPlayer std::shared_ptr GetActiveZRClass() { return m_pActiveZRClass; } std::shared_ptr GetActiveZRModel() { return m_pActiveZRModel; } int GetButtonWatchMode(); - + void OnSpawn(); void OnAuthenticated(); void CheckAdmin(); @@ -374,21 +376,21 @@ class CPlayerManager void CheckHideDistances(); void SetupInfiniteAmmo(); CPlayerSlot GetSlotFromUserId(uint16 userid); - ZEPlayer *GetPlayerFromUserId(uint16 userid); - ZEPlayer *GetPlayerFromSteamId(uint64 steamid); - ETargetError GetPlayersFromString(CCSPlayerController* pPlayer, const char* pszTarget, int &iNumClients, int *clients, uint64 iBlockedFlags = NO_TARGET_BLOCKS); - ETargetError GetPlayersFromString(CCSPlayerController* pPlayer, const char* pszTarget, int &iNumClients, int *clients, uint64 iBlockedFlags, ETargetType& nType); + ZEPlayer* GetPlayerFromUserId(uint16 userid); + ZEPlayer* GetPlayerFromSteamId(uint64 steamid); + ETargetError GetPlayersFromString(CCSPlayerController* pPlayer, const char* pszTarget, int& iNumClients, int* clients, uint64 iBlockedFlags = NO_TARGET_BLOCKS); + ETargetError GetPlayersFromString(CCSPlayerController* pPlayer, const char* pszTarget, int& iNumClients, int* clients, uint64 iBlockedFlags, ETargetType& nType); static std::string GetErrorString(ETargetError eType, int iSlot = 0); bool CanTargetPlayers(CCSPlayerController* pPlayer, const char* pszTarget, int& iNumClients, int* clients, uint64 iBlockedFlags = NO_TARGET_BLOCKS); bool CanTargetPlayers(CCSPlayerController* pPlayer, const char* pszTarget, int& iNumClients, int* clients, uint64 iBlockedFlags, ETargetType& nType); - ZEPlayer *GetPlayer(CPlayerSlot slot); + ZEPlayer* GetPlayer(CPlayerSlot slot); uint64 GetStopSoundMask() { return m_nUsingStopSound; } uint64 GetSilenceSoundMask() { return m_nUsingSilenceSound; } uint64 GetStopDecalsMask() { return m_nUsingStopDecals; } uint64 GetNoShakeMask() { return m_nUsingNoShake; } - + void SetPlayerStopSound(int slot, bool set); void SetPlayerSilenceSound(int slot, bool set); void SetPlayerStopDecals(int slot, bool set); @@ -407,7 +409,7 @@ class CPlayerManager STEAM_GAMESERVER_CALLBACK_MANUAL(CPlayerManager, OnValidateAuthTicket, ValidateAuthTicketResponse_t, m_CallbackValidateAuthTicketResponse); private: - ZEPlayer *m_vecPlayers[MAXPLAYERS]; + ZEPlayer* m_vecPlayers[MAXPLAYERS]; uint64 m_nUsingStopSound; uint64 m_nUsingSilenceSound; @@ -415,6 +417,6 @@ class CPlayerManager uint64 m_nUsingNoShake; }; -extern CPlayerManager *g_playerManager; +extern CPlayerManager* g_playerManager; void PrecacheBeaconParticle(IEntityResourceManifest* pResourceManifest); \ No newline at end of file diff --git a/src/recipientfilters.h b/src/recipientfilters.h index b3ba9b85..722d52bd 100644 --- a/src/recipientfilters.h +++ b/src/recipientfilters.h @@ -41,7 +41,6 @@ class CSingleRecipientFilter : public IRecipientFilter bool m_bInitMessage; }; - class CRecipientFilter : public IRecipientFilter { public: @@ -51,17 +50,15 @@ class CRecipientFilter : public IRecipientFilter m_bInitMessage = false; } - CRecipientFilter(IRecipientFilter *source, int iExcept = -1) + CRecipientFilter(IRecipientFilter* source, int iExcept = -1) { m_nBufType = source->GetNetworkBufType(); m_bInitMessage = source->IsInitMessage(); m_Recipients.RemoveAll(); for (int i = 0; i < source->GetRecipientCount(); i++) - { if (source->GetRecipientIndex(i).Get() != iExcept) m_Recipients.AddToTail(source->GetRecipientIndex(i)); - } } ~CRecipientFilter() override {} diff --git a/src/serversideclient.h b/src/serversideclient.h index 4664b3cc..2b369fd7 100644 --- a/src/serversideclient.h +++ b/src/serversideclient.h @@ -2,7 +2,7 @@ #define SERVERSIDECLIENT_H #if COMPILER_MSVC -#pragma once + #pragma once #endif #include "clientframe.h" @@ -12,9 +12,9 @@ #include // #include // @Wend4r: use instead. #include +#include #include #include -#include #include #include @@ -24,8 +24,10 @@ class INetMessage; class CNetworkGameServerBase; class CNetworkGameServer; -struct HltvReplayStats_t { - enum FailEnum_t { +struct HltvReplayStats_t +{ + enum FailEnum_t + { FAILURE_ALREADY_IN_REPLAY, FAILURE_TOO_FREQUENT, FAILURE_NO_FRAME, @@ -46,14 +48,15 @@ struct HltvReplayStats_t { uint nFailedReplays[NUM_FAILURES]; }; // sizeof 56 - -struct Spike_t { +struct Spike_t +{ public: CUtlString m_szDesc; int m_nBits; }; // sizeof 16 -class CNetworkStatTrace { +class CNetworkStatTrace +{ public: CUtlVector m_Records; int m_nMinWarningBytes; @@ -70,234 +73,279 @@ class CServerSideClientBase virtual ~CServerSideClientBase() = 0; public: - CPlayerSlot GetPlayerSlot() const { return m_nClientSlot; } - CPlayerUserId GetUserID() const { return m_UserID; } - CEntityIndex GetEntityIndex() const { return m_nEntityIndex; } - CSteamID GetClientSteamID() const { return m_SteamID; } - const char *GetClientName() const { return m_Name; } - INetChannel *GetNetChannel() const { return m_NetChannel; } - const netadr_t *GetRemoteAddress() const { return &m_nAddr.GetAddress(); } - CNetworkGameServerBase *GetServer() const { return m_Server; } - - virtual void Connect( int socket, const char* pszName, int nUserID, INetChannel* pNetChannel, bool bFakePlayer, bool bSplitClient, int iClientPlatform ) = 0; - virtual void Inactivate() = 0; - virtual void Reactivate( CPlayerSlot nSlot ) = 0; - virtual void SetServer( CNetworkGameServer *pNetServer ) = 0; - virtual void Reconnect() = 0; - virtual void Disconnect( ENetworkDisconnectionReason reason ) = 0; - virtual bool CheckConnect() = 0; + CPlayerSlot GetPlayerSlot() const { return m_nClientSlot; } + CPlayerUserId GetUserID() const { return m_UserID; } + CEntityIndex GetEntityIndex() const { return m_nEntityIndex; } + CSteamID GetClientSteamID() const { return m_SteamID; } + const char* GetClientName() const { return m_Name; } + INetChannel* GetNetChannel() const { return m_NetChannel; } + const netadr_t* GetRemoteAddress() const { return &m_nAddr.GetAddress(); } + CNetworkGameServerBase* GetServer() const { return m_Server; } + + virtual void Connect(int socket, const char* pszName, int nUserID, INetChannel* pNetChannel, bool bFakePlayer, bool bSplitClient, int iClientPlatform) = 0; + virtual void Inactivate() = 0; + virtual void Reactivate(CPlayerSlot nSlot) = 0; + virtual void SetServer(CNetworkGameServer* pNetServer) = 0; + virtual void Reconnect() = 0; + virtual void Disconnect(ENetworkDisconnectionReason reason) = 0; + virtual bool CheckConnect() = 0; private: - virtual void unk_10() = 0; + virtual void unk_10() = 0; public: - virtual void SetRate( int nRate ) = 0; - virtual void SetUpdateRate( float fUpdateRate ) = 0; - virtual int GetRate() = 0; + virtual void SetRate(int nRate) = 0; + virtual void SetUpdateRate(float fUpdateRate) = 0; + virtual int GetRate() = 0; - virtual void Clear() = 0; + virtual void Clear() = 0; - virtual void ExecuteStringCommand( const CNETMsg_StringCmd& msg ) = 0; - virtual void SendNetMessage( const CNetMessage *pData, NetChannelBufType_t bufType ) = 0; + virtual void ExecuteStringCommand(const CNETMsg_StringCmd& msg) = 0; + virtual void SendNetMessage(const CNetMessage* pData, NetChannelBufType_t bufType) = 0; #ifdef LINUX private: - virtual void unk_17() = 0; + virtual void unk_17() = 0; #endif public: - virtual void ClientPrintf( const char*, ...) = 0; - - bool IsConnected() const { return m_nSignonState >= SIGNONSTATE_CONNECTED; } - bool IsSpawned() const { return m_nSignonState >= SIGNONSTATE_NEW; } - bool IsActive() const { return m_nSignonState == SIGNONSTATE_FULL; } - virtual bool IsFakeClient() const { return m_bFakePlayer; } - virtual bool IsHLTV() = 0; + virtual void ClientPrintf(const char*, ...) = 0; + + bool IsConnected() const + { + return m_nSignonState >= SIGNONSTATE_CONNECTED; + } + bool IsSpawned() const + { + return m_nSignonState >= SIGNONSTATE_NEW; + } + bool IsActive() const + { + return m_nSignonState == SIGNONSTATE_FULL; + } + virtual bool IsFakeClient() const + { + return m_bFakePlayer; + } + virtual bool IsHLTV() = 0; // Is an actual human player or splitscreen player (not a bot and not a HLTV slot) - virtual bool IsHumanPlayer() const { return false; } - virtual bool IsHearingClient( CPlayerSlot nSlot ) const { return false; } - virtual bool IsLowViolenceClient() const { return m_bLowViolence; } - - virtual bool IsSplitScreenUser() const { return m_bSplitScreenUser; } - int GetClientPlatform() const { return m_ClientPlatform; } // CrossPlayPlatform_t + virtual bool IsHumanPlayer() const + { + return false; + } + virtual bool IsHearingClient(CPlayerSlot nSlot) const + { + return false; + } + virtual bool IsLowViolenceClient() const + { + return m_bLowViolence; + } + + virtual bool IsSplitScreenUser() const + { + return m_bSplitScreenUser; + } + int GetClientPlatform() const + { + return m_ClientPlatform; + } // CrossPlayPlatform_t public: // Message Handlers - virtual bool ProcessTick( const CNETMsg_Tick_t& msg ) = 0; - virtual bool ProcessStringCmd( const CNETMsg_StringCmd_t& msg ) = 0; + virtual bool ProcessTick(const CNETMsg_Tick_t& msg) = 0; + virtual bool ProcessStringCmd(const CNETMsg_StringCmd_t& msg) = 0; private: - virtual bool unk_27() = 0; - virtual bool unk_28() = 0; + virtual bool unk_27() = 0; + virtual bool unk_28() = 0; public: - virtual bool ProcessSpawnGroup_LoadCompleted( const CNETMsg_SpawnGroup_LoadCompleted_t &msg ) = 0; - virtual bool ProcessClientInfo( const CCLCMsg_ClientInfo_t &msg ) = 0; - virtual bool ProcessBaselineAck( const CCLCMsg_BaselineAck_t &msg ) = 0; - virtual bool ProcessLoadingProgress( const CCLCMsg_LoadingProgress_t &msg ) = 0; - virtual bool ProcessSplitPlayerConnect( const CCLCMsg_SplitPlayerConnect_t &msg ) = 0; - virtual bool ProcessSplitPlayerDisconnect( const CCLCMsg_SplitPlayerDisconnect_t &msg ) = 0; - virtual bool ProcessCmdKeyValues( const CCLCMsg_CmdKeyValues_t &msg ) = 0; + virtual bool ProcessSpawnGroup_LoadCompleted(const CNETMsg_SpawnGroup_LoadCompleted_t& msg) = 0; + virtual bool ProcessClientInfo(const CCLCMsg_ClientInfo_t& msg) = 0; + virtual bool ProcessBaselineAck(const CCLCMsg_BaselineAck_t& msg) = 0; + virtual bool ProcessLoadingProgress(const CCLCMsg_LoadingProgress_t& msg) = 0; + virtual bool ProcessSplitPlayerConnect(const CCLCMsg_SplitPlayerConnect_t& msg) = 0; + virtual bool ProcessSplitPlayerDisconnect(const CCLCMsg_SplitPlayerDisconnect_t& msg) = 0; + virtual bool ProcessCmdKeyValues(const CCLCMsg_CmdKeyValues_t& msg) = 0; private: - virtual bool unk_36() = 0; - virtual bool unk_37() = 0; + virtual bool unk_36() = 0; + virtual bool unk_37() = 0; public: - virtual bool ProcessMove( const CCLCMsg_Move_t &msg ) = 0; - virtual bool ProcessVoiceData( const CCLCMsg_VoiceData_t &msg ) = 0; - virtual bool ProcessFileCRCCheck( const CCLCMsg_FileCRCCheck_t &msg ) = 0; - virtual bool ProcessRespondCvarValue( const CCLCMsg_RespondCvarValue_t &msg ) = 0; + virtual bool ProcessMove(const CCLCMsg_Move_t& msg) = 0; + virtual bool ProcessVoiceData(const CCLCMsg_VoiceData_t& msg) = 0; + virtual bool ProcessFileCRCCheck(const CCLCMsg_FileCRCCheck_t& msg) = 0; + virtual bool ProcessRespondCvarValue(const CCLCMsg_RespondCvarValue_t& msg) = 0; - virtual bool ProcessPacketStart( const NetMessagePacketStart_t &msg ) = 0; - virtual bool ProcessPacketEnd( const NetMessagePacketEnd_t &msg ) = 0; - virtual bool ProcessConnectionClosed( const NetMessageConnectionClosed_t &msg ) = 0; - virtual bool ProcessConnectionCrashed( const NetMessageConnectionCrashed_t &msg ) = 0; + virtual bool ProcessPacketStart(const NetMessagePacketStart_t& msg) = 0; + virtual bool ProcessPacketEnd(const NetMessagePacketEnd_t& msg) = 0; + virtual bool ProcessConnectionClosed(const NetMessageConnectionClosed_t& msg) = 0; + virtual bool ProcessConnectionCrashed(const NetMessageConnectionCrashed_t& msg) = 0; public: - virtual bool ProcessChangeSplitscreenUser( const NetMessageSplitscreenUserChanged_t &msg ) = 0; + virtual bool ProcessChangeSplitscreenUser(const NetMessageSplitscreenUserChanged_t& msg) = 0; private: - virtual bool unk_47() = 0; - virtual bool unk_48() = 0; - virtual bool unk_49() = 0; + virtual bool unk_47() = 0; + virtual bool unk_48() = 0; + virtual bool unk_49() = 0; public: - virtual void ConnectionStart( INetChannel *pNetChannel ) = 0; + virtual void ConnectionStart(INetChannel* pNetChannel) = 0; private: // SpawnGroup something. - virtual void unk_51() = 0; - virtual void unk_52() = 0; + virtual void unk_51() = 0; + virtual void unk_52() = 0; public: - virtual void ExecuteDelayedCall( void * ) = 0; + virtual void ExecuteDelayedCall(void*) = 0; - virtual bool UpdateAcknowledgedFramecount( int tick ) = 0; - void ForceFullUpdate() { UpdateAcknowledgedFramecount(-1); } + virtual bool UpdateAcknowledgedFramecount(int tick) = 0; + void ForceFullUpdate() + { + UpdateAcknowledgedFramecount(-1); + } - virtual bool ShouldSendMessages() = 0; - virtual void UpdateSendState() = 0; + virtual bool ShouldSendMessages() = 0; + virtual void UpdateSendState() = 0; - virtual const CMsgPlayerInfo &GetPlayerInfo() const { return m_playerInfo; } + virtual const CMsgPlayerInfo& GetPlayerInfo() const + { + return m_playerInfo; + } - virtual void UpdateUserSettings() = 0; - virtual void ResetUserSettings() = 0; + virtual void UpdateUserSettings() = 0; + virtual void ResetUserSettings() = 0; private: - virtual void unk_60() = 0; + virtual void unk_60() = 0; public: - virtual void SendSignonData() = 0; - virtual void SpawnPlayer() = 0; - virtual void ActivatePlayer() = 0; + virtual void SendSignonData() = 0; + virtual void SpawnPlayer() = 0; + virtual void ActivatePlayer() = 0; - virtual void SetName( const char *name ) = 0; - virtual void SetUserCVar( const char *cvar, const char *value ) = 0; + virtual void SetName(const char* name) = 0; + virtual void SetUserCVar(const char* cvar, const char* value) = 0; - int GetSignonState() const { return m_nSignonState; } + int GetSignonState() const + { + return m_nSignonState; + } - virtual void FreeBaselines() = 0; + virtual void FreeBaselines() = 0; - bool IsFullyAuthenticated( void ) { return m_bFullyAuthenticated; } - void SetFullyAuthenticated( void ) { m_bFullyAuthenticated = true; } + bool IsFullyAuthenticated(void) + { + return m_bFullyAuthenticated; + } + void SetFullyAuthenticated(void) + { + m_bFullyAuthenticated = true; + } - virtual CServerSideClientBase *GetSplitScreenOwner() { return m_pAttachedTo; } + virtual CServerSideClientBase* GetSplitScreenOwner() + { + return m_pAttachedTo; + } - virtual int GetNumPlayers() = 0; + virtual int GetNumPlayers() = 0; - virtual void ShouldReceiveStringTableUserData() = 0; + virtual void ShouldReceiveStringTableUserData() = 0; private: - virtual void unk_70( CPlayerSlot nSlot ) = 0; - virtual void unk_71() = 0; - virtual void unk_72() = 0; + virtual void unk_70(CPlayerSlot nSlot) = 0; + virtual void unk_71() = 0; + virtual void unk_72() = 0; public: - virtual int GetHltvLastSendTick() = 0; + virtual int GetHltvLastSendTick() = 0; private: - virtual void unk_74() = 0; - virtual void unk_75() = 0; - virtual void unk_76() = 0; + virtual void unk_74() = 0; + virtual void unk_75() = 0; + virtual void unk_76() = 0; public: - virtual void Await() = 0; + virtual void Await() = 0; - virtual void MarkToKick() = 0; - virtual void UnmarkToKick() = 0; + virtual void MarkToKick() = 0; + virtual void UnmarkToKick() = 0; - virtual bool ProcessSignonStateMsg( int state ) = 0; - virtual void PerformDisconnection( ENetworkDisconnectionReason reason ) = 0; + virtual bool ProcessSignonStateMsg(int state) = 0; + virtual void PerformDisconnection(ENetworkDisconnectionReason reason) = 0; public: - [[maybe_unused]] void* m_pVT1; // INetworkMessageProcessingPreFilter - CUtlString m_unk16; // 16 + [[maybe_unused]] void* m_pVT1; // INetworkMessageProcessingPreFilter + CUtlString m_unk16; // 16 [[maybe_unused]] char pad24[0x16]; // 24 #ifdef __linux__ [[maybe_unused]] char pad46[0x10]; // 46 #endif - void (*RebroadcastSource)(int msgID); // 64 - CUtlString m_UserIDString; // 72 - CUtlString m_Name; // 80 - CPlayerSlot m_nClientSlot; // 88 - CEntityIndex m_nEntityIndex; // 92 - CNetworkGameServerBase* m_Server; // 96 - INetChannel* m_NetChannel; // 104 - uint8 m_nUnkVariable; // 112 - bool m_bMarkedToKick; // 113 - int32 m_nSignonState; // 116 - bool m_bSplitScreenUser; // 120 - bool m_bSplitAllowFastDisconnect; // 121 - int m_nSplitScreenPlayerSlot; // 124 + void (*RebroadcastSource)(int msgID); // 64 + CUtlString m_UserIDString; // 72 + CUtlString m_Name; // 80 + CPlayerSlot m_nClientSlot; // 88 + CEntityIndex m_nEntityIndex; // 92 + CNetworkGameServerBase* m_Server; // 96 + INetChannel* m_NetChannel; // 104 + uint8 m_nUnkVariable; // 112 + bool m_bMarkedToKick; // 113 + int32 m_nSignonState; // 116 + bool m_bSplitScreenUser; // 120 + bool m_bSplitAllowFastDisconnect; // 121 + int m_nSplitScreenPlayerSlot; // 124 CServerSideClientBase* m_SplitScreenUsers[4]; // 128 - CServerSideClientBase* m_pAttachedTo; // 160 - bool m_bSplitPlayerDisconnecting; // 168 - int m_UnkVariable172; // 172 - bool m_bFakePlayer; // 176 - bool m_bSendingSnapshot; // 177 + CServerSideClientBase* m_pAttachedTo; // 160 + bool m_bSplitPlayerDisconnecting; // 168 + int m_UnkVariable172; // 172 + bool m_bFakePlayer; // 176 + bool m_bSendingSnapshot; // 177 [[maybe_unused]] char pad6[0x5]; CPlayerUserId m_UserID; // 184 bool m_bReceivedPacket; // 186 - CSteamID m_SteamID; // 187 - CSteamID m_UnkSteamID; // 195 + CSteamID m_SteamID; // 187 + CSteamID m_UnkSteamID; // 195 CSteamID m_UnkSteamID2; // 203 from auth ticket - CSteamID m_nFriendsID; // 211 - ns_address m_nAddr; // 220 - ns_address m_nAddr2; // 252 - KeyValues* m_ConVars; // 288 + CSteamID m_nFriendsID; // 211 + ns_address m_nAddr; // 220 + ns_address m_nAddr2; // 252 + KeyValues* m_ConVars; // 288 bool m_bConVarsChanged; // 296 - bool m_bConVarsInited; // 297 - bool m_bIsHLTV; // 298 - bool m_bIsReplay; // 299 + bool m_bConVarsInited; // 297 + bool m_bIsHLTV; // 298 + bool m_bIsReplay; // 299 [[maybe_unused]] char pad29[0xA]; - uint32 m_nSendtableCRC; // 312 - int m_ClientPlatform; // 316 - int m_nSignonTick; // 320 - int m_nDeltaTick; // 324 - int m_UnkVariable3; // 328 - int m_nStringTableAckTick; // 332 - int m_UnkVariable4; // 336 - CFrameSnapshot* m_pLastSnapshot; // 344 + uint32 m_nSendtableCRC; // 312 + int m_ClientPlatform; // 316 + int m_nSignonTick; // 320 + int m_nDeltaTick; // 324 + int m_UnkVariable3; // 328 + int m_nStringTableAckTick; // 332 + int m_UnkVariable4; // 336 + CFrameSnapshot* m_pLastSnapshot; // 344 CUtlVector m_vecLoadedSpawnGroups; // 352 - CMsgPlayerInfo m_playerInfo; // 376 - CFrameSnapshot* m_pBaseline; // 432 - int m_nBaselineUpdateTick; // 440 - CBitVec m_BaselinesSent; // 444 - int m_nBaselineUsed; // 2492 - int m_nLoadingProgress; // 2496 - int m_nForceWaitForTick; // 2500 - bool m_bLowViolence; // 2504 - bool m_bSomethingWithAddressType; // 2505 - bool m_bFullyAuthenticated; // 2506 - bool m_bUnkBool2507; // 2507 - float m_fNextMessageTime; // 2508 - float m_fSnapshotInterval; // 2512 - float m_fAuthenticatedTime; // 2516 - [[maybe_unused]] char pad168[0x124]; // 2520 - [[maybe_unused]] char pad1658[0x24]; // 2816 something in CServerSideClientBase::ExecuteStringCommand - CNetworkStatTrace m_Trace; // 2848 - int m_spamCommandsCount; // 2888 if the value is greater than 16, the player will be kicked with reason 39 - double m_lastExecutedCommand; // 2896 if command executed more than once per second, ++m_spamCommandCount + CMsgPlayerInfo m_playerInfo; // 376 + CFrameSnapshot* m_pBaseline; // 432 + int m_nBaselineUpdateTick; // 440 + CBitVec m_BaselinesSent; // 444 + int m_nBaselineUsed; // 2492 + int m_nLoadingProgress; // 2496 + int m_nForceWaitForTick; // 2500 + bool m_bLowViolence; // 2504 + bool m_bSomethingWithAddressType; // 2505 + bool m_bFullyAuthenticated; // 2506 + bool m_bUnkBool2507; // 2507 + float m_fNextMessageTime; // 2508 + float m_fSnapshotInterval; // 2512 + float m_fAuthenticatedTime; // 2516 + [[maybe_unused]] char pad168[0x124]; // 2520 + [[maybe_unused]] char pad1658[0x24]; // 2816 something in CServerSideClientBase::ExecuteStringCommand + CNetworkStatTrace m_Trace; // 2848 + int m_spamCommandsCount; // 2888 if the value is greater than 16, the player will be kicked with reason 39 + double m_lastExecutedCommand; // 2896 if command executed more than once per second, ++m_spamCommandCount }; class CServerSideClient : public CServerSideClientBase @@ -306,26 +354,26 @@ class CServerSideClient : public CServerSideClientBase virtual ~CServerSideClient() = 0; public: - CPlayerBitVec m_VoiceStreams; // 2904 - CPlayerBitVec m_VoiceProximity; // 2912 - CCheckTransmitInfo m_PackInfo; // 2920 - CClientFrameManager m_FrameManager; // 3520 - CClientFrame* m_pCurrentFrame; // 3808 - float m_flLastClientCommandQuotaStart; // 3816 - float m_flTimeClientBecameFullyConnected; // 3820 - bool m_bVoiceLoopback; // 3824 - int m_nHltvReplayDelay; // 3828 - CHLTVServer* m_pHltvReplayServer; // 3832 - int m_nHltvReplayStopAt; // 3840 - int m_nHltvReplayStartAt; // 3844 - int m_nHltvReplaySlowdownBeginAt; // 3848 - int m_nHltvReplaySlowdownEndAt; // 3852 - float m_flHltvReplaySlowdownRate; // 3856 - int m_nHltvLastSendTick; // 3860 - float m_flHltvLastReplayRequestTime; // 3864 + CPlayerBitVec m_VoiceStreams; // 2904 + CPlayerBitVec m_VoiceProximity; // 2912 + CCheckTransmitInfo m_PackInfo; // 2920 + CClientFrameManager m_FrameManager; // 3520 + CClientFrame* m_pCurrentFrame; // 3808 + float m_flLastClientCommandQuotaStart; // 3816 + float m_flTimeClientBecameFullyConnected; // 3820 + bool m_bVoiceLoopback; // 3824 + int m_nHltvReplayDelay; // 3828 + CHLTVServer* m_pHltvReplayServer; // 3832 + int m_nHltvReplayStopAt; // 3840 + int m_nHltvReplayStartAt; // 3844 + int m_nHltvReplaySlowdownBeginAt; // 3848 + int m_nHltvReplaySlowdownEndAt; // 3852 + float m_flHltvReplaySlowdownRate; // 3856 + int m_nHltvLastSendTick; // 3860 + float m_flHltvLastReplayRequestTime; // 3864 CUtlVector m_HltvQueuedMessages; // 3872 - HltvReplayStats_t m_HltvReplayStats; // 3896 - void* m_pLastJob; // 3952 + HltvReplayStats_t m_HltvReplayStats; // 3896 + void* m_pLastJob; // 3952 }; // not full class reversed @@ -335,20 +383,20 @@ class CHLTVClient : public CServerSideClientBase virtual ~CHLTVClient() = 0; public: - CNetworkGameServerBase* m_pHLTV; // 2904 - CUtlString m_szPassword; // 2912 - CUtlString m_szChatGroup; // 2920 - double m_fLastSendTime; // 2928 - double m_flLastChatTime; // 2936 - int m_nLastSendTick; // 2944 + CNetworkGameServerBase* m_pHLTV; // 2904 + CUtlString m_szPassword; // 2912 + CUtlString m_szChatGroup; // 2920 + double m_fLastSendTime; // 2928 + double m_flLastChatTime; // 2936 + int m_nLastSendTick; // 2944 [[maybe_unused]] char pad2948[0x4]; // 2948 - int m_nFullFrameTime; // 2952 + int m_nFullFrameTime; // 2952 [[maybe_unused]] char pad2956[0x4]; // 2956 [[maybe_unused]] char pad2960[0x4]; // 2960 - bool m_bNoChat; // 2964 - bool m_bUnkBool; // 2965 - bool m_bUnkBool2; // 2966 - bool m_bUnkBool3; // 2967 + bool m_bNoChat; // 2964 + bool m_bUnkBool; // 2965 + bool m_bUnkBool2; // 2966 + bool m_bUnkBool3; // 2967 }; // sizeof 3008 #endif // SERVERSIDECLIENT_H diff --git a/src/user_preferences.cpp b/src/user_preferences.cpp index c5e6d5d4..4cf9fc59 100644 --- a/src/user_preferences.cpp +++ b/src/user_preferences.cpp @@ -17,9 +17,9 @@ * this program. If not, see . */ +#include "user_preferences.h" #include "commands.h" #include "common.h" -#include "user_preferences.h" #include "httpmanager.h" #include "playermanager.h" #include "strtools.h" @@ -29,22 +29,23 @@ using json = nlohmann::json; - CUserPreferencesStorage* g_pUserPreferencesStorage = nullptr; CUserPreferencesSystem* g_pUserPreferencesSystem = nullptr; // CONVAR_TODO CON_COMMAND_F(cs2f_user_prefs_api, "API for user preferences, currently a REST API.", FCVAR_LINKED_CONCOMMAND | FCVAR_SPONLY | FCVAR_PROTECTED) { - if (!g_pUserPreferencesSystem || !g_pUserPreferencesStorage) { + if (!g_pUserPreferencesSystem || !g_pUserPreferencesStorage) + { Message("The user preferences subsystem is not enabled."); return; } - CUserPreferencesREST* restStorageSystem = (CUserPreferencesREST*) g_pUserPreferencesStorage; + CUserPreferencesREST* restStorageSystem = (CUserPreferencesREST*)g_pUserPreferencesStorage; if (args.ArgC() < 2) Message("Usage: %s . Current value: %s\n", args[0], restStorageSystem->GetPreferencesAPIUrl()); - else { + else + { Message("Setting preferences URL to %s\n", args[1]); restStorageSystem->SetPreferencesAPIUrl(args[1]); } @@ -62,7 +63,8 @@ CON_COMMAND_CHAT_FLAGS(setpref, "- Set a preference key for the player.", ADMFLA { if (args.ArgC() < 3) Message("Usage: %s \n", args[0]); - else { + else + { ZEPlayer* pPlayer = player->GetZEPlayer(); if (!pPlayer) return; @@ -74,7 +76,8 @@ CON_COMMAND_CHAT_FLAGS(getpref, "- Get a preference key for the player.", ADMFLA { if (args.ArgC() < 2) Message("Usage: %s \n", args[0]); - else { + else + { ZEPlayer* pPlayer = player->GetZEPlayer(); if (!pPlayer) return; @@ -91,26 +94,26 @@ CON_COMMAND_CHAT_FLAGS(pushprefs, "- Push preferences.", ADMFLAG_ROOT) g_pUserPreferencesSystem->PushPreferences(pPlayer->GetPlayerSlot().Get()); } -void CUserPreferencesSystem::ClearPreferences(int iSlot) +void CUserPreferencesSystem::ClearPreferences(int iSlot) { m_mUserSteamIds[iSlot] = 0; m_mPreferencesLoaded[iSlot] = false; m_mPreferencesMaps[iSlot].Purge(); } -bool CUserPreferencesSystem::PutPreferences(int iSlot, uint64 iSteamId, CUtlMap &preferenceData) +bool CUserPreferencesSystem::PutPreferences(int iSlot, uint64 iSteamId, CUtlMap& preferenceData) { ZEPlayer* player = g_playerManager->GetPlayer(CPlayerSlot(iSlot)); if (!player || !player->IsAuthenticated()) return false; - if (iSteamId != player->GetSteamId64()) { + if (iSteamId != player->GetSteamId64()) return false; - } #ifdef _DEBUG Message("Putting data for %llu\n", iSteamId); #endif m_mUserSteamIds[iSlot] = iSteamId; m_mPreferencesLoaded[iSlot] = true; - FOR_EACH_MAP(preferenceData, i) { + FOR_EACH_MAP(preferenceData, i) + { uint32 iKeyHash = preferenceData.Key(i); int iValueIdx = preferenceData.Find(iKeyHash); if (iValueIdx == preferenceData.InvalidIndex()) @@ -118,16 +121,16 @@ bool CUserPreferencesSystem::PutPreferences(int iSlot, uint64 iSteamId, CUtlMap< m_mPreferencesMaps[iSlot].InsertOrReplace(iKeyHash, preferenceData[iValueIdx]); } return true; -} +} void CUserPreferencesSystem::OnPutPreferences(int iSlot) { int iHideDistance = GetPreferenceInt(iSlot, HIDE_DISTANCE_PREF_KEY_NAME, 0); int iSoundStatus = GetPreferenceInt(iSlot, SOUND_STATUS_PREF_KEY_NAME, 1); - bool bStopSound = (bool) (iSoundStatus & 1); - bool bSilenceSound = (bool) (iSoundStatus & 2); - bool bHideDecals = (bool) GetPreferenceInt(iSlot, DECAL_PREF_KEY_NAME, 1); - bool bNoShake = (bool) GetPreferenceInt(iSlot, NO_SHAKE_PREF_KEY_NAME, 0); + bool bStopSound = (bool)(iSoundStatus & 1); + bool bSilenceSound = (bool)(iSoundStatus & 2); + bool bHideDecals = (bool)GetPreferenceInt(iSlot, DECAL_PREF_KEY_NAME, 1); + bool bNoShake = (bool)GetPreferenceInt(iSlot, NO_SHAKE_PREF_KEY_NAME, 0); int iButtonWatchMode = GetPreferenceInt(iSlot, BUTTON_WATCH_PREF_KEY_NAME, 0); // Set the values that we just loaded --- the player is guaranteed available @@ -142,7 +145,7 @@ void CUserPreferencesSystem::OnPutPreferences(int iSlot) player->CycleButtonWatch(); } -void CUserPreferencesSystem::PullPreferences(int iSlot) +void CUserPreferencesSystem::PullPreferences(int iSlot) { if (!g_pUserPreferencesStorage) return; @@ -154,11 +157,9 @@ void CUserPreferencesSystem::PullPreferences(int iSlot) g_pUserPreferencesStorage->LoadPreferences( iSteamId, [iSlot](uint64 iSteamId, CUtlMap& preferenceData) { - if (g_pUserPreferencesSystem->PutPreferences(iSlot, iSteamId, preferenceData)) { + if (g_pUserPreferencesSystem->PutPreferences(iSlot, iSteamId, preferenceData)) g_pUserPreferencesSystem->OnPutPreferences(iSlot); - } - } - ); + }); } const char* CUserPreferencesSystem::GetPreference(int iSlot, const char* sKey, const char* sDefaultValue) @@ -169,7 +170,7 @@ const char* CUserPreferencesSystem::GetPreference(int iSlot, const char* sKey, c Message("User at slot %d is reading from preference '%s' with hash %d at index %d.\n", iSlot, sKey, iKeyHash, iKeyIdx); #endif if (iKeyIdx == m_mPreferencesMaps[iSlot].InvalidIndex()) return sDefaultValue; - return (const char*) m_mPreferencesMaps[iSlot][iKeyIdx].GetValue(); + return (const char*)m_mPreferencesMaps[iSlot][iKeyIdx].GetValue(); } int CUserPreferencesSystem::GetPreferenceInt(int iSlot, const char* sKey, int iDefaultValue) @@ -198,14 +199,17 @@ void CUserPreferencesSystem::SetPreference(int iSlot, const char* sKey, const ch // Create or populate the content of the preference value int iValueIdx = m_mPreferencesMaps[iSlot].Find(iKeyHash); CPreferenceValue* prefValue; - if (iValueIdx == m_mPreferencesMaps[iSlot].InvalidIndex()) { + if (iValueIdx == m_mPreferencesMaps[iSlot].InvalidIndex()) + { prefValue = new CPreferenceValue(sKey, sValue); - } else { + } + else + { prefValue = &m_mPreferencesMaps[iSlot][iValueIdx]; prefValue->SetKeyValue(sKey, sValue); } - // Override the key-value pair and insert + // Override the key-value pair and insert m_mPreferencesMaps[iSlot].InsertOrReplace(iKeyHash, *prefValue); } @@ -213,14 +217,14 @@ void CUserPreferencesSystem::SetPreferenceInt(int iSlot, const char* sKey, int i { char sPreferenceString[MAX_PREFERENCE_LENGTH]; V_snprintf(sPreferenceString, sizeof(sPreferenceString), "%d", iValue); - SetPreference(iSlot, sKey, (const char*) sPreferenceString); + SetPreference(iSlot, sKey, (const char*)sPreferenceString); } void CUserPreferencesSystem::SetPreferenceFloat(int iSlot, const char* sKey, float fValue) { char sPreferenceString[MAX_PREFERENCE_LENGTH]; V_snprintf(sPreferenceString, sizeof(sPreferenceString), "%f", fValue); - SetPreference(iSlot, sKey, (const char*) sPreferenceString); + SetPreference(iSlot, sKey, (const char*)sPreferenceString); } bool CUserPreferencesSystem::CheckPreferencesLoaded(int iSlot) @@ -242,23 +246,22 @@ void CUserPreferencesSystem::PushPreferences(int iSlot) iSteamId, m_mPreferencesMaps[iSlot], [iSlot](uint64 iSteamId, CUtlMap& preferenceData) { - if (g_pUserPreferencesSystem->PutPreferences(iSlot, iSteamId, preferenceData)) { + if (g_pUserPreferencesSystem->PutPreferences(iSlot, iSteamId, preferenceData)) g_pUserPreferencesSystem->OnPutPreferences(iSlot); - } - } - ); + }); } -void CUserPreferencesREST::JsonToPreferencesMap(json data, CUtlMap &preferencesMap) +void CUserPreferencesREST::JsonToPreferencesMap(json data, CUtlMap& preferencesMap) { preferencesMap.SetLessFunc(DefLessFunc(uint32)); - for (auto it = data.begin(); it != data.end(); ++it) { + for (auto it = data.begin(); it != data.end(); ++it) + { std::string key = it.key(); std::string value = it.value(); // Prepare the key and value pair, and also the key name via hashes #ifdef _DEBUG - Message("- Storing KV-pair: %s, %s\n", key.c_str(), value.c_str()); + Message("- Storing KV-pair: %s, %s\n", key.c_str(), value.c_str()); #endif CPreferenceValue* prefValue = new CPreferenceValue(key.c_str(), value.c_str()); @@ -280,16 +283,16 @@ void CUserPreferencesREST::LoadPreferences(uint64 iSteamId, StorageCallback cb) V_snprintf(sUserPreferencesUrl, sizeof(sUserPreferencesUrl), "%s%llu", m_pszUserPreferencesUrl, iSteamId); g_HTTPManager.GET(sUserPreferencesUrl, [iSteamId, cb](HTTPRequestHandle request, json data) { #ifdef _DEBUG - Message("Executing storage callback during load for %llu\n", iSteamId); + Message("Executing storage callback during load for %llu\n", iSteamId); #endif CUtlMap preferencesMap; - ((CUserPreferencesREST*) g_pUserPreferencesStorage)->JsonToPreferencesMap(data, preferencesMap); + ((CUserPreferencesREST*)g_pUserPreferencesStorage)->JsonToPreferencesMap(data, preferencesMap); cb(iSteamId, preferencesMap); preferencesMap.Purge(); }); } -void CUserPreferencesREST::StorePreferences(uint64 iSteamId, CUtlMap &preferences, StorageCallback cb) +void CUserPreferencesREST::StorePreferences(uint64 iSteamId, CUtlMap& preferences, StorageCallback cb) { #ifdef _DEBUG Message("Storing data for %llu\n", iSteamId); @@ -298,7 +301,8 @@ void CUserPreferencesREST::StorePreferences(uint64 iSteamId, CUtlMap preferencesMap; - ((CUserPreferencesREST*) g_pUserPreferencesStorage)->JsonToPreferencesMap(data, preferencesMap); + ((CUserPreferencesREST*)g_pUserPreferencesStorage)->JsonToPreferencesMap(data, preferencesMap); cb(iSteamId, preferencesMap); preferencesMap.Purge(); }); diff --git a/src/user_preferences.h b/src/user_preferences.h index 1e11bf84..3611309e 100644 --- a/src/user_preferences.h +++ b/src/user_preferences.h @@ -18,6 +18,7 @@ */ #pragma once +#include "common.h" #include "utlmap.h" #include "utlstring.h" #undef snprintf @@ -30,7 +31,6 @@ using json = nlohmann::json; #define MAX_PREFERENCE_LENGTH 128 - class CPreferenceValue { public: @@ -41,7 +41,8 @@ class CPreferenceValue } char* GetKey() { return m_sKey; }; char* GetValue() { return m_sValue; }; - void SetKeyValue(const char* sKey, const char* sValue) { + void SetKeyValue(const char* sKey, const char* sValue) + { V_strcpy(m_sKey, sKey); V_strcpy(m_sValue, sValue); } @@ -55,17 +56,18 @@ class CUserPreferencesStorage { public: virtual void LoadPreferences(uint64 iSteamId, StorageCallback cb) = 0; - virtual void StorePreferences(uint64 iSteamId, CUtlMap &preferences, StorageCallback cb) = 0; + virtual void StorePreferences(uint64 iSteamId, CUtlMap& preferences, StorageCallback cb) = 0; }; class CUserPreferencesREST : public CUserPreferencesStorage { public: void LoadPreferences(uint64 iSteamId, StorageCallback cb); - void StorePreferences(uint64 iSteamId, CUtlMap &preferences, StorageCallback cb); + void StorePreferences(uint64 iSteamId, CUtlMap& preferences, StorageCallback cb); void SetPreferencesAPIUrl(const char* sUserPreferencesUrl) { V_strcpy(m_pszUserPreferencesUrl, sUserPreferencesUrl); }; - const char* GetPreferencesAPIUrl() { return (const char*) m_pszUserPreferencesUrl; }; - void JsonToPreferencesMap(json data, CUtlMap &preferences); + const char* GetPreferencesAPIUrl() { return (const char*)m_pszUserPreferencesUrl; }; + void JsonToPreferencesMap(json data, CUtlMap& preferences); + private: char m_pszUserPreferencesUrl[256] = ""; }; @@ -75,7 +77,8 @@ class CUserPreferencesSystem public: CUserPreferencesSystem() { - for (int i = 0; i < MAXPLAYERS; i++) { + for (int i = 0; i < MAXPLAYERS; i++) + { m_mPreferencesMaps[i].SetLessFunc(DefLessFunc(uint32)); m_mPreferencesLoaded[i] = false; } @@ -90,9 +93,10 @@ class CUserPreferencesSystem void SetPreferenceInt(int iSlot, const char* sKey, int iValue); void SetPreferenceFloat(int iSlot, const char* sKey, float fValue); bool CheckPreferencesLoaded(int iSlot); - bool PutPreferences(int iSlot, uint64 iSteamId, CUtlMap &preferenceData); + bool PutPreferences(int iSlot, uint64 iSteamId, CUtlMap& preferenceData); void OnPutPreferences(int iSlot); void PushPreferences(int iSlot); + private: CUtlMap m_mPreferencesMaps[MAXPLAYERS]; uint64 m_mUserSteamIds[MAXPLAYERS]; diff --git a/src/utils/entity.cpp b/src/utils/entity.cpp index 5e0243a4..0bc52384 100644 --- a/src/utils/entity.cpp +++ b/src/utils/entity.cpp @@ -23,17 +23,17 @@ #include "../common.h" #include "../gameconfig.h" #include "../utils/virtual.h" +#include "entity/cgamerules.h" #include "entitysystem.h" #include "platform.h" -#include "entity/cgamerules.h" #include "tier0/memdbgon.h" -extern CGameEntitySystem *g_pEntitySystem; -extern CGameConfig *g_GameConfig; -extern CCSGameRules *g_pGameRules; +extern CGameEntitySystem* g_pEntitySystem; +extern CGameConfig* g_GameConfig; +extern CCSGameRules* g_pGameRules; -CBaseEntity *UTIL_FindPickerEntity(CBasePlayerController *pPlayer) +CBaseEntity* UTIL_FindPickerEntity(CBasePlayerController* pPlayer) { static int offset = g_GameConfig->GetOffset("CGameRules_FindPickerEntity"); @@ -43,22 +43,22 @@ CBaseEntity *UTIL_FindPickerEntity(CBasePlayerController *pPlayer) return nullptr; } - return CALL_VIRTUAL(CBaseEntity *, offset, g_pGameRules, pPlayer); + return CALL_VIRTUAL(CBaseEntity*, offset, g_pGameRules, pPlayer); } -CBaseEntity *UTIL_FindEntityByClassname(CEntityInstance *pStartEntity, const char *szName) +CBaseEntity* UTIL_FindEntityByClassname(CEntityInstance* pStartEntity, const char* szName) { return addresses::CGameEntitySystem_FindEntityByClassName(g_pEntitySystem, pStartEntity, szName); } -CBaseEntity *UTIL_FindEntityByName(CEntityInstance *pStartEntity, const char *szName, - CEntityInstance *pSearchingEntity, CEntityInstance *pActivator, CEntityInstance *pCaller, IEntityFindFilter *pFilter) +CBaseEntity* UTIL_FindEntityByName(CEntityInstance* pStartEntity, const char* szName, + CEntityInstance* pSearchingEntity, CEntityInstance* pActivator, CEntityInstance* pCaller, IEntityFindFilter* pFilter) { return addresses::CGameEntitySystem_FindEntityByName(g_pEntitySystem, pStartEntity, szName, pSearchingEntity, pActivator, pCaller, pFilter); } -void UTIL_AddEntityIOEvent(CEntityInstance *pTarget, const char *pszInput, - CEntityInstance *pActivator, CEntityInstance *pCaller, variant_t value, float flDelay) +void UTIL_AddEntityIOEvent(CEntityInstance* pTarget, const char* pszInput, + CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t value, float flDelay) { addresses::CEntitySystem_AddEntityIOEvent(g_pEntitySystem, pTarget, pszInput, pActivator, pCaller, &value, flDelay, 0); } diff --git a/src/utils/entity.h b/src/utils/entity.h index e946231e..a09e1c39 100644 --- a/src/utils/entity.h +++ b/src/utils/entity.h @@ -19,22 +19,22 @@ #pragma once -#include "platform.h" +#include "../addresses.h" #include "datamap.h" +#include "platform.h" #include "string_t.h" #include "variant.h" -#include "../addresses.h" class CEntityInstance; class CBaseEntity; class CBasePlayerController; class IEntityFindFilter; -CBaseEntity *UTIL_FindPickerEntity(CBasePlayerController *pPlayer); -CBaseEntity *UTIL_FindEntityByClassname(CEntityInstance *pStart, const char *name); -CBaseEntity *UTIL_FindEntityByName(CEntityInstance *pStartEntity, const char *szName, - CEntityInstance *pSearchingEntity = nullptr, CEntityInstance *pActivator = nullptr, - CEntityInstance *pCaller = nullptr, IEntityFindFilter *pFilter = nullptr); +CBaseEntity* UTIL_FindPickerEntity(CBasePlayerController* pPlayer); +CBaseEntity* UTIL_FindEntityByClassname(CEntityInstance* pStart, const char* name); +CBaseEntity* UTIL_FindEntityByName(CEntityInstance* pStartEntity, const char* szName, + CEntityInstance* pSearchingEntity = nullptr, CEntityInstance* pActivator = nullptr, + CEntityInstance* pCaller = nullptr, IEntityFindFilter* pFilter = nullptr); template T* CreateEntityByName(const char* className) @@ -44,6 +44,6 @@ T* CreateEntityByName(const char* className) // Add an entity IO event to the event queue, just like a map would // The queue is processed after all entities are simulated every frame -void UTIL_AddEntityIOEvent(CEntityInstance *pTarget, const char *pszInput, - CEntityInstance *pActivator = nullptr, CEntityInstance *pCaller = nullptr, +void UTIL_AddEntityIOEvent(CEntityInstance* pTarget, const char* pszInput, + CEntityInstance* pActivator = nullptr, CEntityInstance* pCaller = nullptr, variant_t value = variant_t(""), float flDelay = 0.0f); diff --git a/src/utils/module.h b/src/utils/module.h index ccd09468..e39394a7 100644 --- a/src/utils/module.h +++ b/src/utils/module.h @@ -21,15 +21,14 @@ #include "../common.h" #include "dbg.h" #include "interface.h" -#include "strtools.h" #include "plat.h" +#include "strtools.h" #include #include - #ifdef _WIN32 -#include + #include #endif enum SigError @@ -67,6 +66,7 @@ class SignatureIterator return nullptr; } + private: byte* m_pBase; size_t m_iSize; @@ -78,7 +78,7 @@ class SignatureIterator class CModule { public: - CModule(const char *path, const char *module) : + CModule(const char* path, const char* module) : m_pszModule(module), m_pszPath(path) { char szModule[MAX_PATH]; @@ -94,7 +94,7 @@ class CModule MODULEINFO m_hModuleInfo; GetModuleInformation(GetCurrentProcess(), m_hModule, &m_hModuleInfo, sizeof(m_hModuleInfo)); - m_base = (void *)m_hModuleInfo.lpBaseOfDll; + m_base = (void*)m_hModuleInfo.lpBaseOfDll; m_size = m_hModuleInfo.SizeOfImage; InitializeSections(); #else @@ -102,16 +102,16 @@ class CModule Error("Failed to get module info for %s, error %d\n", szModule, e); #endif - for(auto& section : m_sections) + for (auto& section : m_sections) Message("Section %s base: 0x%p | size: %d\n", section.m_szName.c_str(), section.m_pBase, section.m_iSize); Message("Initialized module %s base: 0x%p | size: %d\n", m_pszModule, m_base, m_size); } - void *FindSignature(const byte *pData, size_t iSigLength, int &error) + void* FindSignature(const byte* pData, size_t iSigLength, int& error) { - unsigned char *pMemory; - void *return_addr = nullptr; + unsigned char* pMemory; + void* return_addr = nullptr; error = 0; pMemory = (byte*)m_base; @@ -130,7 +130,7 @@ class CModule return return_addr; } - return_addr = (void *)(pMemory + i); + return_addr = (void*)(pMemory + i); break; } } @@ -142,14 +142,14 @@ class CModule return return_addr; } - void *FindInterface(const char *name) + void* FindInterface(const char* name) { CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(m_hModule, "CreateInterface"); if (!fn) Error("Could not find CreateInterface in %s\n", m_pszModule); - void *pInterface = fn(name, nullptr); + void* pInterface = fn(name, nullptr); if (!pInterface) Error("Could not find %s in %s\n", name, m_pszModule); @@ -162,10 +162,8 @@ class CModule Section* GetSection(const std::string_view name) { for (auto& section : m_sections) - { if (section.m_szName == name) return §ion; - } return nullptr; } @@ -173,8 +171,9 @@ class CModule void InitializeSections(); #endif void* FindVirtualTable(const std::string& name); + public: - const char *m_pszModule; + const char* m_pszModule; const char* m_pszPath; HINSTANCE m_hModule; void* m_base; diff --git a/src/utils/plat.h b/src/utils/plat.h index 9858909c..479d5ee9 100644 --- a/src/utils/plat.h +++ b/src/utils/plat.h @@ -18,10 +18,10 @@ */ #pragma once -#include -#include -#include #include "metamod_oslink.h" +#include +#include +#include struct Section { @@ -31,12 +31,12 @@ struct Section }; #if defined(_WIN32) -#define FASTCALL __fastcall -#define THISCALL __thiscall + #define FASTCALL __fastcall + #define THISCALL __thiscall #else -#define FASTCALL -#define THISCALL -#define strtok_s strtok_r + #define FASTCALL + #define THISCALL + #define strtok_s strtok_r #endif struct Module @@ -53,11 +53,11 @@ int GetModuleInformation(HINSTANCE module, void** base, size_t* length, std::vec #endif #ifdef _WIN32 -#define MODULE_PREFIX "" -#define MODULE_EXT ".dll" + #define MODULE_PREFIX "" + #define MODULE_EXT ".dll" #else -#define MODULE_PREFIX "lib" -#define MODULE_EXT ".so" + #define MODULE_PREFIX "lib" + #define MODULE_EXT ".so" #endif -void Plat_WriteMemory(void* pPatchAddress, uint8_t *pPatch, int iPatchSize); \ No newline at end of file +void Plat_WriteMemory(void* pPatchAddress, uint8_t* pPatch, int iPatchSize); \ No newline at end of file diff --git a/src/utils/plat_unix.cpp b/src/utils/plat_unix.cpp index d30d6bb7..6181c0ae 100644 --- a/src/utils/plat_unix.cpp +++ b/src/utils/plat_unix.cpp @@ -2,7 +2,7 @@ * ============================================================================= * CS2Fixes * Copyright (C) 2023-2024 Source2ZE - * + * * DynLibUtils * Copyright (C) 2023 komashchenko (Phoenix) * ============================================================================= @@ -21,38 +21,37 @@ */ #ifdef __linux__ -#include "module.h" -#include "plat.h" -#include -#include -#include -#include -#include "sys/mman.h" -#include -#include -#include -#include "dbg.h" -#include -#include -#include - -#include "tier0/memdbgon.h" - -#define PAGE_SIZE 4096 -#define PAGE_ALIGN_UP(x) ((x + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)) + #include "dbg.h" + #include "module.h" + #include "plat.h" + #include "sys/mman.h" + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #include "tier0/memdbgon.h" + + #define PAGE_SIZE 4096 + #define PAGE_ALIGN_UP(x) ((x + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)) struct ModuleInfo { const char* path; // in - uint8_t* base; // out - uint size; // out + uint8_t* base; // out + uint size; // out }; // https://github.com/alliedmodders/sourcemod/blob/master/core/logic/MemoryUtils.cpp#L502-L587 // https://github.com/komashchenko/DynLibUtils/blob/5eb95475170becfcc64fd5d32d14ec2b76dcb6d4/module_linux.cpp#L95 int GetModuleInformation(HINSTANCE hModule, void** base, size_t* length, std::vector
& m_sections) { - link_map* lmap; if (dlinfo(hModule, RTLD_DI_LINKMAP, &lmap) != 0) { @@ -76,7 +75,7 @@ int GetModuleInformation(HINSTANCE hModule, void** base, size_t* length, std::ve ElfW(Ehdr)* ehdr = static_cast(map); ElfW(Shdr)* shdrs = reinterpret_cast(reinterpret_cast(ehdr) + ehdr->e_shoff); const char* strTab = reinterpret_cast(reinterpret_cast(ehdr) + shdrs[ehdr->e_shstrndx].sh_offset); - + for (auto i = 0; i < ehdr->e_phnum; ++i) { ElfW(Phdr)* phdr = reinterpret_cast(reinterpret_cast(ehdr) + ehdr->e_phoff + i * ehdr->e_phentsize); @@ -118,23 +117,23 @@ static int parse_prot(const char* s) { switch (*s) { - case '-': - break; - case 'r': - prot |= PROT_READ; - break; - case 'w': - prot |= PROT_WRITE; - break; - case 'x': - prot |= PROT_EXEC; - break; - case 's': - break; - case 'p': - break; - default: - break; + case '-': + break; + case 'r': + prot |= PROT_READ; + break; + case 'w': + prot |= PROT_WRITE; + break; + case 'x': + prot |= PROT_EXEC; + break; + case 's': + break; + case 'p': + break; + default: + break; } } @@ -178,7 +177,7 @@ static int get_prot(void* pAddr, size_t nSize) uintptr_t nStart = (uintptr_t)strtoul(start, nullptr, 16); uintptr_t nEnd = (uintptr_t)strtoul(end, nullptr, 16); - if (nStart < nAddr && nEnd >(nAddr + nSize)) + if (nStart < nAddr && nEnd > (nAddr + nSize)) { fclose(f); return parse_prot(prot); @@ -239,7 +238,7 @@ void* CModule::FindVirtualTable(const std::string& name) void* typeInfo = (void*)((uintptr_t)typeName - 0x8); - for (const auto& sectionName : { std::string_view(".data.rel.ro"), std::string_view(".data.rel.ro.local") }) + for (const auto& sectionName : {std::string_view(".data.rel.ro"), std::string_view(".data.rel.ro.local")}) { auto section = GetSection(sectionName); if (!section) @@ -248,14 +247,11 @@ void* CModule::FindVirtualTable(const std::string& name) SignatureIterator sigIt3(section->m_pBase, section->m_iSize, (const byte*)&typeInfo, sizeof(void*)); while (void* vtable = sigIt3.FindNext(false)) - { - if(*(int64_t*)((uintptr_t)vtable - 0x8) == 0) + if (*(int64_t*)((uintptr_t)vtable - 0x8) == 0) return (void*)((uintptr_t)vtable + 0x8); - } } Warning("Failed to find vtable for %s\n", name.c_str()); return nullptr; } #endif - diff --git a/src/utils/plat_win.cpp b/src/utils/plat_win.cpp index 559bb597..e3ed7a7b 100644 --- a/src/utils/plat_win.cpp +++ b/src/utils/plat_win.cpp @@ -30,7 +30,6 @@ void Plat_WriteMemory(void* pPatchAddress, uint8_t* pPatch, int iPatchSize) WriteProcessMemory(GetCurrentProcess(), pPatchAddress, (void*)pPatch, iPatchSize, nullptr); } - void CModule::InitializeSections() { IMAGE_DOS_HEADER* pDosHeader = reinterpret_cast(m_hModule); @@ -83,7 +82,7 @@ void* CModule::FindVirtualTable(const std::string& name) { auto completeObjectLocatorHeader = (uintptr_t)completeObjectLocator - 0xC; // check RTTI Complete Object Locator header, always 0x1 - if(*(int32_t*)(completeObjectLocatorHeader) != 1) + if (*(int32_t*)(completeObjectLocatorHeader) != 1) continue; // check RTTI Complete Object Locator vtable offset diff --git a/src/utils/virtual.h b/src/utils/virtual.h index b035c06c..df525d4f 100644 --- a/src/utils/virtual.h +++ b/src/utils/virtual.h @@ -25,8 +25,8 @@ namespace vmt { - template - inline T GetVMethod(uint32 uIndex, void *pClass) + template + inline T GetVMethod(uint32 uIndex, void* pClass) { if (!pClass) { @@ -34,7 +34,7 @@ namespace vmt return T(); } - void **pVTable = *static_cast(pClass); + void** pVTable = *static_cast(pClass); if (!pVTable) { Warning("Tried getting virtual function from a null vtable.\n"); @@ -45,10 +45,10 @@ namespace vmt } template - inline T CallVirtual(uint32 uIndex, void *pClass, Args... args) + inline T CallVirtual(uint32 uIndex, void* pClass, Args... args) { #ifdef _WIN32 - auto pFunc = GetVMethod(uIndex, pClass); + auto pFunc = GetVMethod(uIndex, pClass); #else auto pFunc = GetVMethod(uIndex, pClass); #endif @@ -60,4 +60,4 @@ namespace vmt return pFunc(pClass, args...); } -} \ No newline at end of file +} // namespace vmt \ No newline at end of file diff --git a/src/votemanager.cpp b/src/votemanager.cpp index aa50afc3..51b649a5 100644 --- a/src/votemanager.cpp +++ b/src/votemanager.cpp @@ -19,11 +19,11 @@ #include "votemanager.h" #include "commands.h" -#include "playermanager.h" #include "ctimer.h" -#include "icvar.h" #include "entity/cgamerules.h" +#include "icvar.h" #include "panoramavote.h" +#include "playermanager.h" #include "tier0/memdbgon.h" @@ -75,21 +75,17 @@ void VoteManager_Init() g_iExtends = 0; - new CTimer(g_flExtendVoteDelay, false, true, []() - { - if (g_ExtendState < EExtendState::POST_EXTEND_NO_EXTENDS_LEFT) - g_ExtendState = EExtendState::EXTEND_ALLOWED; - return -1.0f; - } - ); + new CTimer(g_flExtendVoteDelay, false, true, []() { + if (g_ExtendState < EExtendState::POST_EXTEND_NO_EXTENDS_LEFT) + g_ExtendState = EExtendState::EXTEND_ALLOWED; + return -1.0f; + }); - new CTimer(g_flRtvDelay, false, true, []() - { - if (g_RTVState != ERTVState::BLOCKED_BY_ADMIN) - g_RTVState = ERTVState::RTV_ALLOWED; - return -1.0f; - } - ); + new CTimer(g_flRtvDelay, false, true, []() { + if (g_RTVState != ERTVState::BLOCKED_BY_ADMIN) + g_RTVState = ERTVState::RTV_ALLOWED; + return -1.0f; + }); new CTimer(flExtendVoteTickrate, false, true, TimerCheckTimeleft); } @@ -103,7 +99,7 @@ float TimerCheckTimeleft() if (!g_bVoteManagerEnable) return flExtendVoteTickrate; - + // Auto votes disabled, dont stop the timer in case this changes mid-map if (g_ExtendVoteMode != EExtendVoteMode::EXTENDVOTE_AUTO) return flExtendVoteTickrate; @@ -130,25 +126,22 @@ float TimerCheckTimeleft() if (flTimeleft > (g_flExtendVoteStartTime * 60.0)) return flExtendVoteTickrate; - bVoteStarting = true; ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Extend vote starting in 10 seconds!"); - new CTimer(7.0f, false, true, []() + new CTimer(7.0f, false, true, []() { + if (iVoteStartTicks == 0) { - if (iVoteStartTicks == 0) - { - iVoteStartTicks = 3; - StartExtendVote(VOTE_CALLER_SERVER); - bVoteStarting = false; - return -1.0f; - } - - ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Extend vote starting in %d....", iVoteStartTicks); - iVoteStartTicks--; - return 1.0f; + iVoteStartTicks = 3; + StartExtendVote(VOTE_CALLER_SERVER); + bVoteStarting = false; + return -1.0f; } - ); + + ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Extend vote starting in %d....", iVoteStartTicks); + iVoteStartTicks--; + return 1.0f; + }); return flExtendVoteTickrate; } @@ -232,18 +225,18 @@ CON_COMMAND_CHAT(rtv, "- Vote to end the current map sooner") switch (g_RTVState) { - case ERTVState::MAP_START: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV is not open yet."); - return; - case ERTVState::POST_RTV_SUCCESSFULL: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV vote already succeeded."); - return; - case ERTVState::POST_LAST_ROUND_END: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV is closed during next map selection."); - return; - case ERTVState::BLOCKED_BY_ADMIN: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV has been blocked by an Admin."); - return; + case ERTVState::MAP_START: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV is not open yet."); + return; + case ERTVState::POST_RTV_SUCCESSFULL: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV vote already succeeded."); + return; + case ERTVState::POST_LAST_ROUND_END: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV is closed during next map selection."); + return; + case ERTVState::BLOCKED_BY_ADMIN: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "RTV has been blocked by an Admin."); + return; } int iCurrentRTVCount = GetCurrentRTVCount(); @@ -273,12 +266,11 @@ CON_COMMAND_CHAT(rtv, "- Vote to end the current map sooner") { ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "RTV succeeded! Ending the map now..."); - new CTimer(3.0f, false, true, []() - { - g_pGameRules->TerminateRound(5.0f, CSRoundEndReason::Draw); + new CTimer(3.0f, false, true, []() { + g_pGameRules->TerminateRound(5.0f, CSRoundEndReason::Draw); - return -1.0f; - }); + return -1.0f; + }); } else { @@ -345,39 +337,39 @@ CON_COMMAND_CHAT(ve, "- Vote to extend current map") switch (g_ExtendVoteMode) { - case EExtendVoteMode::EXTENDVOTE_OFF: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend votes are disabled."); - return; - case EExtendVoteMode::EXTENDVOTE_ADMINONLY: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend votes are disabled."); - return; - case EExtendVoteMode::EXTENDVOTE_AUTO: - { - if (g_ExtendState == EExtendState::EXTEND_ALLOWED) + case EExtendVoteMode::EXTENDVOTE_OFF: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend votes are disabled."); + return; + case EExtendVoteMode::EXTENDVOTE_ADMINONLY: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend votes are disabled."); + return; + case EExtendVoteMode::EXTENDVOTE_AUTO: { - ConVar* cvar = g_pCVar->GetConVar(g_pCVar->FindConVar("mp_timelimit")); + if (g_ExtendState == EExtendState::EXTEND_ALLOWED) + { + ConVar* cvar = g_pCVar->GetConVar(g_pCVar->FindConVar("mp_timelimit")); - // CONVAR_TODO - // HACK: values is actually the cvar value itself, hence this ugly cast. - float flTimelimit = *(float*)&cvar->values; - if (flTimelimit <= 0.0) - return; + // CONVAR_TODO + // HACK: values is actually the cvar value itself, hence this ugly cast. + float flTimelimit = *(float*)&cvar->values; + if (flTimelimit <= 0.0) + return; - float flTimeleft = (g_pGameRules->m_flGameStartTime + flTimelimit * 60.0f) - gpGlobals->curtime; - int iTimeTillVote = (int)(flTimeleft - (g_flExtendVoteStartTime * 60.0)); + float flTimeleft = (g_pGameRules->m_flGameStartTime + flTimelimit * 60.0f) - gpGlobals->curtime; + int iTimeTillVote = (int)(flTimeleft - (g_flExtendVoteStartTime * 60.0)); - div_t div = std::div(iTimeTillVote, 60); - int iMinutesLeft = div.quot; - int iSecondsLeft = div.rem; + div_t div = std::div(iTimeTillVote, 60); + int iMinutesLeft = div.quot; + int iSecondsLeft = div.rem; - if (iMinutesLeft > 0) - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "An extend vote will start in %im %is", iMinutesLeft, iSecondsLeft); - else - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "An extend vote will start in %i seconds", iSecondsLeft); - return; + if (iMinutesLeft > 0) + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "An extend vote will start in %im %is", iMinutesLeft, iSecondsLeft); + else + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "An extend vote will start in %i seconds", iSecondsLeft); + return; + } } } - } int iPlayer = player->GetPlayerSlot(); @@ -392,30 +384,30 @@ CON_COMMAND_CHAT(ve, "- Vote to extend current map") switch (g_ExtendState) { - case EExtendState::MAP_START: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is not open yet."); - return; - case EExtendState::IN_PROGRESS: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "An extend vote is in progress right now!"); - return; - case EExtendState::POST_EXTEND_COOLDOWN: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is not open yet."); - return; - case EExtendState::POST_EXTEND_NO_EXTENDS_LEFT: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "There are no extends left for the current map."); - return; - case EExtendState::POST_EXTEND_FAILED: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "A previous extend vote already failed."); - return; - case EExtendState::POST_LAST_ROUND_END: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is closed during next map selection."); - return; - case EExtendState::POST_RTV: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is closed because RTV vote has passed."); - return; - case EExtendState::NO_EXTENDS: - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is not allowed for current map."); - return; + case EExtendState::MAP_START: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is not open yet."); + return; + case EExtendState::IN_PROGRESS: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "An extend vote is in progress right now!"); + return; + case EExtendState::POST_EXTEND_COOLDOWN: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is not open yet."); + return; + case EExtendState::POST_EXTEND_NO_EXTENDS_LEFT: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "There are no extends left for the current map."); + return; + case EExtendState::POST_EXTEND_FAILED: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "A previous extend vote already failed."); + return; + case EExtendState::POST_LAST_ROUND_END: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is closed during next map selection."); + return; + case EExtendState::POST_RTV: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is closed because RTV vote has passed."); + return; + case EExtendState::NO_EXTENDS: + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "Extend vote is not allowed for current map."); + return; } int iCurrentExtendCount = GetCurrentExtendCount(); @@ -556,16 +548,11 @@ CON_COMMAND_CHAT(extendsleft, "- Display amount of extends left for the current return; if (g_iMaxExtends - g_iExtends <= 0) - { ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "There are no extends left, the map was already extended %i/%i times.", g_iExtends, g_iMaxExtends); - } + else if (g_ExtendState == EExtendState::POST_EXTEND_FAILED) + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "The map had %i/%i extends left, but the last extend vote failed.", g_iMaxExtends - g_iExtends, g_iMaxExtends); else - { - if (g_ExtendState == EExtendState::POST_EXTEND_FAILED) - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "The map had %i/%i extends left, but the last extend vote failed.", g_iMaxExtends - g_iExtends, g_iMaxExtends); - else - ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "The map has %i/%i extends left.", g_iMaxExtends - g_iExtends, g_iMaxExtends); - } + ClientPrint(player, HUD_PRINTTALK, CHAT_PREFIX "The map has %i/%i extends left.", g_iMaxExtends - g_iExtends, g_iMaxExtends); } CON_COMMAND_CHAT(timeleft, "- Display time left to end of current map.") @@ -609,7 +596,7 @@ CON_COMMAND_CHAT(timeleft, "- Display time left to end of current map.") void ExtendMap(int iMinutes) { // mimic behaviour of !extend - // CONVAR_TODO + // CONVAR_TODO ConVar* cvar = g_pCVar->GetConVar(g_pCVar->FindConVar("mp_timelimit")); // CONVAR_TODO @@ -639,40 +626,38 @@ void VoteExtendHandler(YesNoVoteAction action, int param1, int param2) { switch (action) { - case YesNoVoteAction::VoteAction_Start: - { - ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Extend vote started!"); - break; - } - case YesNoVoteAction::VoteAction_Vote: // param1 = client slot, param2 = choice (VOTE_OPTION1=yes, VOTE_OPTION2=no) - { - CCSPlayerController* pController = CCSPlayerController::FromSlot(param1); - if (!pController || !pController->IsController() || !pController->IsConnected()) + case YesNoVoteAction::VoteAction_Start: + { + ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Extend vote started!"); break; - ClientPrint(pController, HUD_PRINTTALK, CHAT_PREFIX "Thanks for voting! Type !revote to change your vote!"); - break; - } - case YesNoVoteAction::VoteAction_End: - { - if ((YesNoVoteEndReason)param1 == YesNoVoteEndReason::VoteEnd_Cancelled) + } + case YesNoVoteAction::VoteAction_Vote: // param1 = client slot, param2 = choice (VOTE_OPTION1=yes, VOTE_OPTION2=no) { - // Admin cancelled so stop further votes - // It will reenable if an admin manually calls a vote - if (g_ExtendVoteMode == EExtendVoteMode::EXTENDVOTE_AUTO) + CCSPlayerController* pController = CCSPlayerController::FromSlot(param1); + if (!pController || !pController->IsController() || !pController->IsConnected()) + break; + ClientPrint(pController, HUD_PRINTTALK, CHAT_PREFIX "Thanks for voting! Type !revote to change your vote!"); + break; + } + case YesNoVoteAction::VoteAction_End: + { + if ((YesNoVoteEndReason)param1 == YesNoVoteEndReason::VoteEnd_Cancelled) { - g_ExtendState = EExtendState::POST_EXTEND_FAILED; + // Admin cancelled so stop further votes + // It will reenable if an admin manually calls a vote + if (g_ExtendVoteMode == EExtendVoteMode::EXTENDVOTE_AUTO) + g_ExtendState = EExtendState::POST_EXTEND_FAILED; } - } - break; - } + break; + } } } // return true to show vote pass, false to show fail bool VoteExtendEndCallback(YesNoVoteInfo info) { - //ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Vote end: numvotes:%d yes:%d no:%d numclients:%d", info.num_votes, info.yes_votes, info.no_votes, info.num_clients); + // ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Vote end: numvotes:%d yes:%d no:%d numclients:%d", info.num_votes, info.yes_votes, info.no_votes, info.num_clients); float yes_percent = 0.0f; @@ -694,24 +679,22 @@ bool VoteExtendEndCallback(YesNoVoteInfo info) // there's an extend left after a successfull extend vote if (g_ExtendVoteMode == EExtendVoteMode::EXTENDVOTE_AUTO) { - //small delay to allow cvar change to go through - new CTimer(0.1, false, true, []() - { - g_ExtendState = EExtendState::EXTEND_ALLOWED; - return -1.0f; - }); + // small delay to allow cvar change to go through + new CTimer(0.1, false, true, []() { + g_ExtendState = EExtendState::EXTEND_ALLOWED; + return -1.0f; + }); } else { g_ExtendState = EExtendState::POST_EXTEND_COOLDOWN; // Allow another extend vote after added time lapses - new CTimer(g_iExtendTimeToAdd * 60.0f, false, true, []() - { - if (g_ExtendState == EExtendState::POST_EXTEND_COOLDOWN) - g_ExtendState = EExtendState::EXTEND_ALLOWED; - return -1.0f; - }); + new CTimer(g_iExtendTimeToAdd * 60.0f, false, true, []() { + if (g_ExtendState == EExtendState::POST_EXTEND_COOLDOWN) + g_ExtendState = EExtendState::EXTEND_ALLOWED; + return -1.0f; + }); } } @@ -747,19 +730,17 @@ void StartExtendVote(int iCaller) g_ExtendState = EExtendState::IN_PROGRESS; g_pPanoramaVoteHandler->SendYesNoVoteToAll(g_flExtendVoteDuration, iCaller, "#SFUI_vote_passed_nextlevel_extend", - sDetailStr, &VoteExtendEndCallback, &VoteExtendHandler); + sDetailStr, &VoteExtendEndCallback, &VoteExtendHandler); - new CTimer(g_flExtendVoteDuration - 3.0f, false, true, []() + new CTimer(g_flExtendVoteDuration - 3.0f, false, true, []() { + if (iVoteEndTicks == 0 || g_ExtendState != EExtendState::IN_PROGRESS) { - if (iVoteEndTicks == 0 || g_ExtendState != EExtendState::IN_PROGRESS) - { - iVoteEndTicks = 3; - return -1.0f; - } - - ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Extend vote ending in %d....", iVoteEndTicks); - iVoteEndTicks--; - return 1.0f; + iVoteEndTicks = 3; + return -1.0f; } - ); + + ClientPrintAll(HUD_PRINTTALK, CHAT_PREFIX "Extend vote ending in %d....", iVoteEndTicks); + iVoteEndTicks--; + return 1.0f; + }); } diff --git a/src/votemanager.h b/src/votemanager.h index 49f41fef..2784abc7 100644 --- a/src/votemanager.h +++ b/src/votemanager.h @@ -44,10 +44,10 @@ enum class EExtendState enum EExtendVoteMode { - EXTENDVOTE_OFF, // No extend votes can be called - EXTENDVOTE_ADMINONLY, // Only admins can initiate extend votes, all further options also include this - EXTENDVOTE_MANUAL, // Extend votes are triggered by players typing !ve - EXTENDVOTE_AUTO, // Extend votes can be triggered by !ve or when map timelimit reaches a given value + EXTENDVOTE_OFF, // No extend votes can be called + EXTENDVOTE_ADMINONLY, // Only admins can initiate extend votes, all further options also include this + EXTENDVOTE_MANUAL, // Extend votes are triggered by players typing !ve + EXTENDVOTE_AUTO, // Extend votes can be triggered by !ve or when map timelimit reaches a given value }; extern ERTVState g_RTVState; diff --git a/src/zombiereborn.cpp b/src/zombiereborn.cpp index db1f3cf9..e14da7c9 100644 --- a/src/zombiereborn.cpp +++ b/src/zombiereborn.cpp @@ -20,26 +20,26 @@ #include "usermessages.pb.h" #include "commands.h" -#include "utils/entity.h" -#include "playermanager.h" #include "ctimer.h" -#include "eventlistener.h" -#include "zombiereborn.h" +#include "customio.h" +#include "engine/igameeventsystem.h" #include "entity/cgamerules.h" -#include "entity/services.h" -#include "entity/cteam.h" #include "entity/cparticlesystem.h" -#include "engine/igameeventsystem.h" +#include "entity/cteam.h" +#include "entity/services.h" +#include "eventlistener.h" +#include "leader.h" #include "networksystem/inetworkmessages.h" +#include "playermanager.h" #include "recipientfilters.h" #include "serversideclient.h" -#include "user_preferences.h" -#include "customio.h" -#include -#include "leader.h" #include "tier0/vprof.h" -#include +#include "user_preferences.h" +#include "utils/entity.h" #include "vendor/nlohmann/json.hpp" +#include "zombiereborn.h" +#include +#include #include "tier0/memdbgon.h" @@ -50,12 +50,12 @@ extern IVEngineServer2* g_pEngineServer2; extern CGlobalVars* gpGlobals; extern CCSGameRules* g_pGameRules; extern IGameEventManager2* g_gameEventManager; -extern IGameEventSystem *g_gameEventSystem; +extern IGameEventSystem* g_gameEventSystem; extern double g_flUniversalTime; -void ZR_Infect(CCSPlayerController *pAttackerController, CCSPlayerController *pVictimController, bool bBroadcast); +void ZR_Infect(CCSPlayerController* pAttackerController, CCSPlayerController* pVictimController, bool bBroadcast); bool ZR_CheckTeamWinConditions(int iTeamNum); -void ZR_Cure(CCSPlayerController *pTargetController); +void ZR_Cure(CCSPlayerController* pTargetController); void ZR_EndRoundAndAddTeamScore(int iTeamNum); void SetupCTeams(); bool ZR_IsTeamAlive(int iTeamNum); @@ -68,8 +68,8 @@ static CHandle g_hTeamCT; static CHandle g_hTeamT; CZRPlayerClassManager* g_pZRPlayerClassManager = nullptr; -ZRWeaponConfig *g_pZRWeaponConfig = nullptr; -ZRHitgroupConfig *g_pZRHitgroupConfig = nullptr; +ZRWeaponConfig* g_pZRWeaponConfig = nullptr; +ZRHitgroupConfig* g_pZRHitgroupConfig = nullptr; bool g_bEnableZR = false; static float g_flMaxZteleDistance = 150.0f; @@ -135,7 +135,7 @@ FAKE_FLOAT_CVAR(zr_infect_shake_duration, "Duration of shaking effect", g_flInfe CON_COMMAND_F(zr_reload_classes, "Reload ZR player classes", FCVAR_SPONLY | FCVAR_LINKED_CONCOMMAND) { g_pZRPlayerClassManager->LoadPlayerClass(); - + Message("Reloaded ZR player classes.\n"); } #endif @@ -147,7 +147,7 @@ void ZR_Precache(IEntityResourceManifest* pResourceManifest) pResourceManifest->AddResource(g_szHumanWinOverlayParticle.c_str()); pResourceManifest->AddResource(g_szZombieWinOverlayParticle.c_str()); - + pResourceManifest->AddResource(g_szHumanWinOverlayMaterial.c_str()); pResourceManifest->AddResource(g_szZombieWinOverlayMaterial.c_str()); @@ -162,10 +162,10 @@ void ZR_CreateOverlay(const char* pszOverlayParticlePath, float flAlpha, float f pKeyValues->SetString("effect_name", pszOverlayParticlePath); // these properties are mapped to control point position by the entity - pKeyValues->SetFloat("alphascale", flAlpha); //17.x - pKeyValues->SetFloat("scale", flRadius); //17.y - pKeyValues->SetFloat("selfillumscale", flLifeTime); //17.z - pKeyValues->SetColor("colortint", clrTint); //16.xyz + pKeyValues->SetFloat("alphascale", flAlpha); // 17.x + pKeyValues->SetFloat("scale", flRadius); // 17.y + pKeyValues->SetFloat("selfillumscale", flLifeTime); // 17.z + pKeyValues->SetColor("colortint", clrTint); // 16.xyz pKeyValues->SetString("effect_textureOverride", pszMaterialOverride); @@ -178,31 +178,29 @@ void ZR_CreateOverlay(const char* pszOverlayParticlePath, float flAlpha, float f ZRModelEntry::ZRModelEntry(std::shared_ptr modelEntry) : szModelPath(modelEntry->szModelPath), szColor(modelEntry->szColor) +{ + vecSkins.Purge(); + FOR_EACH_VEC(modelEntry->vecSkins, i) { - vecSkins.Purge(); - FOR_EACH_VEC(modelEntry->vecSkins, i) - { - vecSkins.AddToTail(modelEntry->vecSkins[i]); - } - }; + vecSkins.AddToTail(modelEntry->vecSkins[i]); + } +}; ZRModelEntry::ZRModelEntry(ordered_json jsonModelEntry) : szModelPath(jsonModelEntry.value("modelname", "")), szColor(jsonModelEntry.value("color", "255 255 255")) - { - vecSkins.Purge(); +{ + vecSkins.Purge(); - if (jsonModelEntry.contains("skins")) - { - if (jsonModelEntry["skins"].size() > 0) // single int or array of ints - { - for (auto& [key, skinIndex] : jsonModelEntry["skins"].items()) - vecSkins.AddToTail(skinIndex); - } - return; - } - vecSkins.AddToTail(0); // key missing, set default - }; + if (jsonModelEntry.contains("skins")) + { + if (jsonModelEntry["skins"].size() > 0) // single int or array of ints + for (auto& [key, skinIndex] : jsonModelEntry["skins"].items()) + vecSkins.AddToTail(skinIndex); + return; + } + vecSkins.AddToTail(0); // key missing, set default +}; // seperate parsing to adminsystem's ParseFlags as making class 'z' flagged would make it available to players with non-zero flag uint64 ZRClass::ParseClassFlags(const char* pszFlags) @@ -232,17 +230,16 @@ ZRClass::ZRClass(ordered_json jsonKeys, std::string szClassname, int iTeam) : flSpeed(jsonKeys["speed"].get()), flGravity(jsonKeys["gravity"].get()), iAdminFlag(ParseClassFlags( - jsonKeys["admin_flag"].get().c_str() - )) - { - vecModels.Purge(); + jsonKeys["admin_flag"].get().c_str())) +{ + vecModels.Purge(); - for (auto& [key, jsonModelEntry] : jsonKeys["models"].items()) - { - std::shared_ptr modelEntry = std::make_shared(jsonModelEntry); - vecModels.AddToTail(modelEntry); - } - }; + for (auto& [key, jsonModelEntry] : jsonKeys["models"].items()) + { + std::shared_ptr modelEntry = std::make_shared(jsonModelEntry); + vecModels.AddToTail(modelEntry); + } +}; void ZRClass::Override(ordered_json jsonKeys, std::string szClassname) { @@ -259,13 +256,12 @@ void ZRClass::Override(ordered_json jsonKeys, std::string szClassname) flGravity = jsonKeys["gravity"].get(); if (jsonKeys.contains("admin_flag")) iAdminFlag = ParseClassFlags( - jsonKeys["admin_flag"].get().c_str() - ); + jsonKeys["admin_flag"].get().c_str()); // no models entry key or it's empty, use model entries of base class if (!jsonKeys.contains("models") || jsonKeys["models"].empty()) return; - + // one model entry in base and overriding class, apply model entry keys if defined if (vecModels.Count() == 1 && jsonKeys["models"].size() == 1) { @@ -283,9 +279,9 @@ void ZRClass::Override(ordered_json jsonKeys, std::string szClassname) return; } - + // more than one model entry in either base or child class, either override all entries or none - for (int i = jsonKeys["models"].size()-1; i >= 0; i--) + for (int i = jsonKeys["models"].size() - 1; i >= 0; i--) { if (jsonKeys["models"][i].size() < 3) { @@ -293,7 +289,7 @@ void ZRClass::Override(ordered_json jsonKeys, std::string szClassname) jsonKeys["models"].erase(i); } } - + if (jsonKeys["models"].empty()) { Warning("No valid model entries remaining in child class %s, using model entries of base class %s\n", @@ -310,7 +306,8 @@ void ZRClass::Override(ordered_json jsonKeys, std::string szClassname) } } -ZRHumanClass::ZRHumanClass(ordered_json jsonKeys, std::string szClassname) : ZRClass(jsonKeys, szClassname, CS_TEAM_CT){}; +ZRHumanClass::ZRHumanClass(ordered_json jsonKeys, std::string szClassname) : + ZRClass(jsonKeys, szClassname, CS_TEAM_CT){}; ZRZombieClass::ZRZombieClass(ordered_json jsonKeys, std::string szClassname) : ZRClass(jsonKeys, szClassname, CS_TEAM_T), @@ -329,7 +326,7 @@ void ZRZombieClass::Override(ordered_json jsonKeys, std::string szClassname) flKnockback = jsonKeys["knockback"].get(); } -bool ZRClass::IsApplicableTo(CCSPlayerController *pController) +bool ZRClass::IsApplicableTo(CCSPlayerController* pController) { if (!bEnabled) return false; if (!V_stricmp(szClassName.c_str(), "MotherZombie")) return false; @@ -365,7 +362,7 @@ void CZRPlayerClassManager::LoadPlayerClass() m_vecZombieDefaultClass.Purge(); m_vecHumanDefaultClass.Purge(); - const char *pszJsonPath = "addons/cs2fixes/configs/zr/playerclass.jsonc"; + const char* pszJsonPath = "addons/cs2fixes/configs/zr/playerclass.jsonc"; char szPath[MAX_PATH]; V_snprintf(szPath, sizeof(szPath), "%s%s%s", Plat_GetGameDirectory(), "/csgo/", pszJsonPath); std::ifstream jsoncFile(szPath); @@ -492,10 +489,10 @@ void CZRPlayerClassManager::LoadPlayerClass() if (bTeamDefault) m_vecHumanDefaultClass.AddToTail(pHumanClass); - + pHumanClass->PrintInfo(); } - else + else { std::shared_ptr pZombieClass; if (!szBase.empty()) @@ -518,7 +515,7 @@ void CZRPlayerClassManager::LoadPlayerClass() m_ZombieClassMap.Insert(hash_32_fnv1a_const(szClassName.c_str()), pZombieClass); if (bTeamDefault) m_vecZombieDefaultClass.AddToTail(pZombieClass); - + pZombieClass->PrintInfo(); } @@ -552,7 +549,7 @@ void CZRPlayerClassManager::ApplyBaseClass(std::shared_ptr pClass, CCSP // I don't know why, I don't want to know why, // I shouldn't have to wonder why, but for whatever reason // this shit caused crashes on ROUND END or MAP CHANGE after the 26/04/2024 update - //pPawn->m_flVelocityModifier = pClass->flSpeed; + // pPawn->m_flVelocityModifier = pClass->flSpeed; const auto pController = reinterpret_cast(pPawn->GetController()); if (const auto pPlayer = pController != nullptr ? pController->GetZEPlayer() : nullptr) { @@ -571,7 +568,7 @@ void CZRPlayerClassManager::ApplyBaseClassVisuals(std::shared_ptr pClas std::shared_ptr pModelEntry = pClass->GetRandomModelEntry(); Color clrRender; V_StringToColor(pModelEntry->szColor.c_str(), clrRender); - + pPawn->SetModel(pModelEntry->szModelPath.c_str()); pPawn->m_clrRender = clrRender; pPawn->AcceptInput("Skin", pModelEntry->GetRandomSkin()); @@ -598,22 +595,21 @@ std::shared_ptr CZRPlayerClassManager::GetHumanClass(const char* p void CZRPlayerClassManager::ApplyHumanClass(std::shared_ptr pClass, CCSPlayerPawn* pPawn) { ApplyBaseClass(pClass, pPawn); - CCSPlayerController *pController = CCSPlayerController::FromPawn(pPawn); + CCSPlayerController* pController = CCSPlayerController::FromPawn(pPawn); if (pController) CZRRegenTimer::StopRegen(pController); - + if (!g_bEnableLeader || !pController) return; - - ZEPlayer *pPlayer = g_playerManager->GetPlayer(pController->GetPlayerSlot()); + + ZEPlayer* pPlayer = g_playerManager->GetPlayer(pController->GetPlayerSlot()); if (pPlayer && pPlayer->IsLeader()) { CHandle hPawn = pPawn->GetHandle(); - new CTimer(0.02f, false, false, [hPawn]() - { - CCSPlayerPawn *pPawn = hPawn.Get(); + new CTimer(0.02f, false, false, [hPawn]() { + CCSPlayerPawn* pPawn = hPawn.Get(); if (pPawn) Leader_ApplyLeaderVisuals(pPawn); return -1.0f; @@ -621,9 +617,9 @@ void CZRPlayerClassManager::ApplyHumanClass(std::shared_ptr pClass } } -void CZRPlayerClassManager::ApplyPreferredOrDefaultHumanClass(CCSPlayerPawn *pPawn) +void CZRPlayerClassManager::ApplyPreferredOrDefaultHumanClass(CCSPlayerPawn* pPawn) { - CCSPlayerController *pController = CCSPlayerController::FromPawn(pPawn); + CCSPlayerController* pController = CCSPlayerController::FromPawn(pPawn); if (!pController) return; // Get the human class user preference, or default if no class is set @@ -633,21 +629,26 @@ void CZRPlayerClassManager::ApplyPreferredOrDefaultHumanClass(CCSPlayerPawn *pPa // If the preferred human class exists and can be applied, override the default uint16 index = m_HumanClassMap.Find(hash_32_fnv1a_const(sPreferredHumanClass)); - if (m_HumanClassMap.IsValidIndex(index) && m_HumanClassMap[index]->IsApplicableTo(pController)) { + if (m_HumanClassMap.IsValidIndex(index) && m_HumanClassMap[index]->IsApplicableTo(pController)) + { humanClass = m_HumanClassMap[index]; - } else if (m_vecHumanDefaultClass.Count()) { + } + else if (m_vecHumanDefaultClass.Count()) + { humanClass = m_vecHumanDefaultClass[rand() % m_vecHumanDefaultClass.Count()]; - } else if (!humanClass) { + } + else if (!humanClass) + { Warning("Missing default human class or valid preferences!\n"); return; } - + ApplyHumanClass(humanClass, pPawn); } -void CZRPlayerClassManager::ApplyPreferredOrDefaultHumanClassVisuals(CCSPlayerPawn *pPawn) +void CZRPlayerClassManager::ApplyPreferredOrDefaultHumanClassVisuals(CCSPlayerPawn* pPawn) { - CCSPlayerController *pController = CCSPlayerController::FromPawn(pPawn); + CCSPlayerController* pController = CCSPlayerController::FromPawn(pPawn); if (!pController) return; // Get the human class user preference, or default if no class is set @@ -657,11 +658,16 @@ void CZRPlayerClassManager::ApplyPreferredOrDefaultHumanClassVisuals(CCSPlayerPa // If the preferred human class exists and can be applied, override the default uint16 index = m_HumanClassMap.Find(hash_32_fnv1a_const(sPreferredHumanClass)); - if (m_HumanClassMap.IsValidIndex(index) && m_HumanClassMap[index]->IsApplicableTo(pController)) { + if (m_HumanClassMap.IsValidIndex(index) && m_HumanClassMap[index]->IsApplicableTo(pController)) + { humanClass = m_HumanClassMap[index]; - } else if (m_vecHumanDefaultClass.Count()) { + } + else if (m_vecHumanDefaultClass.Count()) + { humanClass = m_vecHumanDefaultClass[rand() % m_vecHumanDefaultClass.Count()]; - } else if (!humanClass) { + } + else if (!humanClass) + { Warning("Missing default human class or valid preferences!\n"); return; } @@ -680,14 +686,14 @@ std::shared_ptr CZRPlayerClassManager::GetZombieClass(const char* void CZRPlayerClassManager::ApplyZombieClass(std::shared_ptr pClass, CCSPlayerPawn* pPawn) { ApplyBaseClass(pClass, pPawn); - CCSPlayerController *pController = CCSPlayerController::FromPawn(pPawn); + CCSPlayerController* pController = CCSPlayerController::FromPawn(pPawn); if (pController) CZRRegenTimer::StartRegen(pClass->flHealthRegenInterval, pClass->iHealthRegenCount, pController); } -void CZRPlayerClassManager::ApplyPreferredOrDefaultZombieClass(CCSPlayerPawn *pPawn) +void CZRPlayerClassManager::ApplyPreferredOrDefaultZombieClass(CCSPlayerPawn* pPawn) { - CCSPlayerController *pController = CCSPlayerController::FromPawn(pPawn); + CCSPlayerController* pController = CCSPlayerController::FromPawn(pPawn); if (!pController) return; // Get the zombie class user preference, or default if no class is set @@ -697,15 +703,20 @@ void CZRPlayerClassManager::ApplyPreferredOrDefaultZombieClass(CCSPlayerPawn *pP // If the preferred zombie class exists and can be applied, override the default uint16 index = m_ZombieClassMap.Find(hash_32_fnv1a_const(sPreferredZombieClass)); - if (m_ZombieClassMap.IsValidIndex(index) && m_ZombieClassMap[index]->IsApplicableTo(pController)) { + if (m_ZombieClassMap.IsValidIndex(index) && m_ZombieClassMap[index]->IsApplicableTo(pController)) + { zombieClass = m_ZombieClassMap[index]; - } else if (m_vecZombieDefaultClass.Count()) { + } + else if (m_vecZombieDefaultClass.Count()) + { zombieClass = m_vecZombieDefaultClass[rand() % m_vecZombieDefaultClass.Count()]; - } else if (!zombieClass) { + } + else if (!zombieClass) + { Warning("Missing default zombie class or valid preferences!\n"); return; } - + ApplyZombieClass(zombieClass, pPawn); } @@ -731,11 +742,11 @@ void CZRPlayerClassManager::GetZRClassList(int iTeam, CUtlVectorIsAlive()) return false; @@ -748,10 +759,10 @@ bool CZRRegenTimer::Execute() return true; } -void CZRRegenTimer::StartRegen(float flRegenInterval, int iRegenAmount, CCSPlayerController *pController) +void CZRRegenTimer::StartRegen(float flRegenInterval, int iRegenAmount, CCSPlayerController* pController) { int slot = pController->GetPlayerSlot(); - CZRRegenTimer *pTimer = s_vecRegenTimers[slot]; + CZRRegenTimer* pTimer = s_vecRegenTimers[slot]; if (pTimer != nullptr) { pTimer->m_flInterval = flRegenInterval; @@ -761,7 +772,7 @@ void CZRRegenTimer::StartRegen(float flRegenInterval, int iRegenAmount, CCSPlaye s_vecRegenTimers[slot] = new CZRRegenTimer(flRegenInterval, iRegenAmount, pController->m_hPlayerPawn()); } -void CZRRegenTimer::StopRegen(CCSPlayerController *pController) +void CZRRegenTimer::StopRegen(CCSPlayerController* pController) { int slot = pController->GetPlayerSlot(); if (!s_vecRegenTimers[slot]) @@ -782,16 +793,14 @@ void CZRRegenTimer::Tick() s_flNextExecution = g_flUniversalTime + 0.1f; for (int i = MAXPLAYERS - 1; i >= 0; i--) { - CZRRegenTimer *pTimer = s_vecRegenTimers[i]; + CZRRegenTimer* pTimer = s_vecRegenTimers[i]; if (!pTimer) - { continue; - } - + if (pTimer->m_flLastExecute == -1) pTimer->m_flLastExecute = g_flUniversalTime; - // Timer execute + // Timer execute if (pTimer->m_flLastExecute + pTimer->m_flInterval <= g_flUniversalTime) { pTimer->Execute(); @@ -805,9 +814,7 @@ void CZRRegenTimer::RemoveAllTimers() for (int i = MAXPLAYERS - 1; i >= 0; i--) { if (!s_vecRegenTimers[i]) - { continue; - } delete s_vecRegenTimers[i]; s_vecRegenTimers[i] = nullptr; } @@ -818,8 +825,7 @@ void ZR_OnLevelInit() g_ZRRoundState = EZRRoundState::ROUND_START; // Delay one tick to override any .cfg's - new CTimer(0.02f, false, true, []() - { + new CTimer(0.02f, false, true, []() { // Here we force some cvars that are necessary for the gamemode g_pEngineServer2->ServerCommand("mp_give_player_c4 0"); g_pEngineServer2->ServerCommand("mp_friendlyfire 0"); @@ -847,7 +853,7 @@ void ZRWeaponConfig::LoadWeaponConfig() KeyValues* pKV = new KeyValues("Weapons"); KeyValues::AutoDelete autoDelete(pKV); - const char *pszPath = "addons/cs2fixes/configs/zr/weapons.cfg"; + const char* pszPath = "addons/cs2fixes/configs/zr/weapons.cfg"; if (!pKV->LoadFromFile(g_pFullFileSystem, pszPath)) { @@ -856,7 +862,7 @@ void ZRWeaponConfig::LoadWeaponConfig() } for (KeyValues* pKey = pKV->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey()) { - const char *pszWeaponName = pKey->GetName(); + const char* pszWeaponName = pKey->GetName(); bool bEnabled = pKey->GetBool("enabled", false); float flKnockback = pKey->GetFloat("knockback", 1.0f); Message("%s knockback: %f\n", pszWeaponName, flKnockback); @@ -872,7 +878,7 @@ void ZRWeaponConfig::LoadWeaponConfig() return; } -std::shared_ptr ZRWeaponConfig::FindWeapon(const char *pszWeaponName) +std::shared_ptr ZRWeaponConfig::FindWeapon(const char* pszWeaponName) { uint16 index = m_WeaponMap.Find(hash_32_fnv1a_const(pszWeaponName)); if (m_WeaponMap.IsValidIndex(index)) @@ -887,7 +893,7 @@ void ZRHitgroupConfig::LoadHitgroupConfig() KeyValues* pKV = new KeyValues("Hitgroups"); KeyValues::AutoDelete autoDelete(pKV); - const char *pszPath = "addons/cs2fixes/configs/zr/hitgroups.cfg"; + const char* pszPath = "addons/cs2fixes/configs/zr/hitgroups.cfg"; if (!pKV->LoadFromFile(g_pFullFileSystem, pszPath)) { @@ -896,8 +902,8 @@ void ZRHitgroupConfig::LoadHitgroupConfig() } for (KeyValues* pKey = pKV->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey()) { - const char *pszHitgroupName = pKey->GetName(); - float flKnockback= pKey->GetFloat("knockback", 1.0f); + const char* pszHitgroupName = pKey->GetName(); + float flKnockback = pKey->GetFloat("knockback", 1.0f); int iIndex = -1; if (!V_strcasecmp(pszHitgroupName, "Generic")) @@ -926,7 +932,7 @@ void ZRHitgroupConfig::LoadHitgroupConfig() Panic("Failed to load hitgroup %s, invalid name!", pszHitgroupName); continue; } - + std::shared_ptr hitGroup = std::make_shared(); hitGroup->flKnockback = flKnockback; @@ -940,11 +946,11 @@ void ZRHitgroupConfig::LoadHitgroupConfig() std::shared_ptr ZRHitgroupConfig::FindHitgroupIndex(int iIndex) { uint16 index = m_HitgroupMap.Find(iIndex); - //Message("We are finding hitgroup index with index: %d and index is: %d\n", iIndex, index); + // Message("We are finding hitgroup index with index: %d and index is: %d\n", iIndex, index); if (m_HitgroupMap.IsValidIndex(index)) { - //Message("We found valid index with (m_HitgroupMap[index]): %d\n", m_HitgroupMap[index]); + // Message("We found valid index with (m_HitgroupMap[index]): %d\n", m_HitgroupMap[index]); return m_HitgroupMap[index]; } @@ -993,7 +999,7 @@ void ZR_OnRoundPrestart(IGameEvent* pEvent) if (pController->m_iTeamNum() == CS_TEAM_T) pController->SwitchTeam(CS_TEAM_CT); - CCSPlayerPawn *pPawn = pController->GetPlayerPawn(); + CCSPlayerPawn* pPawn = pController->GetPlayerPawn(); // Prevent damage that occurs between now and when the round restart is finished // Somehow CT filtered nukes can apply damage during the round restart (all within CCSGameRules::RestartRound) @@ -1017,16 +1023,10 @@ void SetupCTeams() { CTeam* pTeam = nullptr; while (nullptr != (pTeam = (CTeam*)UTIL_FindEntityByClassname(pTeam, "cs_team_manager"))) - { if (pTeam->m_iTeamNum() == CS_TEAM_CT) - { g_hTeamCT = pTeam->GetHandle(); - } else if (pTeam->m_iTeamNum() == CS_TEAM_T) - { g_hTeamT = pTeam->GetHandle(); - } - } } void ZR_OnRoundStart(IGameEvent* pEvent) @@ -1037,12 +1037,12 @@ void ZR_OnRoundStart(IGameEvent* pEvent) for (int i = 0; i < gpGlobals->maxClients; i++) { - CCSPlayerController *pController = CCSPlayerController::FromSlot(i); + CCSPlayerController* pController = CCSPlayerController::FromSlot(i); if (!pController) continue; - CCSPlayerPawn *pPawn = pController->GetPlayerPawn(); + CCSPlayerPawn* pPawn = pController->GetPlayerPawn(); // Now we can enable damage back if (pPawn) @@ -1057,7 +1057,7 @@ void ZR_OnPlayerSpawn(CCSPlayerController* pController) // We're infecting this guy with a delay, disable all damage as they have 100 hp until then // also set team immediately in case the spawn teleport is team filtered - if (bInfect) + if (bInfect) { pController->GetPawn()->m_bTakesDamage(false); pController->SwitchTeam(CS_TEAM_T); @@ -1068,12 +1068,11 @@ void ZR_OnPlayerSpawn(CCSPlayerController* pController) } CHandle handle = pController->GetHandle(); - new CTimer(0.05f, false, false, [handle, bInfect]() - { + new CTimer(0.05f, false, false, [handle, bInfect]() { CCSPlayerController* pController = (CCSPlayerController*)handle.Get(); if (!pController) return -1.0f; - if(bInfect) + if (bInfect) ZR_Infect(pController, pController, true); else ZR_Cure(pController); @@ -1081,7 +1080,7 @@ void ZR_OnPlayerSpawn(CCSPlayerController* pController) }); } -void ZR_ApplyKnockback(CCSPlayerPawn *pHuman, CCSPlayerPawn *pVictim, int iDamage, const char *szWeapon, int hitgroup, float classknockback) +void ZR_ApplyKnockback(CCSPlayerPawn* pHuman, CCSPlayerPawn* pVictim, int iDamage, const char* szWeapon, int hitgroup, float classknockback) { std::shared_ptr pWeapon = g_pZRWeaponConfig->FindWeapon(szWeapon); std::shared_ptr pHitgroup = g_pZRHitgroupConfig->FindHitgroupIndex(hitgroup); @@ -1100,7 +1099,7 @@ void ZR_ApplyKnockback(CCSPlayerPawn *pHuman, CCSPlayerPawn *pVictim, int iDamag pVictim->m_vecAbsVelocity = pVictim->m_vecAbsVelocity() + vecKnockback; } -void ZR_ApplyKnockbackExplosion(CBaseEntity *pProjectile, CCSPlayerPawn *pVictim, int iDamage, bool bMolotov) +void ZR_ApplyKnockbackExplosion(CBaseEntity* pProjectile, CCSPlayerPawn* pVictim, int iDamage, bool bMolotov) { std::shared_ptr pWeapon = g_pZRWeaponConfig->FindWeapon(pProjectile->GetClassname()); if (!pWeapon) @@ -1119,9 +1118,9 @@ void ZR_ApplyKnockbackExplosion(CBaseEntity *pProjectile, CCSPlayerPawn *pVictim pVictim->m_vecAbsVelocity = pVictim->m_vecAbsVelocity() + vecKnockback; } -void ZR_FakePlayerDeath(CCSPlayerController *pAttackerController, CCSPlayerController *pVictimController, const char *szWeapon) +void ZR_FakePlayerDeath(CCSPlayerController* pAttackerController, CCSPlayerController* pVictimController, const char* szWeapon) { - IGameEvent *pEvent = g_gameEventManager->CreateEvent("player_death"); + IGameEvent* pEvent = g_gameEventManager->CreateEvent("player_death"); if (!pEvent) return; @@ -1136,12 +1135,12 @@ void ZR_FakePlayerDeath(CCSPlayerController *pAttackerController, CCSPlayerContr g_gameEventManager->FireEvent(pEvent, false); } -void ZR_StripAndGiveKnife(CCSPlayerPawn *pPawn) +void ZR_StripAndGiveKnife(CCSPlayerPawn* pPawn) { - CCSPlayer_ItemServices *pItemServices = pPawn->m_pItemServices(); + CCSPlayer_ItemServices* pItemServices = pPawn->m_pItemServices(); CCSPlayer_WeaponServices* pWeaponServices = pPawn->m_pWeaponServices(); - // it can sometimes be null when player joined on the very first round? + // it can sometimes be null when player joined on the very first round? if (!pItemServices || !pWeaponServices) return; @@ -1178,17 +1177,17 @@ void ZR_StripAndGiveKnife(CCSPlayerPawn *pPawn) } } -void ZR_Cure(CCSPlayerController *pTargetController) +void ZR_Cure(CCSPlayerController* pTargetController) { if (pTargetController->m_iTeamNum() == CS_TEAM_T) pTargetController->SwitchTeam(CS_TEAM_CT); - ZEPlayer *pZEPlayer = pTargetController->GetZEPlayer(); + ZEPlayer* pZEPlayer = pTargetController->GetZEPlayer(); if (pZEPlayer) pZEPlayer->SetInfectState(false); - CCSPlayerPawn *pTargetPawn = (CCSPlayerPawn*)pTargetController->GetPawn(); + CCSPlayerPawn* pTargetPawn = (CCSPlayerPawn*)pTargetController->GetPawn(); if (!pTargetPawn) return; @@ -1203,7 +1202,7 @@ float ZR_MoanTimer(ZEPlayerHandle hPlayer) if (!hPlayer.Get()->IsInfected()) return -1.f; - CCSPlayerPawn *pPawn = CCSPlayerController::FromSlot(hPlayer.GetPlayerSlot())->GetPlayerPawn(); + CCSPlayerPawn* pPawn = CCSPlayerController::FromSlot(hPlayer.GetPlayerSlot())->GetPlayerPawn(); if (!pPawn || pPawn->m_iTeamNum == CS_TEAM_CT) return -1.f; @@ -1217,12 +1216,12 @@ float ZR_MoanTimer(ZEPlayerHandle hPlayer) return g_flMoanInterval + (rand() % 5); } -void ZR_InfectShake(CCSPlayerController *pController) +void ZR_InfectShake(CCSPlayerController* pController) { if (!pController || !pController->IsConnected() || pController->IsBot() || !g_bInfectShake) return; - INetworkMessageInternal *pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("Shake"); + INetworkMessageInternal* pNetMsg = g_pNetworkMessages->FindNetworkMessagePartial("Shake"); auto data = pNetMsg->AllocateMessage()->ToPB(); @@ -1244,10 +1243,10 @@ std::vector ZR_GetSpawns() std::vector spawns; FOR_EACH_VEC(*ctSpawns, i) - spawns.push_back((*ctSpawns)[i]); + spawns.push_back((*ctSpawns)[i]); FOR_EACH_VEC(*tSpawns, i) - spawns.push_back((*tSpawns)[i]); + spawns.push_back((*tSpawns)[i]); if (!spawns.size()) Panic("There are no spawns!\n"); @@ -1255,7 +1254,7 @@ std::vector ZR_GetSpawns() return spawns; } -void ZR_Infect(CCSPlayerController *pAttackerController, CCSPlayerController *pVictimController, bool bDontBroadcast) +void ZR_Infect(CCSPlayerController* pAttackerController, CCSPlayerController* pVictimController, bool bDontBroadcast) { // This can be null if the victim disconnected right before getting hit AND someone joined in their place immediately, thus replacing the controller if (!pVictimController) @@ -1269,7 +1268,7 @@ void ZR_Infect(CCSPlayerController *pAttackerController, CCSPlayerController *pV if (!bDontBroadcast) ZR_FakePlayerDeath(pAttackerController, pVictimController, "knife"); // or any other killicon - CCSPlayerPawn *pVictimPawn = (CCSPlayerPawn*)pVictimController->GetPawn(); + CCSPlayerPawn* pVictimPawn = (CCSPlayerPawn*)pVictimController->GetPawn(); if (!pVictimPawn) return; @@ -1279,12 +1278,12 @@ void ZR_Infect(CCSPlayerController *pAttackerController, CCSPlayerController *pV pVictimPawn->EmitSound("zr.amb.scream"); ZR_StripAndGiveKnife(pVictimPawn); - + g_pZRPlayerClassManager->ApplyPreferredOrDefaultZombieClass(pVictimPawn); ZR_InfectShake(pVictimController); - ZEPlayer *pZEPlayer = pVictimController->GetZEPlayer(); + ZEPlayer* pZEPlayer = pVictimController->GetZEPlayer(); if (pZEPlayer && !pZEPlayer->IsInfected()) { @@ -1295,9 +1294,9 @@ void ZR_Infect(CCSPlayerController *pAttackerController, CCSPlayerController *pV } } -void ZR_InfectMotherZombie(CCSPlayerController *pVictimController, std::vector spawns) +void ZR_InfectMotherZombie(CCSPlayerController* pVictimController, std::vector spawns) { - CCSPlayerPawn *pVictimPawn = (CCSPlayerPawn*)pVictimController->GetPawn(); + CCSPlayerPawn* pVictimPawn = (CCSPlayerPawn*)pVictimController->GetPawn(); if (!pVictimPawn) return; @@ -1324,7 +1323,7 @@ void ZR_InfectMotherZombie(CCSPlayerController *pVictimController, std::vectorGetZEPlayer(); + ZEPlayer* pZEPlayer = pVictimController->GetZEPlayer(); pZEPlayer->SetInfectState(true); @@ -1363,13 +1362,13 @@ void ZR_InitialInfection() // the num of mz to infect int iMZToInfect = pCandidateControllers.Count() / g_iInfectSpawnMZRatio; iMZToInfect = g_iInfectSpawnMinCount > iMZToInfect ? g_iInfectSpawnMinCount : iMZToInfect; - bool vecIsMZ[MAXPLAYERS] = { false }; + bool vecIsMZ[MAXPLAYERS] = {false}; // get spawn points std::vector spawns = ZR_GetSpawns(); if (g_iInfectSpawnType == EZRSpawnType::RESPAWN && !spawns.size()) { - ClientPrintAll(HUD_PRINTTALK, ZR_PREFIX"There are no spawns!"); + ClientPrintAll(HUD_PRINTTALK, ZR_PREFIX "There are no spawns!"); return; } @@ -1377,7 +1376,7 @@ void ZR_InitialInfection() int iFailSafeCounter = 0; while (iMZToInfect > 0) { - //If we somehow don't have enough mother zombies after going through the players 5 times, + // If we somehow don't have enough mother zombies after going through the players 5 times, if (iFailSafeCounter >= 5) { FOR_EACH_VEC(pCandidateControllers, i) @@ -1411,7 +1410,7 @@ void ZR_InitialInfection() CCSPlayerController* pController = (CCSPlayerController*)pSurvivorControllers[randomindex]; CCSPlayerPawn* pPawn = (CCSPlayerPawn*)pController->GetPawn(); ZEPlayer* pPlayer = pSurvivorControllers[randomindex]->GetZEPlayer(); - //roll for immunity + // roll for immunity if (rand() % 100 < pPlayer->GetImmunity()) { pSurvivorControllers.FastRemove(randomindex); @@ -1433,7 +1432,7 @@ void ZR_InitialInfection() ZEPlayer* pPlayer = g_playerManager->GetPlayer(i); if (!pPlayer || vecIsMZ[i]) continue; - + pPlayer->SetImmunity(pPlayer->GetImmunity() - g_iMZImmunityReduction); } @@ -1451,8 +1450,7 @@ void ZR_StartInitialCountdown() V_swap(g_iInfectSpawnTimeMin, g_iInfectSpawnTimeMax); g_iInfectionCountDown = g_iInfectSpawnTimeMin + (rand() % (g_iInfectSpawnTimeMax - g_iInfectSpawnTimeMin + 1)); - new CTimer(0.0f, false, false, []() - { + new CTimer(0.0f, false, false, []() { if (g_ZRRoundState != EZRRoundState::ROUND_START) return -1.0f; if (g_iInfectionCountDown <= 0) @@ -1476,16 +1474,16 @@ void ZR_StartInitialCountdown() }); } -bool ZR_Hook_OnTakeDamage_Alive(CTakeDamageInfo *pInfo, CCSPlayerPawn *pVictimPawn) +bool ZR_Hook_OnTakeDamage_Alive(CTakeDamageInfo* pInfo, CCSPlayerPawn* pVictimPawn) { CCSPlayerPawn* pAttackerPawn = (CCSPlayerPawn*)pInfo->m_hAttacker.Get(); if (!(pAttackerPawn && pVictimPawn && pAttackerPawn->IsPawn() && pVictimPawn->IsPawn())) return false; - CCSPlayerController *pAttackerController = CCSPlayerController::FromPawn(pAttackerPawn); - CCSPlayerController *pVictimController = CCSPlayerController::FromPawn(pVictimPawn); - const char *pszAbilityClass = pInfo->m_hAbility.Get() ? pInfo->m_hAbility.Get()->GetClassname() : ""; + CCSPlayerController* pAttackerController = CCSPlayerController::FromPawn(pAttackerPawn); + CCSPlayerController* pVictimController = CCSPlayerController::FromPawn(pVictimPawn); + const char* pszAbilityClass = pInfo->m_hAbility.Get() ? pInfo->m_hAbility.Get()->GetClassname() : ""; if (pAttackerPawn->m_iTeamNum() == CS_TEAM_T && pVictimPawn->m_iTeamNum() == CS_TEAM_CT && !V_strncmp(pszAbilityClass, "weapon_knife", 12)) { ZR_Infect(pAttackerController, pVictimController, false); @@ -1498,8 +1496,8 @@ bool ZR_Hook_OnTakeDamage_Alive(CTakeDamageInfo *pInfo, CCSPlayerPawn *pVictimPa // grenade and molotov knockback if (pAttackerPawn->m_iTeamNum() == CS_TEAM_CT && pVictimPawn->m_iTeamNum() == CS_TEAM_T) { - CBaseEntity *pInflictor = pInfo->m_hInflictor.Get(); - const char *pszInflictorClass = pInflictor ? pInflictor->GetClassname() : ""; + CBaseEntity* pInflictor = pInfo->m_hInflictor.Get(); + const char* pszInflictorClass = pInflictor ? pInflictor->GetClassname() : ""; // inflictor class from grenade damage is actually hegrenade_projectile bool bGrenade = V_strncmp(pszInflictorClass, "hegrenade", 9) == 0; bool bInferno = V_strncmp(pszInflictorClass, "inferno", 7) == 0; @@ -1522,12 +1520,12 @@ bool ZR_Hook_OnTakeDamage_Alive(CTakeDamageInfo *pInfo, CCSPlayerPawn *pVictimPa } // return false to prevent player from picking it up -bool ZR_Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices *pWeaponServices, CBasePlayerWeapon* pPlayerWeapon) +bool ZR_Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices* pWeaponServices, CBasePlayerWeapon* pPlayerWeapon) { - CCSPlayerPawn *pPawn = pWeaponServices->__m_pChainEntity(); + CCSPlayerPawn* pPawn = pWeaponServices->__m_pChainEntity(); if (!pPawn) return false; - const char *pszWeaponClassname = pPlayerWeapon->GetClassname(); + const char* pszWeaponClassname = pPlayerWeapon->GetClassname(); if (pPawn->m_iTeamNum() == CS_TEAM_T && V_strncmp(pszWeaponClassname, "weapon_knife", 12) && V_strncmp(pszWeaponClassname, "weapon_c4", 9)) return false; if (pPawn->m_iTeamNum() == CS_TEAM_CT && V_strlen(pszWeaponClassname) > 7 && !g_pZRWeaponConfig->FindWeapon(pszWeaponClassname + 7)) @@ -1573,8 +1571,7 @@ void SpawnPlayer(CCSPlayerController* pController) } CHandle handle = pController->GetHandle(); - new CTimer(2.0f, false, false, [handle]() - { + new CTimer(2.0f, false, false, [handle]() { CCSPlayerController* pController = (CCSPlayerController*)handle.Get(); if (!pController || !g_bRespawnEnabled || pController->m_iTeamNum < CS_TEAM_T) return -1.0f; @@ -1583,7 +1580,7 @@ void SpawnPlayer(CCSPlayerController* pController) }); } -void ZR_Hook_ClientPutInServer(CPlayerSlot slot, char const *pszName, int type, uint64 xuid) +void ZR_Hook_ClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid) { CCSPlayerController* pController = CCSPlayerController::FromSlot(slot); if (!pController) @@ -1592,7 +1589,7 @@ void ZR_Hook_ClientPutInServer(CPlayerSlot slot, char const *pszName, int type, SpawnPlayer(pController); } -void ZR_Hook_ClientCommand_JoinTeam(CPlayerSlot slot, const CCommand &args) +void ZR_Hook_ClientCommand_JoinTeam(CPlayerSlot slot, const CCommand& args) { CCSPlayerController* pController = CCSPlayerController::FromSlot(slot); if (!pController) @@ -1610,8 +1607,8 @@ void ZR_Hook_ClientCommand_JoinTeam(CPlayerSlot slot, const CCommand &args) void ZR_OnPlayerHurt(IGameEvent* pEvent) { - CCSPlayerController *pAttackerController = (CCSPlayerController*)pEvent->GetPlayerController("attacker"); - CCSPlayerController *pVictimController = (CCSPlayerController*)pEvent->GetPlayerController("userid"); + CCSPlayerController* pAttackerController = (CCSPlayerController*)pEvent->GetPlayerController("attacker"); + CCSPlayerController* pVictimController = (CCSPlayerController*)pEvent->GetPlayerController("userid"); const char* szWeapon = pEvent->GetString("weapon"); int iDmgHealth = pEvent->GetInt("dmg_health"); int iHitGroup = pEvent->GetInt("hitgroup"); @@ -1642,10 +1639,10 @@ void ZR_OnPlayerDeath(IGameEvent* pEvent) if (pEvent->GetBool("infected")) return; - CCSPlayerController *pVictimController = (CCSPlayerController*)pEvent->GetPlayerController("userid"); + CCSPlayerController* pVictimController = (CCSPlayerController*)pEvent->GetPlayerController("userid"); if (!pVictimController) return; - CCSPlayerPawn *pVictimPawn = (CCSPlayerPawn*)pVictimController->GetPawn(); + CCSPlayerPawn* pVictimPawn = (CCSPlayerPawn*)pVictimController->GetPawn(); if (!pVictimPawn) return; @@ -1656,8 +1653,7 @@ void ZR_OnPlayerDeath(IGameEvent* pEvent) // respawn player CHandle handle = pVictimController->GetHandle(); - new CTimer(g_flRespawnDelay < 0.0f ? 2.0f : g_flRespawnDelay, false, false, [handle]() - { + new CTimer(g_flRespawnDelay < 0.0f ? 2.0f : g_flRespawnDelay, false, false, [handle]() { CCSPlayerController* pController = (CCSPlayerController*)handle.Get(); if (!pController || !g_bRespawnEnabled || pController->m_iTeamNum < CS_TEAM_T) return -1.0f; @@ -1674,8 +1670,7 @@ void ZR_OnRoundFreezeEnd(IGameEvent* pEvent) // there is probably a better way to check when time is running out... void ZR_OnRoundTimeWarning(IGameEvent* pEvent) { - new CTimer(10.0, false, false, []() - { + new CTimer(10.0, false, false, []() { if (g_ZRRoundState == EZRRoundState::ROUND_END) return -1.0f; ZR_EndRoundAndAddTeamScore(g_iDefaultWinnerTeam); @@ -1691,7 +1686,7 @@ bool ZR_IsTeamAlive(int iTeamNum) { if (!pPawn->IsAlive()) continue; - + if (pPawn->m_iTeamNum() == iTeamNum) return true; } @@ -1772,7 +1767,7 @@ void ZR_EndRoundAndAddTeamScore(int iTeamNum) ZR_CreateOverlay(g_szHumanWinOverlayParticle.c_str(), 1.0f, g_flHumanWinOverlaySize, flRestartDelay, Color(255, 255, 255), g_szHumanWinOverlayMaterial.c_str()); } else if (iTeamNum == CS_TEAM_T) - { + { if (!g_hTeamT.Get()) { Panic("Cannot find CTeam for T!\n"); @@ -1806,35 +1801,34 @@ CON_COMMAND_CHAT(ztele, "- Teleport to spawn") std::vector spawns = ZR_GetSpawns(); if (!spawns.size()) { - ClientPrint(player, HUD_PRINTTALK, ZR_PREFIX"There are no spawns!"); + ClientPrint(player, HUD_PRINTTALK, ZR_PREFIX "There are no spawns!"); return; } - //Pick and get random spawnpoint + // Pick and get random spawnpoint int randomindex = rand() % spawns.size(); CHandle spawnHandle = spawns[randomindex]->GetHandle(); - //Here's where the mess starts - CBasePlayerPawn *pPawn = player->GetPawn(); + // Here's where the mess starts + CBasePlayerPawn* pPawn = player->GetPawn(); if (!pPawn) return; if (!pPawn->IsAlive()) { - ClientPrint(player, HUD_PRINTTALK, ZR_PREFIX"You cannot teleport when dead!"); + ClientPrint(player, HUD_PRINTTALK, ZR_PREFIX "You cannot teleport when dead!"); return; } - //Get initial player position so we can do distance check + // Get initial player position so we can do distance check Vector initialpos = pPawn->GetAbsOrigin(); - ClientPrint(player, HUD_PRINTTALK, ZR_PREFIX"Teleporting to spawn in 5 seconds."); + ClientPrint(player, HUD_PRINTTALK, ZR_PREFIX "Teleporting to spawn in 5 seconds."); CHandle pawnHandle = pPawn->GetHandle(); - new CTimer(5.0f, false, false, [spawnHandle, pawnHandle, initialpos]() - { + new CTimer(5.0f, false, false, [spawnHandle, pawnHandle, initialpos]() { CCSPlayerPawn* pPawn = pawnHandle.Get(); SpawnPoint* pSpawn = spawnHandle.Get(); @@ -1894,7 +1888,7 @@ CON_COMMAND_CHAT(zclass, " - Find and select your Z: const char* sTeamName = team == CS_TEAM_CT ? "Human" : "Zombie"; const char* sCurrentClass = g_pUserPreferencesSystem->GetPreference(iSlot, team == CS_TEAM_CT ? HUMAN_CLASS_KEY_NAME : ZOMBIE_CLASS_KEY_NAME); - + if (sCurrentClass[0] != '\0') ClientPrint(player, HUD_PRINTTALK, ZR_PREFIX "Your current %s class is: \x10%s\x1. Available classes:", sTeamName, sCurrentClass); else @@ -1903,7 +1897,7 @@ CON_COMMAND_CHAT(zclass, " - Find and select your Z: FOR_EACH_VEC(vecClasses, i) { if (vecClasses[i]->iTeam == team) - ClientPrint(player, HUD_PRINTTALK, "%i. %s", i+1, vecClasses[i]->szClassName.c_str()); + ClientPrint(player, HUD_PRINTTALK, "%i. %s", i + 1, vecClasses[i]->szClassName.c_str()); } } diff --git a/src/zombiereborn.h b/src/zombiereborn.h index e3822d9d..f402787e 100644 --- a/src/zombiereborn.h +++ b/src/zombiereborn.h @@ -19,11 +19,11 @@ #pragma once #include "adminsystem.h" -#include "eventlistener.h" #include "ctimer.h" -#include "gamesystem.h" #include "entity/ccsplayercontroller.h" #include "entity/ccsplayerpawn.h" +#include "eventlistener.h" +#include "gamesystem.h" #include "vendor/nlohmann/json_fwd.hpp" using ordered_json = nlohmann::ordered_json; @@ -59,7 +59,7 @@ struct ZRModelEntry } }; -//everything that human and zombie share +// everything that human and zombie share struct ZRClass { int iTeam; @@ -80,14 +80,14 @@ struct ZRClass flSpeed(pClass->flSpeed), flGravity(pClass->flGravity), iAdminFlag(pClass->iAdminFlag) + { + vecModels.Purge(); + FOR_EACH_VEC(pClass->vecModels, i) { - vecModels.Purge(); - FOR_EACH_VEC(pClass->vecModels, i) - { - std::shared_ptr modelEntry = std::make_shared(pClass->vecModels[i]); - vecModels.AddToTail(modelEntry); - } - }; + std::shared_ptr modelEntry = std::make_shared(pClass->vecModels[i]); + vecModels.AddToTail(modelEntry); + } + }; ZRClass(ordered_json jsonKeys, std::string szClassname, int iTeam); void PrintInfo() @@ -125,7 +125,7 @@ struct ZRClass iAdminFlag); }; void Override(ordered_json jsonKeys, std::string szClassname); - bool IsApplicableTo(CCSPlayerController *pController); + bool IsApplicableTo(CCSPlayerController* pController); uint64 ParseClassFlags(const char* pszFlags); std::shared_ptr GetRandomModelEntry() { @@ -133,10 +133,10 @@ struct ZRClass }; }; - struct ZRHumanClass : ZRClass { - ZRHumanClass(std::shared_ptr pClass) : ZRClass(pClass, CS_TEAM_CT) {}; + ZRHumanClass(std::shared_ptr pClass) : + ZRClass(pClass, CS_TEAM_CT){}; ZRHumanClass(ordered_json jsonKeys, std::string szClassname); }; @@ -146,7 +146,7 @@ struct ZRZombieClass : ZRClass float flHealthRegenInterval; float flKnockback; ZRZombieClass(std::shared_ptr pClass) : - ZRClass(pClass, CS_TEAM_T), + ZRClass(pClass, CS_TEAM_T), iHealthRegenCount(pClass->iHealthRegenCount), flHealthRegenInterval(pClass->flHealthRegenInterval), flKnockback(pClass->flKnockback){}; @@ -206,13 +206,14 @@ class CZRPlayerClassManager void ApplyBaseClassVisuals(std::shared_ptr pClass, CCSPlayerPawn* pPawn); std::shared_ptr GetHumanClass(const char* pszClassName); void ApplyHumanClass(std::shared_ptr pClass, CCSPlayerPawn* pPawn); - void ApplyPreferredOrDefaultHumanClass(CCSPlayerPawn *pPawn); - void ApplyPreferredOrDefaultHumanClassVisuals(CCSPlayerPawn *pPawn); + void ApplyPreferredOrDefaultHumanClass(CCSPlayerPawn* pPawn); + void ApplyPreferredOrDefaultHumanClassVisuals(CCSPlayerPawn* pPawn); std::shared_ptr GetZombieClass(const char* pszClassName); void ApplyZombieClass(std::shared_ptr pClass, CCSPlayerPawn* pPawn); - void ApplyPreferredOrDefaultZombieClass(CCSPlayerPawn *pPawn); + void ApplyPreferredOrDefaultZombieClass(CCSPlayerPawn* pPawn); void PrecacheModels(IEntityResourceManifest* pResourceManifest); void GetZRClassList(int iTeam, CUtlVector>& vecClasses, CCSPlayerController* pController = nullptr); + private: void ApplyBaseClass(std::shared_ptr pClass, CCSPlayerPawn* pPawn); CUtlVector> m_vecZombieDefaultClass; @@ -225,18 +226,18 @@ class CZRRegenTimer : public CTimerBase { public: CZRRegenTimer(float flRegenInterval, int iRegenAmount, CHandle hPawnHandle) : - CTimerBase(flRegenInterval, false, false), m_iRegenAmount(iRegenAmount), m_hPawnHandle(hPawnHandle) {}; + CTimerBase(flRegenInterval, false, false), m_iRegenAmount(iRegenAmount), m_hPawnHandle(hPawnHandle){}; bool Execute(); - static void StartRegen(float flRegenInterval, int iRegenAmount, CCSPlayerController *pController); - static void StopRegen(CCSPlayerController *pController); + static void StartRegen(float flRegenInterval, int iRegenAmount, CCSPlayerController* pController); + static void StopRegen(CCSPlayerController* pController); static int GetIndex(CPlayerSlot slot); static void Tick(); static void RemoveAllTimers(); private: static double s_flNextExecution; - static CZRRegenTimer *s_vecRegenTimers[MAXPLAYERS]; + static CZRRegenTimer* s_vecRegenTimers[MAXPLAYERS]; int m_iRegenAmount; CHandle m_hPawnHandle; }; @@ -259,12 +260,12 @@ class ZRWeaponConfig m_WeaponMap.SetLessFunc(DefLessFunc(uint32)); }; void LoadWeaponConfig(); - std::shared_ptr FindWeapon(const char *pszWeaponName); + std::shared_ptr FindWeapon(const char* pszWeaponName); + private: CUtlMap> m_WeaponMap; }; - class ZRHitgroupConfig { public: @@ -274,12 +275,13 @@ class ZRHitgroupConfig }; void LoadHitgroupConfig(); std::shared_ptr FindHitgroupIndex(int iIndex); + private: CUtlMap> m_HitgroupMap; }; -extern ZRWeaponConfig *g_pZRWeaponConfig; -extern ZRHitgroupConfig *g_pZRHitgroupConfig; +extern ZRWeaponConfig* g_pZRWeaponConfig; +extern ZRHitgroupConfig* g_pZRHitgroupConfig; extern CZRPlayerClassManager* g_pZRPlayerClassManager; extern bool g_bEnableZR; @@ -293,9 +295,9 @@ void ZR_OnPlayerHurt(IGameEvent* pEvent); void ZR_OnPlayerDeath(IGameEvent* pEvent); void ZR_OnRoundFreezeEnd(IGameEvent* pEvent); void ZR_OnRoundTimeWarning(IGameEvent* pEvent); -bool ZR_Hook_OnTakeDamage_Alive(CTakeDamageInfo *pInfo, CCSPlayerPawn *pVictimPawn); -bool ZR_Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices *pWeaponServices, CBasePlayerWeapon* pPlayerWeapon); +bool ZR_Hook_OnTakeDamage_Alive(CTakeDamageInfo* pInfo, CCSPlayerPawn* pVictimPawn); +bool ZR_Detour_CCSPlayer_WeaponServices_CanUse(CCSPlayer_WeaponServices* pWeaponServices, CBasePlayerWeapon* pPlayerWeapon); void ZR_Detour_CEntityIdentity_AcceptInput(CEntityIdentity* pThis, CUtlSymbolLarge* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID); -void ZR_Hook_ClientPutInServer(CPlayerSlot slot, char const *pszName, int type, uint64 xuid); -void ZR_Hook_ClientCommand_JoinTeam(CPlayerSlot slot, const CCommand &args); +void ZR_Hook_ClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid); +void ZR_Hook_ClientCommand_JoinTeam(CPlayerSlot slot, const CCommand& args); void ZR_Precache(IEntityResourceManifest* pResourceManifest); \ No newline at end of file