chore: cleanup cpp & add clang format linting (#862)

This commit is contained in:
Michael Wilson
2025-05-12 15:46:13 +10:00
committed by GitHub
parent f50fb783bb
commit 6511a0098a
54 changed files with 2621 additions and 2486 deletions

View File

@@ -38,7 +38,7 @@ BraceWrapping:
SplitEmptyNamespace: true
PointerAlignment: Left
SortIncludes: CaseSensitive
SortIncludes: Never
IncludeBlocks: Regroup
IncludeCategories:
# External headers in <> with extension or /

View File

@@ -1,11 +1,18 @@
{
"name": "SteamRT Sniper SDK",
"image": "registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest",
"updateContentCommand": "git submodule update --init --recursive",
"customizations": {
"vscode": {
"extensions": [
"ms-vscode.cpptools"
"ms-vscode.cpptools",
"ms-vscode.cpptools-extension-pack",
"GitHub.copilot",
"jeff-hykin.better-cpp-syntax"
]
}
},
"features": {
"ghcr.io/devcontainers/features/dotnet": "8.0"
}
}

25
.github/workflows/lint-code.yaml vendored Normal file
View File

@@ -0,0 +1,25 @@
name: Code format checks
on:
pull_request:
paths:
- '.github/workflows/**'
- 'src/**'
- '.clang-format'
push:
paths:
- '.github/workflows/**'
- 'src/**'
- '.clang-format'
jobs:
lint:
name: Lint code with clang-format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jidicula/clang-format-action@4726374d1aa3c6aecf132e5197e498979588ebc8
with:
clang-format-version: '20'
check-path: 'src'
exclude-regex: '(sdk|\.proto)'

View File

@@ -28,8 +28,7 @@ class CGameResourceService
public:
CGameEntitySystem* GetGameEntitySystem()
{
return *reinterpret_cast<CGameEntitySystem**>(
(uintptr_t)(this) +
return *reinterpret_cast<CGameEntitySystem**>((uintptr_t)(this) +
counterstrikesharp::globals::gameConfig->GetOffset("GameEntitySystem"));
}
};

View File

@@ -26,11 +26,10 @@
#include "tier0/memdbgon.h"
namespace counterstrikesharp {
void interfaces::Initialize() {
pGameResourceServiceServer = (CGameResourceService*)modules::engine->FindInterface(
GAMERESOURCESERVICESERVER_INTERFACE_VERSION);
void interfaces::Initialize()
{
pGameResourceServiceServer = (CGameResourceService*)modules::engine->FindInterface(GAMERESOURCESERVICESERVER_INTERFACE_VERSION);
g_pCVar = (ICvar*)modules::tier0->FindInterface(CVAR_INTERFACE_VERSION);
g_pSource2GameEntities = (ISource2GameEntities*)modules::server->FindInterface(
SOURCE2GAMEENTITIES_INTERFACE_VERSION);
g_pSource2GameEntities = (ISource2GameEntities*)modules::server->FindInterface(SOURCE2GAMEENTITIES_INTERFACE_VERSION);
}
} // namespace counterstrikesharp

View File

@@ -33,8 +33,10 @@
using SchemaKeyValueMap_t = CUtlMap<uint32_t, SchemaKey>;
using SchemaTableMap_t = CUtlMap<uint32_t, SchemaKeyValueMap_t*>;
bool IsFieldNetworked(SchemaClassFieldData_t& field) {
for (int i = 0; i < field.m_nStaticMetadataCount; i++) {
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;
}
@@ -42,16 +44,16 @@ bool IsFieldNetworked(SchemaClassFieldData_t& field) {
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 = counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
if (!pType) return false;
SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get();
if (!pClassInfo) {
if (!pClassInfo)
{
SchemaKeyValueMap_t* map = new SchemaKeyValueMap_t(0, 0, DefLessFunc(uint32_t));
tableMap->Insert(classKey, map);
@@ -66,31 +68,34 @@ static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap,
keyValueMap->EnsureCapacity(fieldsSize);
tableMap->Insert(classKey, keyValueMap);
for (int i = 0; i < fieldsSize; ++i) {
for (int i = 0; i < fieldsSize; ++i)
{
SchemaClassFieldData_t& field = pFields[i];
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;
}
int16_t schema::FindChainOffset(const char* className) {
CSchemaSystemTypeScope* pType =
counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
int16_t schema::FindChainOffset(const char* className)
{
CSchemaSystemTypeScope* pType = counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
if (!pType) return false;
auto* pClassInfo = pType->FindDeclaredClass(className).Get();
do {
do
{
SchemaClassFieldData_t* pFields = pClassInfo->m_pFields;
short fieldsSize = pClassInfo->m_nFieldCount;
for (int i = 0; i < fieldsSize; ++i) {
for (int i = 0; i < fieldsSize; ++i)
{
SchemaClassFieldData_t& field = pFields[i];
if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0) {
if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0)
{
return field.m_nSingleInheritanceOffset;
}
}
@@ -99,29 +104,29 @@ int16_t schema::FindChainOffset(const char* className) {
return 0;
}
SchemaKey schema::GetOffset(const char* className,
uint32_t classKey,
const char* memberName,
uint32_t memberKey) {
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 };
}
SchemaKeyValueMap_t* tableMap = schemaTableMap[tableMapIndex];
int16_t memberIndex = tableMap->Find(memberKey);
if (!tableMap->IsValidIndex(memberIndex)) {
if (!tableMap->IsValidIndex(memberIndex))
{
return { 0, 0 };
}
return tableMap->Element(memberIndex);
}
void SetStateChanged(Z_CBaseEntity* pEntity, int offset) {
void SetStateChanged(Z_CBaseEntity* pEntity, int offset)
{
// addresses::StateChanged(pEntity->m_NetworkTransmitComponent(), pEntity, offset, -1, -1);
auto vars = counterstrikesharp::globals::getGlobalVars();

View File

@@ -30,7 +30,8 @@
#undef schema
struct SchemaKey {
struct SchemaKey
{
int32_t offset;
bool networked;
};
@@ -43,16 +44,14 @@ inline uint32_t prime_32_const = 0x1000193;
inline uint64_t val_64_const = 0xcbf29ce484222325;
inline uint64_t prime_64_const = 0x100000001b3;
inline uint32_t hash_32_fnv1a_const(const char *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 uint32_t hash_32_fnv1a_const(const char* 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 uint64_t hash_64_fnv1a_const(const char *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);
inline uint64_t hash_64_fnv1a_const(const char* 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);
}
namespace schema {

View File

@@ -52,7 +52,8 @@ std::map<dyno::Hook*, ValveFunction*> g_HookMap;
// ============================================================================
int GetDynCallConvention(Convention_t eConv)
{
switch (eConv) {
switch (eConv)
{
case CONV_CUSTOM:
return -1;
case CONV_CDECL:
@@ -74,8 +75,7 @@ int GetDynCallConvention(Convention_t eConv)
return -1;
}
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention,
std::vector<DataType_t> args, DataType_t returnType)
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, std::vector<DataType_t> args, DataType_t returnType)
: m_ulAddr(ulAddr)
{
m_Args = args;
@@ -87,8 +87,7 @@ ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention,
m_iCallingConvention = GetDynCallConvention(m_eCallingConvention);
}
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args,
int argCount, DataType_t returnType)
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args, int argCount, DataType_t returnType)
: m_ulAddr(ulAddr)
{
@@ -101,13 +100,9 @@ ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataT
ValveFunction::~ValveFunction() {}
bool ValveFunction::IsCallable()
{
return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1);
}
bool ValveFunction::IsCallable() { return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1); }
template <class ReturnType, class Function>
ReturnType CallHelper(Function func, DCCallVM* vm, void* addr)
template <class ReturnType, class Function> ReturnType CallHelper(Function func, DCCallVM* vm, void* addr)
{
ReturnType result;
result = (ReturnType)func(vm, (void*)addr);
@@ -118,15 +113,16 @@ void CallHelperVoid(DCCallVM* vm, void* addr) { dcCallVoid(vm, (void*)addr); }
void ValveFunction::Call(ScriptContext& script_context, int offset)
{
if (!IsCallable())
return;
if (!IsCallable()) return;
dcReset(g_pCallVM);
dcMode(g_pCallVM, m_iCallingConvention);
for (size_t i = 0; i < m_Args.size(); i++) {
for (size_t i = 0; i < m_Args.size(); i++)
{
int contextIndex = i + offset;
switch (m_Args[i]) {
switch (m_Args[i])
{
case DATA_TYPE_BOOL:
dcArgBool(g_pCallVM, script_context.GetArgument<bool>(contextIndex));
break;
@@ -178,7 +174,8 @@ void ValveFunction::Call(ScriptContext& script_context, int offset)
}
}
switch (m_eReturnType) {
switch (m_eReturnType)
{
case DATA_TYPE_VOID:
CallHelperVoid(g_pCallVM, m_ulAddr);
break;
@@ -213,8 +210,7 @@ void ValveFunction::Call(ScriptContext& script_context, int offset)
script_context.SetResult(CallHelper<long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_ULONG_LONG:
script_context.SetResult(
CallHelper<unsigned long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
script_context.SetResult(CallHelper<unsigned long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_FLOAT:
script_context.SetResult(CallHelper<float>(dcCallFloat, g_pCallVM, m_ulAddr));
@@ -240,23 +236,24 @@ dyno::ReturnAction HookHandler(dyno::HookType hookType, dyno::Hook& hook)
auto callback = hookType == dyno::HookType::Pre ? vf->m_precallback : vf->m_postcallback;
if (callback == nullptr) {
if (callback == nullptr)
{
return dyno::ReturnAction::Ignored;
}
callback->Reset();
callback->ScriptContext().Push(&hook);
for (auto fnMethodToCall : callback->GetFunctions()) {
if (!fnMethodToCall)
continue;
for (auto fnMethodToCall : callback->GetFunctions())
{
if (!fnMethodToCall) continue;
fnMethodToCall(&callback->ScriptContextStruct());
auto result = callback->ScriptContext().GetResult<HookResult>();
CSSHARP_CORE_TRACE("Received hook callback result of {}, hook mode {}", result,
(int)hookType);
CSSHARP_CORE_TRACE("Received hook callback result of {}, hook mode {}", result, (int)hookType);
if (result >= HookResult::Handled) {
if (result >= HookResult::Handled)
{
return dyno::ReturnAction::Supercede;
}
}
@@ -269,7 +266,8 @@ std::vector<dyno::DataObject> ConvertArgsToDynoHook(const std::vector<DataType_t
std::vector<dyno::DataObject> converted;
converted.reserve(dataTypes.size());
for (DataType_t dt : dataTypes) {
for (DataType_t dt : dataTypes)
{
converted.push_back(dyno::DataObject(static_cast<dyno::DataType>(dt)));
}
@@ -290,19 +288,25 @@ void ValveFunction::AddHook(CallbackT callable, bool post)
hook->addCallback(dyno::HookType::Post, (dyno::HookHandler*)&HookHandler);
hook->addCallback(dyno::HookType::Pre, (dyno::HookHandler*)&HookHandler);
if (post) {
if (m_postcallback == nullptr) {
if (post)
{
if (m_postcallback == nullptr)
{
m_postcallback = globals::callbackManager.CreateCallback("");
}
m_postcallback->AddListener(callable);
} else {
if (m_precallback == nullptr) {
}
else
{
if (m_precallback == nullptr)
{
m_precallback = globals::callbackManager.CreateCallback("");
}
m_precallback->AddListener(callable);
}
}
void ValveFunction::RemoveHook(CallbackT callable, bool post) {
void ValveFunction::RemoveHook(CallbackT callable, bool post)
{
dyno::HookManager& manager = dyno::HookManager::Get();
dyno::Hook* hook = manager.hook((void*)m_ulAddr, [this] {
#ifdef _WIN32
@@ -313,12 +317,17 @@ void ValveFunction::RemoveHook(CallbackT callable, bool post) {
});
g_HookMap[hook] = this;
if (post) {
if (m_postcallback != nullptr) {
if (post)
{
if (m_postcallback != nullptr)
{
m_postcallback->RemoveListener(callable);
}
} else {
if (m_precallback != nullptr) {
}
else
{
if (m_precallback != nullptr)
{
m_precallback->RemoveListener(callable);
}
}

View File

@@ -40,7 +40,8 @@ class Hook;
namespace counterstrikesharp {
enum DataType_t {
enum DataType_t
{
DATA_TYPE_VOID,
DATA_TYPE_BOOL,
DATA_TYPE_CHAR,
@@ -60,7 +61,8 @@ enum DataType_t {
DATA_TYPE_VARIANT
};
enum Protection_t {
enum Protection_t
{
PROTECTION_NONE,
PROTECTION_READ,
PROTECTION_READ_WRITE,
@@ -69,19 +71,20 @@ enum Protection_t {
PROTECTION_EXECUTE_READ_WRITE
};
enum Convention_t { CONV_CUSTOM, CONV_CDECL, CONV_THISCALL, CONV_STDCALL, CONV_FASTCALL };
enum Convention_t
{
CONV_CUSTOM,
CONV_CDECL,
CONV_THISCALL,
CONV_STDCALL,
CONV_FASTCALL
};
class ValveFunction {
class ValveFunction
{
public:
ValveFunction(void* ulAddr,
Convention_t callingConvention,
std::vector<DataType_t> args,
DataType_t returnType);
ValveFunction(void* ulAddr,
Convention_t callingConvention,
DataType_t* args,
int argCount,
DataType_t returnType);
ValveFunction(void* ulAddr, Convention_t callingConvention, std::vector<DataType_t> args, DataType_t returnType);
ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args, int argCount, DataType_t returnType);
~ValveFunction();

View File

@@ -36,7 +36,8 @@ bool InitGameSystems()
// bytes so we skip those
uint8* ptr = (uint8*)counterstrikesharp::globals::gameConfig->ResolveSignature("IGameSystem_InitAllSystems_pFirst") + 3;
if (!ptr) {
if (!ptr)
{
CSSHARP_CORE_ERROR("Failed to InitGameSystems, see warnings above.");
return false;
}

View File

@@ -37,8 +37,7 @@ class CGameSystem : public CBaseGameSystem
void SetGameSystemGlobalPtrs(void* pValue) override
{
if (sm_Factory)
sm_Factory->SetGlobalPtr(pValue);
if (sm_Factory) sm_Factory->SetGlobalPtr(pValue);
}
bool DoesGameSystemReallocate() override { return sm_Factory->ShouldAutoAdd(); }

View File

@@ -1,6 +1,5 @@
#pragma once
#include "core/globals.h"
#include "core/memory_module.h"
#include <KeyValues.h>

View File

@@ -32,11 +32,13 @@
#pragma once
namespace counterstrikesharp {
class GlobalClass {
class GlobalClass
{
public:
virtual ~GlobalClass() = default;
GlobalClass() {
GlobalClass()
{
m_pGlobalClassNext = GlobalClass::head;
GlobalClass::head = this;
}
@@ -59,7 +61,8 @@ public:
#define CALL_GLOBAL_LISTENER(func) \
GlobalClass* pBase = GlobalClass::head; \
pBase = GlobalClass::head; \
while (pBase) { \
while (pBase) \
{ \
pBase->func; \
pBase = pBase->m_pGlobalClassNext; \
}

View File

@@ -1,4 +1,3 @@
// clang-format off
#include "mm_plugin.h"
#include "core/globals.h"
#include "core/managers/player_manager.h"
@@ -28,7 +27,6 @@
#include <public/entity2/entitysystem.h>
#include <funchook.h>
// clang-format on
namespace counterstrikesharp {
@@ -142,7 +140,8 @@ void DetourGameEventManagerInit(IGameEventManager2* pGameEventManager)
}
int source_hook_pluginid = 0;
CGlobalVars* getGlobalVars() {
CGlobalVars* getGlobalVars()
{
INetworkGameServer* server = networkServerService->GetIGameServer();
if (!server) return nullptr;
return networkServerService->GetIGameServer()->GetGlobals();

View File

@@ -7,7 +7,8 @@
namespace counterstrikesharp {
std::shared_ptr<spdlog::logger> Log::m_core_logger;
void Log::Init() {
void Log::Init()
{
std::vector<spdlog::sink_ptr> log_sinks;
auto color_sink = std::make_shared<spdlog::sinks::stderr_color_sink_mt>();
#if _WIN32
@@ -17,8 +18,7 @@ void Log::Init() {
#endif
log_sinks.emplace_back(color_sink);
log_sinks.emplace_back(
std::make_shared<spdlog::sinks::basic_file_sink_mt>("counterstrikesharp.log", true));
log_sinks.emplace_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("counterstrikesharp.log", true));
log_sinks[0]->set_pattern("%^[%T.%e] %n: %v%$");
log_sinks[1]->set_pattern("[%T.%e] [%l] %n: %v");
@@ -31,7 +31,8 @@ void Log::Init() {
spdlog::cfg::load_env_levels();
}
void Log::Close() {
void Log::Close()
{
spdlog::drop("CSSharp");
m_core_logger = nullptr;
}

View File

@@ -6,7 +6,8 @@
#include <spdlog/spdlog.h>
namespace counterstrikesharp {
class Log {
class Log
{
public:
static void Init();
static void Close();

View File

@@ -25,18 +25,28 @@
#include <public/eiface.h>
#include "scripting/callback_manager.h"
SH_DECL_HOOK7_void(ISource2GameEntities, CheckTransmit, SH_NOATTRIB, 0, CCheckTransmitInfo**, int, CBitVec<16384>&, const Entity2Networkable_t**, const uint16*, int, bool);
SH_DECL_HOOK7_void(ISource2GameEntities,
CheckTransmit,
SH_NOATTRIB,
0,
CCheckTransmitInfo**,
int,
CBitVec<16384>&,
const Entity2Networkable_t**,
const uint16*,
int,
bool);
namespace counterstrikesharp {
EntityManager::EntityManager()
{
m_profile_name = "EntityManager";
}
EntityManager::EntityManager() { m_profile_name = "EntityManager"; }
EntityManager::~EntityManager() {}
CCheckTransmitInfoList::CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount) : infoList(pInfoInfoList), infoCount(nInfoCount) {}
CCheckTransmitInfoList::CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount)
: infoList(pInfoInfoList), infoCount(nInfoCount)
{
}
void EntityManager::OnAllInitialized()
{
@@ -46,13 +56,13 @@ void EntityManager::OnAllInitialized()
on_entity_spawned_callback = globals::callbackManager.CreateCallback("OnEntitySpawned");
on_entity_created_callback = globals::callbackManager.CreateCallback("OnEntityCreated");
on_entity_deleted_callback = globals::callbackManager.CreateCallback("OnEntityDeleted");
on_entity_parent_changed_callback =
globals::callbackManager.CreateCallback("OnEntityParentChanged");
on_entity_parent_changed_callback = globals::callbackManager.CreateCallback("OnEntityParentChanged");
m_pFireOutputInternal = reinterpret_cast<FireOutputInternal>(modules::server->FindSignature(
globals::gameConfig->GetSignature("CEntityIOOutput_FireOutputInternal")));
m_pFireOutputInternal = reinterpret_cast<FireOutputInternal>(
modules::server->FindSignature(globals::gameConfig->GetSignature("CEntityIOOutput_FireOutputInternal")));
if (m_pFireOutputInternal == nullptr) {
if (m_pFireOutputInternal == nullptr)
{
CSSHARP_CORE_CRITICAL("Failed to find signature for \'CEntityIOOutput_FireOutputInternal\'");
return;
}
@@ -104,7 +114,8 @@ void CEntityListener::OnEntitySpawned(CEntityInstance* pEntity)
{
auto callback = globals::entityManager.on_entity_spawned_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->Execute();
@@ -114,7 +125,8 @@ void CEntityListener::OnEntityCreated(CEntityInstance* pEntity)
{
auto callback = globals::entityManager.on_entity_created_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->Execute();
@@ -124,7 +136,8 @@ void CEntityListener::OnEntityDeleted(CEntityInstance* pEntity)
{
auto callback = globals::entityManager.on_entity_deleted_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->Execute();
@@ -134,7 +147,8 @@ void CEntityListener::OnEntityParentChanged(CEntityInstance* pEntity, CEntityIns
{
auto callback = globals::entityManager.on_entity_parent_changed_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->ScriptContext().Push(pNewParent);
@@ -142,49 +156,58 @@ void CEntityListener::OnEntityParentChanged(CEntityInstance* pEntity, CEntityIns
}
}
void EntityManager::HookEntityOutput(const char* szClassname, const char* szOutput,
CallbackT fnCallback, HookMode mode)
void EntityManager::HookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode)
{
auto outputKey = OutputKey_t(szClassname, szOutput);
CallbackPair* pCallbackPair;
auto search = m_pHookMap.find(outputKey);
if (search == m_pHookMap.end()) {
if (search == m_pHookMap.end())
{
m_pHookMap[outputKey] = new CallbackPair();
pCallbackPair = m_pHookMap[outputKey];
} else
}
else
pCallbackPair = search->second;
auto* pCallback = mode == HookMode::Pre ? pCallbackPair->pre : pCallbackPair->post;
pCallback->AddListener(fnCallback);
}
void EntityManager::UnhookEntityOutput(const char* szClassname, const char* szOutput,
CallbackT fnCallback, HookMode mode)
void EntityManager::UnhookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode)
{
auto outputKey = OutputKey_t(szClassname, szOutput);
auto search = m_pHookMap.find(outputKey);
if (search != m_pHookMap.end()) {
if (search != m_pHookMap.end())
{
auto* pCallbackPair = search->second;
auto* pCallback = mode == Pre ? pCallbackPair->pre : pCallbackPair->post;
pCallback->RemoveListener(fnCallback);
if (!pCallbackPair->HasCallbacks()) {
if (!pCallbackPair->HasCallbacks())
{
m_pHookMap.erase(outputKey);
}
}
}
void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoCount, CBitVec<16384>& unionTransmitEdicts, const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntityIndices, bool bEnablePVSBits)
void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList,
int nInfoCount,
CBitVec<16384>& unionTransmitEdicts,
const Entity2Networkable_t** pNetworkables,
const uint16* pEntityIndicies,
int nEntityIndices,
bool bEnablePVSBits)
{
VPROF_BUDGET(m_profile_name.c_str(), "CS# CheckTransmit");
auto callback = globals::entityManager.check_transmit;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
CCheckTransmitInfoList* infoList = new CCheckTransmitInfoList(pInfoInfoList, nInfoCount);
callback->ScriptContext().Reset();
@@ -195,39 +218,43 @@ void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoC
}
}
void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pActivator,
CEntityInstance* pCaller, const CVariant* const value, float flDelay)
void DetourFireOutputInternal(
CEntityIOOutput* const pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* const value, float flDelay)
{
std::vector vecSearchKeys{OutputKey_t("*", pThis->m_pDesc->m_pName),
OutputKey_t("*", "*")};
std::vector vecSearchKeys{ OutputKey_t("*", pThis->m_pDesc->m_pName), OutputKey_t("*", "*") };
if (pCaller) {
if (pCaller)
{
vecSearchKeys.push_back(OutputKey_t(pCaller->GetClassname(), pThis->m_pDesc->m_pName));
OutputKey_t(pCaller->GetClassname(), "*");
}
std::vector<CallbackPair*> vecCallbackPairs;
if (pCaller) {
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, {}", pThis->m_pDesc->m_pName,
pCaller->GetClassname());
if (pCaller)
{
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, {}", pThis->m_pDesc->m_pName, pCaller->GetClassname());
auto& hookMap = globals::entityManager.m_pHookMap;
for (auto& searchKey : vecSearchKeys) {
for (auto& searchKey : vecSearchKeys)
{
auto search = hookMap.find(searchKey);
if (search != hookMap.end()) {
if (search != hookMap.end())
{
vecCallbackPairs.push_back(search->second);
}
}
} else
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, unknown caller",
pThis->m_pDesc->m_pName);
}
else
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, unknown caller", pThis->m_pDesc->m_pName);
HookResult result = HookResult::Continue;
for (auto pCallbackPair : vecCallbackPairs) {
if (pCallbackPair->pre->GetFunctionCount()) {
for (auto pCallbackPair : vecCallbackPairs)
{
if (pCallbackPair->pre->GetFunctionCount())
{
pCallbackPair->pre->ScriptContext().Reset();
pCallbackPair->pre->ScriptContext().Push(pThis);
pCallbackPair->pre->ScriptContext().Push(pThis->m_pDesc->m_pName);
@@ -236,32 +263,37 @@ void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pAc
pCallbackPair->pre->ScriptContext().Push(value);
pCallbackPair->pre->ScriptContext().Push(flDelay);
for (auto fnMethodToCall : pCallbackPair->pre->GetFunctions()) {
if (!fnMethodToCall)
continue;
for (auto fnMethodToCall : pCallbackPair->pre->GetFunctions())
{
if (!fnMethodToCall) continue;
fnMethodToCall(&pCallbackPair->pre->ScriptContextStruct());
auto thisResult = pCallbackPair->pre->ScriptContext().GetResult<HookResult>();
if (thisResult >= HookResult::Stop) {
if (thisResult >= HookResult::Stop)
{
return;
}
if (thisResult > result) {
if (thisResult > result)
{
result = thisResult;
}
}
}
}
if (result >= HookResult::Handled) {
if (result >= HookResult::Handled)
{
return;
}
m_pFireOutputInternal(pThis, pActivator, pCaller, value, flDelay);
for (auto pCallbackPair : vecCallbackPairs) {
if (pCallbackPair->post->GetFunctionCount()) {
for (auto pCallbackPair : vecCallbackPairs)
{
if (pCallbackPair->post->GetFunctionCount())
{
pCallbackPair->post->ScriptContext().Reset();
pCallbackPair->post->ScriptContext().Push(pThis);
pCallbackPair->post->ScriptContext().Push(pThis->m_pDesc->m_pName);
@@ -276,8 +308,10 @@ void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pAc
SndOpEventGuid_t EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume, float flPitch)
{
if (!CBaseEntity_EmitSoundFilter) {
CSSHARP_CORE_ERROR("[EntityManager][EmitSoundFilter] - Failed to emit a sound. Signature for \'CBaseEntity_EmitSoundFilter\' is not found. The latest update may have broken it.");
if (!CBaseEntity_EmitSoundFilter)
{
CSSHARP_CORE_ERROR("[EntityManager][EmitSoundFilter] - Failed to emit a sound. Signature for \'CBaseEntity_EmitSoundFilter\' is "
"not found. The latest update may have broken it.");
return SndOpEventGuid_t{};
}

View File

@@ -34,23 +34,28 @@ class ScriptCallback;
typedef std::pair<std::string, std::string> OutputKey_t;
class CEntityListener : public IEntityListener {
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;
};
class CCheckTransmitInfoList {
class CCheckTransmitInfoList
{
public:
CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount);
private:
CCheckTransmitInfo** infoList;
int infoCount;
};
class EntityManager : public GlobalClass {
class EntityManager : public GlobalClass
{
friend CEntityListener;
public:
EntityManager();
~EntityManager();
@@ -60,8 +65,15 @@ public:
void UnhookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode);
CEntityListener entityListener;
std::map<OutputKey_t, CallbackPair*> m_pHookMap;
private:
void CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoCount, CBitVec<16384>& unionTransmitEdicts, const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntityIndices, bool bEnablePVSBits);
void CheckTransmit(CCheckTransmitInfo** pInfoInfoList,
int nInfoCount,
CBitVec<16384>& unionTransmitEdicts,
const Entity2Networkable_t** pNetworkables,
const uint16* pEntityIndicies,
int nEntityIndices,
bool bEnablePVSBits);
ScriptCallback* on_entity_spawned_callback;
ScriptCallback* on_entity_created_callback;
@@ -72,7 +84,6 @@ private:
std::string m_profile_name;
};
enum EntityIOTargetType_t
{
ENTITY_IO_TARGET_INVALID = 0xFFFFFFFF,
@@ -118,16 +129,16 @@ class CEntityIOOutput
EntityIOOutputDesc_t* m_pDesc;
};
typedef void (*FireOutputInternal)(CEntityIOOutput* const, CEntityInstance*, CEntityInstance*,
const CVariant* const, float);
typedef void (*FireOutputInternal)(CEntityIOOutput* const, CEntityInstance*, CEntityInstance*, const CVariant* const, float);
static void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pActivator,
CEntityInstance* pCaller, const CVariant* const value, float flDelay);
static void DetourFireOutputInternal(
CEntityIOOutput* const pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* const value, float flDelay);
static FireOutputInternal m_pFireOutputInternal = nullptr;
// Do it in here because i didn't found a good place to do this
inline void (*CEntityInstance_AcceptInput)(CEntityInstance* pThis, const char* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID);
inline void (*CEntityInstance_AcceptInput)(
CEntityInstance* pThis, const char* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID);
inline void (*CEntitySystem_AddEntityIOEvent)(CEntitySystem* pEntitySystem,
CEntityInstance* pTarget,
@@ -167,23 +178,10 @@ enum gender_t : uint8
struct EmitSound_t
{
EmitSound_t() :
m_nChannel(0),
m_pSoundName(0),
m_flVolume(VOL_NORM),
m_SoundLevel(SNDLVL_NONE),
m_nFlags(0),
m_nPitch(PITCH_NORM),
m_pOrigin(0),
m_flSoundTime(0.0f),
m_pflSoundDuration(0),
m_bEmitCloseCaption(true),
m_bWarnOnMissingCloseCaption(false),
m_bWarnOnDirectWaveReference(false),
m_nSpeakerEntity(-1),
m_UtlVecSoundOrigin(),
m_nForceGuid(0),
m_SpeakerGender(GENDER_NONE)
EmitSound_t()
: m_nChannel(0), m_pSoundName(0), m_flVolume(VOL_NORM), m_SoundLevel(SNDLVL_NONE), m_nFlags(0), m_nPitch(PITCH_NORM), m_pOrigin(0),
m_flSoundTime(0.0f), m_pflSoundDuration(0), m_bEmitCloseCaption(true), m_bWarnOnMissingCloseCaption(false),
m_bWarnOnDirectWaveReference(false), m_nSpeakerEntity(-1), m_UtlVecSoundOrigin(), m_nForceGuid(0), m_SpeakerGender(GENDER_NONE)
{
}
int m_nChannel;
@@ -212,5 +210,6 @@ struct SndOpEventGuid_t
inline SndOpEventGuid_t(FASTCALL* CBaseEntity_EmitSoundFilter)(IRecipientFilter& filter, CEntityIndex ent, const EmitSound_t& params);
SndOpEventGuid_t EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume = 1.0f, float flPitch = 1.0f);
SndOpEventGuid_t
EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume = 1.0f, float flPitch = 1.0f);
} // namespace counterstrikesharp

View File

@@ -44,19 +44,15 @@
#include <iplayerinfo.h>
// extern CEntitySystem *g_pEntitySystem;
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, 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_HOOK1_void(IServerGameClients, ClientVoice, SH_NOATTRIB, 0, CPlayerSlot);
SH_DECL_HOOK4_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, CPlayerSlot, char const*,
int, uint64);
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_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_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, CPlayerSlot, const CCommand&);
@@ -66,48 +62,39 @@ void PlayerManager::OnStartup() {}
void PlayerManager::OnAllInitialized()
{
SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
SH_ADD_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
SH_ADD_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
SH_ADD_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientVoice), true);
SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
SH_ADD_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer),
true);
SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect),
false);
SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post),
true);
SH_ADD_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
SH_ADD_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientVoice), true);
m_on_client_connect_callback = globals::callbackManager.CreateCallback("OnClientConnect");
m_on_client_connected_callback = globals::callbackManager.CreateCallback("OnClientConnected");
m_on_client_put_in_server_callback =
globals::callbackManager.CreateCallback("OnClientPutInServer");
m_on_client_put_in_server_callback = globals::callbackManager.CreateCallback("OnClientPutInServer");
m_on_client_disconnect_callback = globals::callbackManager.CreateCallback("OnClientDisconnect");
m_on_client_disconnect_post_callback =
globals::callbackManager.CreateCallback("OnClientDisconnectPost");
m_on_client_disconnect_post_callback = globals::callbackManager.CreateCallback("OnClientDisconnectPost");
m_on_client_voice_callback = globals::callbackManager.CreateCallback("OnClientVoice");
m_on_client_authorized_callback = globals::callbackManager.CreateCallback("OnClientAuthorized");
}
void PlayerManager::OnShutdown()
{
SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post),
true);
SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer),
true);
SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect),
false);
SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
SH_REMOVE_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
SH_REMOVE_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients,
SH_MEMBER(this, &PlayerManager::OnClientVoice), true);
SH_REMOVE_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
SH_REMOVE_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientVoice), true);
globals::callbackManager.ReleaseCallback(m_on_client_connect_callback);
globals::callbackManager.ReleaseCallback(m_on_client_connected_callback);
@@ -118,21 +105,18 @@ void PlayerManager::OnShutdown()
globals::callbackManager.ReleaseCallback(m_on_client_voice_callback);
}
bool PlayerManager::OnClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid,
const char* pszNetworkID, bool unk1,
CBufferString* pRejectReason)
bool PlayerManager::OnClientConnect(
CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason)
{
CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect] - {}, {}, {}", slot.Get(), pszName,
pszNetworkID);
CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect] - {}, {}, {}", slot.Get(), pszName, pszNetworkID);
int client = slot.Get();
CPlayer* pPlayer = &m_players[client];
if (pPlayer->IsConnected()) {
OnClientDisconnect(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, pszName,
xuid, pszNetworkID);
OnClientDisconnect_Post(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID,
pszName, xuid, pszNetworkID);
if (pPlayer->IsConnected())
{
OnClientDisconnect(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, pszName, xuid, pszNetworkID);
OnClientDisconnect_Post(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, pszName, xuid, pszNetworkID);
}
pPlayer->Initialize(pszName, pszNetworkID, slot);
@@ -143,7 +127,8 @@ bool PlayerManager::OnClientConnect(CPlayerSlot slot, const char* pszName, uint6
m_on_client_connect_callback->ScriptContext().Push(pszNetworkID);
m_on_client_connect_callback->Execute();
if (m_on_client_connect_callback->GetFunctionCount() > 0) {
if (m_on_client_connect_callback->GetFunctionCount() > 0)
{
// auto cancel = m_on_client_connect_callback->ScriptContext().GetArgument<bool>(0);
// auto cancelReason =
// m_on_client_connect_callback->ScriptContext().GetArgument<const char *>(1);
@@ -167,47 +152,47 @@ bool PlayerManager::OnClientConnect(CPlayerSlot slot, const char* pszName, uint6
return true;
}
bool PlayerManager::OnClientConnect_Post(CPlayerSlot slot, const char* pszName, uint64 xuid,
const char* pszNetworkID, bool unk1,
CBufferString* pRejectReason)
bool PlayerManager::OnClientConnect_Post(
CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason)
{
CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect_Post] - {}, {}, {}", slot.Get(), pszName,
pszNetworkID);
CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect_Post] - {}, {}, {}", slot.Get(), pszName, pszNetworkID);
int client = slot.Get();
bool orig_value = META_RESULT_ORIG_RET(bool);
CPlayer* pPlayer = &m_players[client];
if (orig_value) {
if (orig_value)
{
m_on_client_connected_callback->ScriptContext().Reset();
m_on_client_connected_callback->ScriptContext().Push(pPlayer->m_slot.Get());
m_on_client_connected_callback->Execute();
if (!pPlayer->IsFakeClient() && m_is_listen_server &&
strncmp(pszNetworkID, "127.0.0.1", 9) == 0) {
if (!pPlayer->IsFakeClient() && m_is_listen_server && strncmp(pszNetworkID, "127.0.0.1", 9) == 0)
{
m_listen_client = client;
}
} else {
}
else
{
InvalidatePlayer(pPlayer);
}
return true;
}
void PlayerManager::OnClientPutInServer(CPlayerSlot slot, char const* pszName, int type,
uint64 xuid)
void PlayerManager::OnClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid)
{
CSSHARP_CORE_TRACE("[PlayerManager][OnClientPutInServer] - {}, {}, {}", slot.Get(), pszName,
type);
CSSHARP_CORE_TRACE("[PlayerManager][OnClientPutInServer] - {}, {}, {}", slot.Get(), pszName, type);
int client = slot.Get();
CPlayer* pPlayer = &m_players[client];
if (!pPlayer->IsConnected()) {
if (!pPlayer->IsConnected())
{
pPlayer->m_is_fake_client = true;
if (!OnClientConnect(slot, pszName, 0, "127.0.0.1", false,
new CBufferStringGrowable<255>())) {
if (!OnClientConnect(slot, pszName, 0, "127.0.0.1", false, new CBufferStringGrowable<255>()))
{
/* :TODO: kick the bot if it's rejected */
return;
}
@@ -233,39 +218,39 @@ void PlayerManager::OnClientPutInServer(CPlayerSlot slot, char const* pszName, i
m_on_client_put_in_server_callback->Execute();
}
void PlayerManager::OnClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason,
const char* pszName, uint64 xuid, const char* pszNetworkID)
void PlayerManager::OnClientDisconnect(
CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID)
{
CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect] - {}, {}, {}", slot.Get(), pszName,
pszNetworkID);
CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect] - {}, {}, {}", slot.Get(), pszName, pszNetworkID);
int client = slot.Get();
CPlayer* pPlayer = &m_players[client];
if (pPlayer->IsConnected()) {
if (pPlayer->IsConnected())
{
m_on_client_disconnect_callback->ScriptContext().Reset();
m_on_client_disconnect_callback->ScriptContext().Push(pPlayer->m_slot.Get());
m_on_client_disconnect_callback->ScriptContext().Push(reason);
m_on_client_disconnect_callback->Execute();
}
if (pPlayer->WasCountedAsInGame()) {
if (pPlayer->WasCountedAsInGame())
{
m_player_count--;
}
// globals::entityListener.HandleEntityDeleted(pPlayer->GetBaseEntity(), client);
}
void PlayerManager::OnClientDisconnect_Post(CPlayerSlot slot, ENetworkDisconnectionReason reason,
const char* pszName, uint64 xuid,
const char* pszNetworkID) const
void PlayerManager::OnClientDisconnect_Post(
CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID) const
{
CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect_Post] - {}, {}, {}", slot.Get(), pszName,
pszNetworkID);
CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect_Post] - {}, {}, {}", slot.Get(), pszName, pszNetworkID);
int client = slot.Get();
CPlayer* pPlayer = &m_players[client];
if (!pPlayer->IsConnected()) {
if (!pPlayer->IsConnected())
{
/* We don't care, prevent a double call */
return;
}
@@ -291,14 +276,14 @@ void PlayerManager::OnLevelEnd()
{
CSSHARP_CORE_TRACE("[PlayerManager][OnLevelEnd]");
for (int i = 0; i <= MaxClients(); i++) {
if (m_players[i].IsConnected()) {
OnClientDisconnect(m_players[i].m_slot,
ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID,
m_players[i].GetName(), 0, m_players[i].GetIpAddress());
OnClientDisconnect_Post(m_players[i].m_slot,
ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID,
m_players[i].GetName(), 0, m_players[i].GetIpAddress());
for (int i = 0; i <= MaxClients(); i++)
{
if (m_players[i].IsConnected())
{
OnClientDisconnect(m_players[i].m_slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, m_players[i].GetName(), 0,
m_players[i].GetIpAddress());
OnClientDisconnect_Post(m_players[i].m_slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, m_players[i].GetName(), 0,
m_players[i].GetIpAddress());
}
}
m_player_count = 0;
@@ -306,17 +291,17 @@ void PlayerManager::OnLevelEnd()
void PlayerManager::OnClientCommand(CPlayerSlot slot, const CCommand& args) const
{
CSSHARP_CORE_TRACE("[PlayerManager][OnClientCommand] - {}, {}, {}", slot.Get(), args.Arg(0),
(void*)&args);
CSSHARP_CORE_TRACE("[PlayerManager][OnClientCommand] - {}, {}, {}", slot.Get(), args.Arg(0), (void*)&args);
const char* cmd = args.Arg(0);
globals::voiceManager.OnClientCommand(slot, args);
auto result = globals::conCommandManager.ExecuteCommandCallbacks(
cmd, CCommandContext(CommandTarget_t::CT_NO_TARGET, slot), args, HookMode::Pre, CommandCallingContext::Console);
auto result = globals::conCommandManager.ExecuteCommandCallbacks(cmd, CCommandContext(CommandTarget_t::CT_NO_TARGET, slot), args,
HookMode::Pre, CommandCallingContext::Console);
if (result >= HookResult::Handled) {
if (result >= HookResult::Handled)
{
RETURN_META(MRES_SUPERCEDE);
}
}
@@ -329,7 +314,8 @@ int PlayerManager::MaxClients() const { return globals::getGlobalVars()->maxClie
CPlayer* PlayerManager::GetPlayerBySlot(int client) const
{
if (client > MaxClients() || client < 0) {
if (client > MaxClients() || client < 0)
{
return nullptr;
}
@@ -378,8 +364,7 @@ CPlayer* PlayerManager::GetPlayerBySlot(int client) const
void PlayerManager::InvalidatePlayer(CPlayer* pPlayer) const
{
auto userid = globals::engine->GetPlayerUserId(pPlayer->m_slot);
if (userid.Get() != -1)
m_user_id_lookup[userid.Get()] = 0;
if (userid.Get() != -1) m_user_id_lookup[userid.Get()] = 0;
pPlayer->Disconnect();
}
@@ -406,7 +391,8 @@ bool CPlayer::IsAuthorized() const { return m_is_authorized; }
bool CPlayer::IsAuthStringValidated() const
{
if (!IsFakeClient()) {
if (!IsFakeClient())
{
return globals::engine->IsClientFullyAuthenticated(m_slot);
}
return false;
@@ -416,12 +402,14 @@ void CPlayer::Authorize() { m_is_authorized = true; }
void CPlayer::PrintToConsole(const char* message) const
{
if (m_is_connected == false || m_is_fake_client == true) {
if (m_is_connected == false || m_is_fake_client == true)
{
return;
}
INetChannelInfo* pNetChan = globals::engine->GetPlayerNetInfo(m_slot);
if (pNetChan == nullptr) {
if (pNetChan == nullptr)
{
return;
}
@@ -457,18 +445,21 @@ PlayerManager::PlayerManager()
void PlayerManager::RunAuthChecks()
{
if (globals::timerSystem.GetTickedTime() - m_last_auth_check_time < 0.5F) {
if (globals::timerSystem.GetTickedTime() - m_last_auth_check_time < 0.5F)
{
return;
}
m_last_auth_check_time = globals::timerSystem.GetTickedTime();
for (int i = 0; i <= MaxClients(); i++) {
if (m_players[i].IsConnected()) {
if (m_players[i].IsAuthorized() || m_players[i].IsFakeClient())
continue;
for (int i = 0; i <= MaxClients(); i++)
{
if (m_players[i].IsConnected())
{
if (m_players[i].IsAuthorized() || m_players[i].IsFakeClient()) continue;
if (globals::engine->IsClientFullyAuthenticated(i)) {
if (globals::engine->IsClientFullyAuthenticated(i))
{
m_players[i].Authorize();
m_players[i].SetSteamId(globals::engine->GetClientSteamID(i));
OnAuthorized(&m_players[i]);
@@ -479,8 +470,7 @@ void PlayerManager::RunAuthChecks()
void PlayerManager::OnAuthorized(CPlayer* player) const
{
CSSHARP_CORE_TRACE("[PlayerManager][OnAuthorized] - {} {}", player->GetName(),
player->GetSteamId()->ConvertToUint64());
CSSHARP_CORE_TRACE("[PlayerManager][OnAuthorized] - {} {}", player->GetName(), player->GetSteamId()->ConvertToUint64());
m_on_client_authorized_callback->ScriptContext().Reset();
m_on_client_authorized_callback->ScriptContext().Push(player->m_slot.Get());
@@ -492,7 +482,8 @@ bool CPlayer::WasCountedAsInGame() const { return m_is_in_game; }
int CPlayer::GetUserId()
{
if (m_user_id == -1) {
if (m_user_id == -1)
{
m_user_id = globals::engine->GetPlayerUserId(m_slot).Get();
}
@@ -523,10 +514,7 @@ int CPlayer::GetFrags() const { return m_info->GetFragCount(); }
int CPlayer::GetDeaths() const { return m_info->GetDeathCount(); }
const char* CPlayer::GetKeyValue(const char* key) const
{
return globals::engine->GetClientConVarValue(m_slot, key);
}
const char* CPlayer::GetKeyValue(const char* key) const { return globals::engine->GetClientConVarValue(m_slot, key); }
Vector CPlayer::GetMaxSize() const { return m_info->GetPlayerMaxs(); }
@@ -542,17 +530,15 @@ int CPlayer::GetUserId() const { return m_user_id; }
float CPlayer::GetTimeConnected() const
{
if (!IsConnected() || IsFakeClient()) {
if (!IsConnected() || IsFakeClient())
{
return 0;
}
return GetNetInfo()->GetTimeConnected();
}
void CPlayer::SetListen(CPlayerSlot slot, ListenOverride listen)
{
m_listenMap[slot.Get()] = listen;
}
void CPlayer::SetListen(CPlayerSlot slot, ListenOverride listen) { m_listenMap[slot.Get()] = listen; }
void CPlayer::SetVoiceFlags(VoiceFlag_t flags) { m_voiceFlag = flags; }
@@ -562,7 +548,8 @@ ListenOverride CPlayer::GetListen(CPlayerSlot slot) const { return m_listenMap[s
void CPlayer::Connect()
{
if (m_is_in_game) {
if (m_is_in_game)
{
return;
}
@@ -590,7 +577,8 @@ Vector CPlayer::GetAbsOrigin() const { return m_info->GetAbsOrigin(); }
bool CPlayer::IsAlive() const
{
if (!IsInGame()) {
if (!IsInGame())
{
return false;
}

View File

@@ -143,15 +143,15 @@ class PlayerManager : public GlobalClass
PlayerManager();
void OnStartup() override;
void OnAllInitialized() override;
bool OnClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid,
const char* pszNetworkID, bool unk1, CBufferString* pRejectReason);
bool OnClientConnect_Post(CPlayerSlot slot, const char* pszName, uint64 xuid,
const char* pszNetworkID, bool unk1, CBufferString* pRejectReason);
bool
OnClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason);
bool OnClientConnect_Post(
CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason);
void OnClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid);
void OnClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason,
const char* pszName, uint64 xuid, const char* pszNetworkID);
void OnClientDisconnect_Post(CPlayerSlot slot, ENetworkDisconnectionReason reason,
const char* pszName, uint64 xuid, const char* pszNetworkID) const;
void
OnClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID);
void OnClientDisconnect_Post(
CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID) const;
void OnClientVoice(CPlayerSlot slot) const;
void OnAuthorized(CPlayer* player) const;
void OnServerActivate(edict_t* pEdictList, int edictCount, int clientMax) const;

View File

@@ -36,21 +36,17 @@ ServerManager::ServerManager() = default;
ServerManager::~ServerManager() = default;
void ServerManager::OnAllInitialized() {
SH_ADD_HOOK(ISource2Server, ServerHibernationUpdate, globals::server,
SH_MEMBER(this, &ServerManager::ServerHibernationUpdate), true);
SH_ADD_HOOK(ISource2Server, GameServerSteamAPIActivated, globals::server,
SH_MEMBER(this, &ServerManager::GameServerSteamAPIActivated), true);
void ServerManager::OnAllInitialized()
{
SH_ADD_HOOK(ISource2Server, ServerHibernationUpdate, globals::server, SH_MEMBER(this, &ServerManager::ServerHibernationUpdate), true);
SH_ADD_HOOK(ISource2Server, GameServerSteamAPIActivated, globals::server, SH_MEMBER(this, &ServerManager::GameServerSteamAPIActivated),
true);
SH_ADD_HOOK(ISource2Server, GameServerSteamAPIDeactivated, globals::server,
SH_MEMBER(this, &ServerManager::GameServerSteamAPIDeactivated), true);
SH_ADD_HOOK(ISource2Server, OnHostNameChanged, globals::server,
SH_MEMBER(this, &ServerManager::OnHostNameChanged), true);
SH_ADD_HOOK(ISource2Server, PreFatalShutdown, globals::server,
SH_MEMBER(this, &ServerManager::PreFatalShutdown), true);
SH_ADD_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server,
SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true);
SH_ADD_HOOK(ISource2Server, PreWorldUpdate, globals::server,
SH_MEMBER(this, &ServerManager::PreWorldUpdate), true);
SH_ADD_HOOK(ISource2Server, OnHostNameChanged, globals::server, SH_MEMBER(this, &ServerManager::OnHostNameChanged), true);
SH_ADD_HOOK(ISource2Server, PreFatalShutdown, globals::server, SH_MEMBER(this, &ServerManager::PreFatalShutdown), true);
SH_ADD_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server, SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true);
SH_ADD_HOOK(ISource2Server, PreWorldUpdate, globals::server, SH_MEMBER(this, &ServerManager::PreWorldUpdate), true);
on_server_hibernation_update_callback = globals::callbackManager.CreateCallback("OnServerHibernationUpdate");
on_server_steam_api_activated_callback = globals::callbackManager.CreateCallback("OnGameServerSteamAPIActivated");
@@ -63,21 +59,18 @@ void ServerManager::OnAllInitialized() {
on_server_precache_resources = globals::callbackManager.CreateCallback("OnServerPrecacheResources");
}
void ServerManager::OnShutdown() {
SH_REMOVE_HOOK(ISource2Server, ServerHibernationUpdate, globals::server,
SH_MEMBER(this, &ServerManager::ServerHibernationUpdate), true);
void ServerManager::OnShutdown()
{
SH_REMOVE_HOOK(ISource2Server, ServerHibernationUpdate, globals::server, SH_MEMBER(this, &ServerManager::ServerHibernationUpdate),
true);
SH_REMOVE_HOOK(ISource2Server, GameServerSteamAPIActivated, globals::server,
SH_MEMBER(this, &ServerManager::GameServerSteamAPIActivated), true);
SH_REMOVE_HOOK(ISource2Server, GameServerSteamAPIDeactivated, globals::server,
SH_MEMBER(this, &ServerManager::GameServerSteamAPIDeactivated), true);
SH_REMOVE_HOOK(ISource2Server, OnHostNameChanged, globals::server,
SH_MEMBER(this, &ServerManager::OnHostNameChanged), true);
SH_REMOVE_HOOK(ISource2Server, PreFatalShutdown, globals::server,
SH_MEMBER(this, &ServerManager::PreFatalShutdown), true);
SH_REMOVE_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server,
SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true);
SH_REMOVE_HOOK(ISource2Server, PreWorldUpdate, globals::server,
SH_MEMBER(this, &ServerManager::PreWorldUpdate), true);
SH_REMOVE_HOOK(ISource2Server, OnHostNameChanged, globals::server, SH_MEMBER(this, &ServerManager::OnHostNameChanged), true);
SH_REMOVE_HOOK(ISource2Server, PreFatalShutdown, globals::server, SH_MEMBER(this, &ServerManager::PreFatalShutdown), true);
SH_REMOVE_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server, SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true);
SH_REMOVE_HOOK(ISource2Server, PreWorldUpdate, globals::server, SH_MEMBER(this, &ServerManager::PreWorldUpdate), true);
globals::callbackManager.ReleaseCallback(on_server_hibernation_update_callback);
globals::callbackManager.ReleaseCallback(on_server_steam_api_activated_callback);
@@ -90,15 +83,9 @@ void ServerManager::OnShutdown() {
globals::callbackManager.ReleaseCallback(on_server_precache_resources);
}
void* ServerManager::GetEconItemSystem()
{
return globals::server->GetEconItemSystem();
}
void* ServerManager::GetEconItemSystem() { return globals::server->GetEconItemSystem(); }
bool ServerManager::IsPaused()
{
return globals::server->IsPaused();
}
bool ServerManager::IsPaused() { return globals::server->IsPaused(); }
void ServerManager::ServerHibernationUpdate(bool bHibernating)
{
@@ -106,7 +93,8 @@ void ServerManager::ServerHibernationUpdate(bool bHibernating)
auto callback = globals::serverManager.on_server_hibernation_update_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(bHibernating);
callback->Execute();
@@ -119,7 +107,8 @@ void ServerManager::GameServerSteamAPIActivated()
auto callback = globals::serverManager.on_server_steam_api_activated_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->Execute();
}
@@ -131,7 +120,8 @@ void ServerManager::GameServerSteamAPIDeactivated()
auto callback = globals::serverManager.on_server_steam_api_deactivated_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->Execute();
}
@@ -143,7 +133,8 @@ void ServerManager::OnHostNameChanged(const char *pHostname)
auto callback = globals::serverManager.on_server_hostname_changed_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pHostname);
callback->Execute();
@@ -156,7 +147,8 @@ void ServerManager::PreFatalShutdown()
auto callback = globals::serverManager.on_server_pre_fatal_shutdown;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->Execute();
}
@@ -168,7 +160,8 @@ void ServerManager::UpdateWhenNotInGame(float flFrameTime)
auto callback = globals::serverManager.on_server_update_when_not_in_game;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(flFrameTime);
callback->Execute();
@@ -181,18 +174,20 @@ void ServerManager::PreWorldUpdate(bool bSimulating)
auto size = m_nextWorldUpdateTasks.try_dequeue_bulk(out_list.begin(), 1024);
if (size > 0) {
CSSHARP_CORE_TRACE("Executing queued tasks of size: {0} at time {1}", size,
globals::getGlobalVars()->curtime);
if (size > 0)
{
CSSHARP_CORE_TRACE("Executing queued tasks of size: {0} at time {1}", size, globals::getGlobalVars()->curtime);
for (size_t i = 0; i < size; i++) {
for (size_t i = 0; i < size; i++)
{
out_list[i]();
}
}
auto callback = globals::serverManager.on_server_pre_world_update;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(bSimulating);
callback->Execute();
@@ -208,7 +203,8 @@ void ServerManager::OnPrecacheResources(IEntityResourceManifest* pResourceManife
{
CSSHARP_CORE_TRACE("Precache resources");
auto callback = globals::serverManager.on_server_precache_resources;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pResourceManifest);
callback->Execute();

View File

@@ -26,7 +26,8 @@
namespace counterstrikesharp {
class ScriptCallback;
class ServerManager : public GlobalClass {
class ServerManager : public GlobalClass
{
public:
ServerManager();
~ServerManager();
@@ -46,7 +47,6 @@ private:
void UpdateWhenNotInGame(float flFrameTime);
void PreWorldUpdate(bool bSimulating);
ScriptCallback* on_server_hibernation_update_callback;
ScriptCallback* on_server_steam_api_activated_callback;
ScriptCallback* on_server_steam_api_deactivated_callback;

View File

@@ -32,6 +32,7 @@ class VoiceManager : public GlobalClass
void OnShutdown() override;
bool SetClientListening(CPlayerSlot iReceiver, CPlayerSlot iSender, bool bListen);
void OnClientCommand(CPlayerSlot slot, const CCommand& args);
private:
};

View File

@@ -22,9 +22,11 @@
#include "gameconfig.h"
#include "memory_module.h"
void* FindSignature(const char* moduleName, const char* bytesStr) {
void* FindSignature(const char* moduleName, const char* bytesStr)
{
auto module = counterstrikesharp::modules::GetModuleByName(moduleName);
if (module == nullptr) {
if (module == nullptr)
{
return nullptr;
}

View File

@@ -63,8 +63,7 @@ void Initialize()
moduleList.emplace_back(std::move(mod));
}
#else
dl_iterate_phdr(
[](struct dl_phdr_info* info, size_t, void*) {
dl_iterate_phdr([](struct dl_phdr_info* info, size_t, void*) {
std::string name = info->dlpi_name;
if (name.rfind(MODULE_EXT) != name.length() - strlen(MODULE_EXT)) return 0;
@@ -80,8 +79,7 @@ void Initialize()
moduleList.emplace_back(std::move(mod));
return 0;
},
nullptr);
}, nullptr);
#endif
}

View File

@@ -86,7 +86,8 @@ class CModule
void DumpSymbols(ElfW(Dyn) * dyn);
#endif
std::optional<std::vector<std::uint8_t>> GetOriginalBytes(const std::vector<std::uint8_t>& disk_data, std::uintptr_t rva, std::size_t size);
std::optional<std::vector<std::uint8_t>>
GetOriginalBytes(const std::vector<std::uint8_t>& disk_data, std::uintptr_t rva, std::size_t size);
void* FindSignature(const std::vector<int16_t>& sigBytes);
};

View File

@@ -30,12 +30,14 @@ std::vector<std::function<void()>> TickScheduler::getCallbacks(int currentTick)
std::lock_guard<std::mutex> lock(taskMutex);
if (scheduledTasks.empty()) {
if (scheduledTasks.empty())
{
return callbacksToRun;
}
// Process tasks due for the current tick
while (!scheduledTasks.empty() && scheduledTasks.top().first <= currentTick) {
while (!scheduledTasks.empty() && scheduledTasks.top().first <= currentTick)
{
callbacksToRun.push_back(scheduledTasks.top().second);
scheduledTasks.pop();
}

View File

@@ -25,8 +25,7 @@ class TickScheduler
public:
struct TaskComparator
{
bool operator()(const std::pair<int, std::function<void()>>& a,
const std::pair<int, std::function<void()>>& b) const
bool operator()(const std::pair<int, std::function<void()>>& a, const std::pair<int, std::function<void()>>& b) const
{
return a.first > b.first;
}
@@ -34,10 +33,9 @@ class TickScheduler
void schedule(int tick, std::function<void()> callback);
std::vector<std::function<void()>> getCallbacks(int currentTick);
private:
std::priority_queue<std::pair<int, std::function<void()>>,
std::vector<std::pair<int, std::function<void()>>>,
TaskComparator>
std::priority_queue<std::pair<int, std::function<void()>>, std::vector<std::pair<int, std::function<void()>>>, TaskComparator>
scheduledTasks;
std::mutex taskMutex;
};

View File

@@ -44,7 +44,8 @@ namespace timers {
#define TIMER_FLAG_REPEAT (1 << 0) /**< Timer will repeat until stopped */
#define TIMER_FLAG_NO_MAPCHANGE (1 << 1) /**< Timer will not carry over mapchanges */
class Timer {
class Timer
{
friend class TimerSystem;
public:
@@ -63,7 +64,8 @@ public:
class ScriptCallback;
class TimerSystem : public GlobalClass {
class TimerSystem : public GlobalClass
{
public:
TimerSystem();
void OnAllInitialized() override;
@@ -78,7 +80,6 @@ public:
void KillTimer(timers::Timer* timer);
double GetTickedTime();
private:
bool m_has_map_ticked = false;
bool m_has_map_simulated = false;

View File

@@ -10,8 +10,10 @@ namespace utils {
static std::string gameDirectory;
inline std::string GameDirectory() {
if (gameDirectory.empty()) {
inline std::string GameDirectory()
{
if (gameDirectory.empty())
{
CBufferStringGrowable<255> gamePath;
globals::engine->GetGameDir(gamePath);
gameDirectory = std::string(gamePath.Get());

View File

@@ -17,7 +17,6 @@
#ifndef _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
#define _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
// clang-format off
#include <ISmmPlugin.h>
#include <functional>
#include <iserver.h>
@@ -27,7 +26,6 @@
#include <vector>
#include "entitysystem.h"
#include "concurrentqueue.h"
// clang-format on
namespace counterstrikesharp {
class ScriptCallback;
@@ -74,9 +72,7 @@ static ScriptCallback* on_activate_callback;
static ScriptCallback* on_metamod_all_plugins_loaded_callback;
extern CounterStrikeSharpMMPlugin gPlugin;
#endif //_INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
}
PLUGIN_GLOBALVARS();

View File

@@ -36,7 +36,6 @@
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
syntax = "proto2";
package google.protobuf;
@@ -54,12 +53,11 @@ option optimize_for = SPEED;
// The protocol compiler can output a FileDescriptorSet containing the .proto
// files it parses.
message FileDescriptorSet {
repeated FileDescriptorProto file = 1;
}
message FileDescriptorSet { repeated FileDescriptorProto file = 1; }
// Describes a complete .proto file.
message FileDescriptorProto {
message FileDescriptorProto
{
optional string name = 1; // file name, relative to root of source tree
optional string package = 2; // e.g. "foo", "foo.bar", etc.
@@ -91,7 +89,8 @@ message FileDescriptorProto {
}
// Describes a message type.
message DescriptorProto {
message DescriptorProto
{
optional string name = 1;
repeated FieldDescriptorProto field = 2;
@@ -100,7 +99,8 @@ message DescriptorProto {
repeated DescriptorProto nested_type = 3;
repeated EnumDescriptorProto enum_type = 4;
message ExtensionRange {
message ExtensionRange
{
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Exclusive.
@@ -115,7 +115,8 @@ message DescriptorProto {
// Range of reserved tag numbers. Reserved tag numbers may not be used by
// fields or extension ranges in the same message. Reserved ranges may
// not overlap.
message ReservedRange {
message ReservedRange
{
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Exclusive.
}
@@ -125,18 +126,20 @@ message DescriptorProto {
repeated string reserved_name = 10;
}
message ExtensionRangeOptions {
message ExtensionRangeOptions
{
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
message FieldDescriptorProto
{
enum Type
{
// 0 is reserved for errors.
// Order is weird for historical reasons.
TYPE_DOUBLE = 1;
@@ -169,7 +172,8 @@ message FieldDescriptorProto {
TYPE_SINT64 = 18; // Uses ZigZag encoding.
}
enum Label {
enum Label
{
// 0 is reserved for errors
LABEL_OPTIONAL = 1;
LABEL_REQUIRED = 2;
@@ -238,13 +242,15 @@ message FieldDescriptorProto {
}
// Describes a oneof.
message OneofDescriptorProto {
message OneofDescriptorProto
{
optional string name = 1;
optional OneofOptions options = 2;
}
// Describes an enum type.
message EnumDescriptorProto {
message EnumDescriptorProto
{
optional string name = 1;
repeated EnumValueDescriptorProto value = 2;
@@ -257,7 +263,8 @@ message EnumDescriptorProto {
// Note that this is distinct from DescriptorProto.ReservedRange in that it
// is inclusive such that it can appropriately represent the entire int32
// domain.
message EnumReservedRange {
message EnumReservedRange
{
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Inclusive.
}
@@ -273,7 +280,8 @@ message EnumDescriptorProto {
}
// Describes a value within an enum.
message EnumValueDescriptorProto {
message EnumValueDescriptorProto
{
optional string name = 1;
optional int32 number = 2;
@@ -281,7 +289,8 @@ message EnumValueDescriptorProto {
}
// Describes a service.
message ServiceDescriptorProto {
message ServiceDescriptorProto
{
optional string name = 1;
repeated MethodDescriptorProto method = 2;
@@ -289,7 +298,8 @@ message ServiceDescriptorProto {
}
// Describes a method of a service.
message MethodDescriptorProto {
message MethodDescriptorProto
{
optional string name = 1;
// Input and output type names. These are resolved in the same way as
@@ -305,7 +315,6 @@ message MethodDescriptorProto {
optional bool server_streaming = 6 [ default = false ];
}
// ===================================================================
// Options
@@ -338,15 +347,14 @@ message MethodDescriptorProto {
// If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
message FileOptions {
message FileOptions
{
// Sets the Java package where classes generated from this .proto will be
// placed. By default, the proto package is used, but this is often
// inappropriate because proto packages do not normally start with backwards
// domain names.
optional string java_package = 1;
// Controls the name of the wrapper Java class generated for the .proto file.
// That class will always contain the .proto file's getDescriptor() method as
// well as any top-level extensions defined in the .proto file.
@@ -373,9 +381,9 @@ message FileOptions {
// This option has no effect on when used with the lite runtime.
optional bool java_string_check_utf8 = 27 [ default = false ];
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
enum OptimizeMode
{
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
@@ -390,9 +398,6 @@ message FileOptions {
// - Otherwise, the basename of the .proto file, without extension.
optional string go_package = 11;
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
@@ -418,7 +423,6 @@ message FileOptions {
// only to generated classes for C++.
optional bool cc_enable_arenas = 31 [ default = true ];
// Sets the objective c class prefix which is prepended to all objective c
// generated classes from this .proto. There is no default.
optional string objc_class_prefix = 36;
@@ -451,7 +455,6 @@ message FileOptions {
// determining the ruby package.
optional string ruby_package = 45;
// The parser stores options it doesn't recognize here.
// See the documentation for the "Options" section above.
repeated UninterpretedOption uninterpreted_option = 999;
@@ -463,7 +466,8 @@ message FileOptions {
reserved 38;
}
message MessageOptions {
message MessageOptions
{
// Set true to use the old proto1 MessageSet wire format for extensions.
// This is provided for backwards-compatibility with the MessageSet wire
// format. You should not use this for any other reason: It's less
@@ -523,7 +527,6 @@ message MessageOptions {
reserved 8; // javalite_serializable
reserved 9; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
@@ -531,13 +534,15 @@ message MessageOptions {
extensions 1000 to max;
}
message FieldOptions {
message FieldOptions
{
// The ctype option instructs the C++ code generator to use a different
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1 [ default = STRING ];
enum CType {
enum CType
{
// Default mode.
STRING = 0;
@@ -564,7 +569,8 @@ message FieldOptions {
// This option is an enum to permit additional types to be added, e.g.
// goog.math.Integer.
optional JSType jstype = 6 [ default = JS_NORMAL ];
enum JSType {
enum JSType
{
// Use the default type.
JS_NORMAL = 0;
@@ -625,7 +631,6 @@ message FieldOptions {
// For Google-internal migration only. Do not use.
optional bool weak = 10 [ default = false ];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
@@ -635,7 +640,8 @@ message FieldOptions {
reserved 4; // removed jtype
}
message OneofOptions {
message OneofOptions
{
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
@@ -643,8 +649,8 @@ message OneofOptions {
extensions 1000 to max;
}
message EnumOptions {
message EnumOptions
{
// Set this option to true to allow mapping different tag names to the same
// value.
optional bool allow_alias = 2;
@@ -664,7 +670,8 @@ message EnumOptions {
extensions 1000 to max;
}
message EnumValueOptions {
message EnumValueOptions
{
// Is this enum value deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the enum value, or it will be completely ignored; in the very least,
@@ -678,8 +685,8 @@ message EnumValueOptions {
extensions 1000 to max;
}
message ServiceOptions {
message ServiceOptions
{
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
@@ -698,8 +705,8 @@ message ServiceOptions {
extensions 1000 to max;
}
message MethodOptions {
message MethodOptions
{
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
@@ -714,13 +721,13 @@ message MethodOptions {
// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
// or neither? HTTP based RPC implementation may choose GET verb for safe
// methods, and PUT verb for idempotent methods instead of the default POST.
enum IdempotencyLevel {
enum IdempotencyLevel
{
IDEMPOTENCY_UNKNOWN = 0;
NO_SIDE_EFFECTS = 1; // implies idempotent
IDEMPOTENT = 2; // idempotent, but may have side effects
}
optional IdempotencyLevel idempotency_level = 34
[default = IDEMPOTENCY_UNKNOWN];
optional IdempotencyLevel idempotency_level = 34 [ default = IDEMPOTENCY_UNKNOWN ];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
@@ -729,20 +736,21 @@ message MethodOptions {
extensions 1000 to max;
}
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
message UninterpretedOption {
message UninterpretedOption
{
// The name of the uninterpreted option. Each string represents a segment in
// a dot-separated name. is_extension is true iff a segment represents an
// extension (denoted with parentheses in options specs in .proto files).
// E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents
// "foo.(bar.baz).moo".
message NamePart {
message NamePart
{
required string name_part = 1;
required bool is_extension = 2;
}
@@ -763,7 +771,8 @@ message UninterpretedOption {
// Encapsulates information about the original source file from which a
// FileDescriptorProto was generated.
message SourceCodeInfo {
message SourceCodeInfo
{
// A Location identifies a piece of source code in a .proto file which
// corresponds to a particular definition. This information is intended
// to be useful to IDEs, code indexers, documentation generators, and similar
@@ -808,7 +817,8 @@ message SourceCodeInfo {
// ignore those that it doesn't understand, as more types of locations could
// be recorded in the future.
repeated Location location = 1;
message Location {
message Location
{
// Identifies which part of the FileDescriptorProto was defined at this
// location.
//
@@ -897,11 +907,13 @@ message SourceCodeInfo {
// Describes the relationship between generated code and its original source
// file. A GeneratedCodeInfo message is associated with only one generated
// source file, but may contain references to different source .proto files.
message GeneratedCodeInfo {
message GeneratedCodeInfo
{
// An Annotation connects some span of text in generated code to an element
// of its generating .proto file.
repeated Annotation annotation = 1;
message Annotation {
message Annotation
{
// Identifies the element in the original source .proto file. This field
// is formatted the same as SourceCodeInfo.Location.path.
repeated int32 path = 1 [ packed = true ];

View File

@@ -20,11 +20,11 @@
#include "core/globals.h"
#include "scripting/script_engine.h"
#define REGISTER_NATIVE(name, func) \
counterstrikesharp::ScriptEngine::RegisterNativeHandler(#name, func);
#define REGISTER_NATIVE(name, func) counterstrikesharp::ScriptEngine::RegisterNativeHandler(#name, func);
#define REGISTER_NATIVES(name, method) \
class Natives##name : public counterstrikesharp::GlobalClass { \
class Natives##name : public counterstrikesharp::GlobalClass \
{ \
public: \
void OnAllInitialized() override method \
}; \
@@ -32,7 +32,8 @@
Natives##name g_natives_##name;
#define CREATE_GETTER_FUNCTION(object_name, parameter_type, parameter_name, from_type, getter) \
static parameter_type object_name##Get##parameter_name(ScriptContext &script_context) { \
static parameter_type object_name##Get##parameter_name(ScriptContext& script_context) \
{ \
auto obj = script_context.GetArgument<from_type>(0); \
return getter; \
}
@@ -41,7 +42,8 @@
static parameter_type Get##parameter_name(ScriptContext& script_context) { return getter; }
#define CREATE_SETTER_FUNCTION(type_name, get_type, name, from_type, setter) \
static void type_name##Set##name(ScriptContext &script_context) { \
static void type_name##Set##name(ScriptContext& script_context) \
{ \
auto obj = script_context.GetArgument<from_type>(0); \
auto value = script_context.GetArgument<get_type>(1); \
setter; \

View File

@@ -99,8 +99,7 @@ bool load_hostfxr()
std::string base_dir = counterstrikesharp::utils::GetRootDirectory();
namespace css = counterstrikesharp;
#if _WIN32
std::wstring buffer =
std::wstring(css::widen(base_dir) + L"\\dotnet\\host\\fxr\\8.0.3\\hostfxr.dll");
std::wstring buffer = std::wstring(css::widen(base_dir) + L"\\dotnet\\host\\fxr\\8.0.3\\hostfxr.dll");
CSSHARP_CORE_INFO("Loading hostfxr from {0}", css::narrow(buffer).c_str());
#else
std::string buffer = std::string(base_dir + "/dotnet/host/fxr/8.0.3/libhostfxr.so");
@@ -109,21 +108,21 @@ bool load_hostfxr()
// Load hostfxr and get desired exports
void* lib = load_library(buffer.c_str());
init_fptr = (hostfxr_initialize_for_runtime_config_fn)get_export(
lib, "hostfxr_initialize_for_runtime_config");
if (init_fptr == nullptr) {
CSSHARP_CORE_CRITICAL(
"unable to get export function: \"hostfxr_initialize_for_runtime_config\"");
init_fptr = (hostfxr_initialize_for_runtime_config_fn)get_export(lib, "hostfxr_initialize_for_runtime_config");
if (init_fptr == nullptr)
{
CSSHARP_CORE_CRITICAL("unable to get export function: \"hostfxr_initialize_for_runtime_config\"");
return false;
}
get_delegate_fptr =
(hostfxr_get_runtime_delegate_fn)get_export(lib, "hostfxr_get_runtime_delegate");
if (!get_delegate_fptr) {
get_delegate_fptr = (hostfxr_get_runtime_delegate_fn)get_export(lib, "hostfxr_get_runtime_delegate");
if (!get_delegate_fptr)
{
CSSHARP_CORE_CRITICAL("unable to get export function: \"hostfxr_get_runtime_delegate\"");
return false;
}
close_fptr = (hostfxr_close_fn)get_export(lib, "hostfxr_close");
if (!close_fptr) {
if (!close_fptr)
{
CSSHARP_CORE_CRITICAL("unable to get export function: \"hostfxr_close\"");
return false;
}
@@ -139,16 +138,17 @@ load_assembly_and_get_function_pointer_fn get_dotnet_load_assembly(const char_t*
// Load .NET Core
void* load_assembly_and_get_function_pointer = nullptr;
int rc = init_fptr(config_path, nullptr, &cxt);
if (rc != 0 || cxt == nullptr) {
if (rc != 0 || cxt == nullptr)
{
CSSHARP_CORE_CRITICAL("Init failed: {0:x}", rc);
close_fptr(cxt);
return nullptr;
}
// Get the load assembly function pointer
rc = get_delegate_fptr(cxt, hdt_load_assembly_and_get_function_pointer,
&load_assembly_and_get_function_pointer);
if (rc != 0 || load_assembly_and_get_function_pointer == nullptr) {
rc = get_delegate_fptr(cxt, hdt_load_assembly_and_get_function_pointer, &load_assembly_and_get_function_pointer);
if (rc != 0 || load_assembly_and_get_function_pointer == nullptr)
{
CSSHARP_CORE_ERROR("Get delegate failed: {0:x}", rc);
}
@@ -168,54 +168,51 @@ bool CDotNetManager::Initialize()
CSSHARP_CORE_INFO("Loading .NET runtime...");
if (!load_hostfxr()) {
if (!load_hostfxr())
{
CSSHARP_CORE_ERROR("Failed to initialize .NET runtime.");
return false;
}
CSSHARP_CORE_INFO(".NET Runtime Initialised.");
namespace css = counterstrikesharp;
#if _WIN32
const auto wide_str =
std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.runtimeconfig.json");
CSSHARP_CORE_INFO("Loading CSS API, Runtime config: {}",
counterstrikesharp::narrow(wide_str).c_str());
const auto wide_str = std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.runtimeconfig.json");
CSSHARP_CORE_INFO("Loading CSS API, Runtime config: {}", counterstrikesharp::narrow(wide_str).c_str());
#else
std::string wide_str =
std::string((base_dir + "/api/CounterStrikeSharp.API.runtimeconfig.json").c_str());
std::string wide_str = std::string((base_dir + "/api/CounterStrikeSharp.API.runtimeconfig.json").c_str());
CSSHARP_CORE_INFO("Loading CSS API, Runtime Config: {}", wide_str);
#endif
const auto load_assembly_and_get_function_pointer = get_dotnet_load_assembly(wide_str.c_str());
if (load_assembly_and_get_function_pointer == nullptr) {
if (load_assembly_and_get_function_pointer == nullptr)
{
CSSHARP_CORE_ERROR("Failed to load CSS API.");
return false;
}
#if _WIN32
const auto dotnetlib_path =
std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.dll");
const auto dotnetlib_path = std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.dll");
CSSHARP_CORE_INFO("CSS API DLL: {}", counterstrikesharp::narrow(dotnetlib_path));
#else
const std::string dotnetlib_path =
std::string((base_dir + "/api/CounterStrikeSharp.API.dll").c_str());
const std::string dotnetlib_path = std::string((base_dir + "/api/CounterStrikeSharp.API.dll").c_str());
#endif
const auto dotnet_type = STR("CounterStrikeSharp.API.Bootstrap, CounterStrikeSharp.API");
// Namespace, assembly name
typedef int(CORECLR_DELEGATE_CALLTYPE * custom_entry_point_fn)();
custom_entry_point_fn entry_point = nullptr;
const int rc = load_assembly_and_get_function_pointer(
dotnetlib_path.c_str(), dotnet_type, STR("Run"), UNMANAGEDCALLERSONLY_METHOD,
const int rc = load_assembly_and_get_function_pointer(dotnetlib_path.c_str(), dotnet_type, STR("Run"), UNMANAGEDCALLERSONLY_METHOD,
nullptr, reinterpret_cast<void**>(&entry_point));
if (entry_point == nullptr) {
if (entry_point == nullptr)
{
CSSHARP_CORE_ERROR("Trying to get entry point \"Bootstrap::Run\" but failed.");
return false;
}
assert(rc == 0 && entry_point != nullptr &&
"Failure: load_assembly_and_get_function_pointer()");
assert(rc == 0 && entry_point != nullptr && "Failure: load_assembly_and_get_function_pointer()");
if (const int invoke_result_code = entry_point(); invoke_result_code == 0) {
if (const int invoke_result_code = entry_point(); invoke_result_code == 0)
{
CSSHARP_CORE_ERROR("Bootstrap::Run return failure.");
return false;
}

View File

@@ -21,18 +21,19 @@
#include <unordered_map>
#include <vector>
class PluginContext {
class PluginContext
{
friend class CDotNetManager;
public:
PluginContext(std::string dll_path)
: m_dll_path(dll_path) {}
PluginContext(std::string dll_path) : m_dll_path(dll_path) {}
private:
std::string m_dll_path;
};
class CDotNetManager {
class CDotNetManager
{
friend class PluginContext;
public:

View File

@@ -20,14 +20,16 @@
namespace counterstrikesharp {
static bool AddListener(ScriptContext &script_context) {
static bool AddListener(ScriptContext& script_context)
{
auto name = script_context.GetArgument<const char*>(0);
auto callback = script_context.GetArgument<CallbackT>(1);
return globals::callbackManager.TryAddFunction(name, callback);
}
static bool RemoveListener(ScriptContext &script_context) {
static bool RemoveListener(ScriptContext& script_context)
{
auto name = script_context.GetArgument<const char*>(0);
auto callback = script_context.GetArgument<CallbackT>(1);

View File

@@ -14,7 +14,6 @@
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
// clang-format off
#include "mm_plugin.h"
#include "core/timer_system.h"
#include "scripting/autonative.h"
@@ -24,19 +23,19 @@
#include "dynohook/core.h"
#include "dynohook/manager.h"
// clang-format on
namespace counterstrikesharp {
void DHookGetReturn(ScriptContext& script_context)
{
auto hook = script_context.GetArgument<dyno::Hook*>(0);
auto dataType = script_context.GetArgument<DataType_t>(1);
if (hook == nullptr) {
if (hook == nullptr)
{
script_context.ThrowNativeError("Invalid hook");
}
switch (dataType) {
switch (dataType)
{
case DATA_TYPE_BOOL:
script_context.SetResult(hook->getReturnValue<bool>());
break;
@@ -92,13 +91,15 @@ void DHookSetReturn(ScriptContext& script_context)
{
auto hook = script_context.GetArgument<dyno::Hook*>(0);
auto dataType = script_context.GetArgument<DataType_t>(1);
if (hook == nullptr) {
if (hook == nullptr)
{
script_context.ThrowNativeError("Invalid hook");
}
auto valueIndex = 2;
switch (dataType) {
switch (dataType)
{
case DATA_TYPE_BOOL:
hook->setReturnValue(script_context.GetArgument<bool>(valueIndex));
break;
@@ -155,11 +156,13 @@ void DHookGetParam(ScriptContext& script_context)
auto hook = script_context.GetArgument<dyno::Hook*>(0);
auto dataType = script_context.GetArgument<DataType_t>(1);
auto paramIndex = script_context.GetArgument<int>(2);
if (hook == nullptr) {
if (hook == nullptr)
{
script_context.ThrowNativeError("Invalid hook");
}
switch (dataType) {
switch (dataType)
{
case DATA_TYPE_BOOL:
script_context.SetResult(hook->getArgument<bool>(paramIndex));
break;
@@ -216,13 +219,15 @@ void DHookSetParam(ScriptContext& script_context)
auto hook = script_context.GetArgument<dyno::Hook*>(0);
auto dataType = script_context.GetArgument<DataType_t>(1);
auto paramIndex = script_context.GetArgument<int>(2);
if (hook == nullptr) {
if (hook == nullptr)
{
script_context.ThrowNativeError("Invalid hook");
}
auto valueIndex = 3;
switch (dataType) {
switch (dataType)
{
case DATA_TYPE_BOOL:
hook->setArgument(paramIndex, script_context.GetArgument<bool>(valueIndex));
break;

View File

@@ -20,7 +20,6 @@
#include <filesystem.h>
#include <public/worldsize.h>
// clang-format off
#include "mm_plugin.h"
#include "core/timer_system.h"
#include "core/utils.h"
@@ -32,7 +31,6 @@
#include "core/managers/player_manager.h"
#include "core/managers/server_manager.h"
#include "core/tick_scheduler.h"
// clang-format on
#if _WIN32
#undef GetCurrentTime

View File

@@ -20,12 +20,12 @@
#include "scripting/autonative.h"
#include "igameevents.h"
namespace counterstrikesharp {
std::vector<IGameEvent*> managed_game_events;
static void HookEvent(ScriptContext &script_context) {
static void HookEvent(ScriptContext& script_context)
{
const char* name = script_context.GetArgument<const char*>(0);
auto callback = script_context.GetArgument<CallbackT>(1);
auto post = script_context.GetArgument<bool>(2);
@@ -33,7 +33,8 @@ static void HookEvent(ScriptContext &script_context) {
globals::eventManager.HookEvent(name, callback, post);
}
static void UnhookEvent(ScriptContext &script_context) {
static void UnhookEvent(ScriptContext& script_context)
{
const char* name = script_context.GetArgument<const char*>(0);
auto callback = script_context.GetArgument<CallbackT>(1);
auto post = script_context.GetArgument<bool>(2);
@@ -41,23 +42,27 @@ static void UnhookEvent(ScriptContext &script_context) {
globals::eventManager.UnhookEvent(name, callback, post);
}
static IGameEvent *CreateEvent(ScriptContext &script_context) {
static IGameEvent* CreateEvent(ScriptContext& script_context)
{
auto name = script_context.GetArgument<const char*>(0);
bool force = script_context.GetArgument<bool>(1);
auto pEvent = globals::gameEventManager->CreateEvent(name, force);
if (pEvent != nullptr) {
if (pEvent != nullptr)
{
managed_game_events.push_back(pEvent);
}
return pEvent;
}
static void FireEvent(ScriptContext &script_context) {
static void FireEvent(ScriptContext& script_context)
{
auto game_event = script_context.GetArgument<IGameEvent*>(0);
bool dont_broadcast = script_context.GetArgument<bool>(1);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return;
}
@@ -66,17 +71,19 @@ static void FireEvent(ScriptContext &script_context) {
managed_game_events.erase(std::remove(managed_game_events.begin(), managed_game_events.end(), game_event), managed_game_events.end());
}
static void FireEventToClient(ScriptContext& script_context) {
static void FireEventToClient(ScriptContext& script_context)
{
auto game_event = script_context.GetArgument<IGameEvent*>(0);
int entityIndex = script_context.GetArgument<int>(1);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return;
}
IGameEventListener2* pListener = globals::GetLegacyGameEventListener(CPlayerSlot(entityIndex - 1));
if (!pListener) {
if (!pListener)
{
script_context.ThrowNativeError("Could not get player event listener");
return;
}
@@ -84,9 +91,11 @@ static void FireEventToClient(ScriptContext& script_context) {
pListener->FireGameEvent(game_event);
}
static void FreeEvent(ScriptContext& script_context) {
static void FreeEvent(ScriptContext& script_context)
{
auto game_event = script_context.GetArgument<IGameEvent*>(0);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return;
}
@@ -95,10 +104,12 @@ static void FreeEvent(ScriptContext& script_context) {
managed_game_events.erase(std::remove(managed_game_events.begin(), managed_game_events.end(), game_event), managed_game_events.end());
}
static const char *GetEventName(ScriptContext &script_context) {
static const char* GetEventName(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return nullptr;
}
@@ -106,11 +117,13 @@ static const char *GetEventName(ScriptContext &script_context) {
return game_event->GetName();
}
static bool GetEventBool(ScriptContext &script_context) {
static bool GetEventBool(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return false;
}
@@ -118,11 +131,13 @@ static bool GetEventBool(ScriptContext &script_context) {
return game_event->GetBool(key_name);
}
static int GetEventInt(ScriptContext &script_context) {
static int GetEventInt(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return -1;
}
@@ -130,11 +145,13 @@ static int GetEventInt(ScriptContext &script_context) {
return game_event->GetInt(key_name);
}
static float GetEventFloat(ScriptContext &script_context) {
static float GetEventFloat(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return -1;
}
@@ -142,11 +159,13 @@ static float GetEventFloat(ScriptContext &script_context) {
return game_event->GetFloat(key_name);
}
static const char *GetEventString(ScriptContext &script_context) {
static const char* GetEventString(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
if (!game_event) {
if (!game_event)
{
script_context.ThrowNativeError("Invalid game event");
return nullptr;
}
@@ -154,51 +173,61 @@ static const char *GetEventString(ScriptContext &script_context) {
return game_event->GetString(key_name);
}
static void SetEventBool(ScriptContext &script_context) {
static void SetEventBool(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
const bool value = script_context.GetArgument<bool>(2);
if (game_event) {
if (game_event)
{
game_event->SetBool(key_name, value);
}
}
static void SetEventInt(ScriptContext &script_context) {
static void SetEventInt(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
const int value = script_context.GetArgument<int>(2);
if (game_event) {
if (game_event)
{
game_event->SetInt(key_name, value);
}
}
static void SetEventFloat(ScriptContext &script_context) {
static void SetEventFloat(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
const float value = script_context.GetArgument<float>(2);
if (game_event) {
if (game_event)
{
game_event->SetFloat(key_name, value);
}
}
static void SetEventString(ScriptContext &script_context) {
static void SetEventString(ScriptContext& script_context)
{
IGameEvent* game_event = script_context.GetArgument<IGameEvent*>(0);
const char* key_name = script_context.GetArgument<const char*>(1);
const char* value = script_context.GetArgument<const char*>(2);
if (game_event) {
if (game_event)
{
game_event->SetString(key_name, value);
}
}
static void *GetPlayerController(ScriptContext &scriptContext) {
static void* GetPlayerController(ScriptContext& scriptContext)
{
IGameEvent* gameEvent = scriptContext.GetArgument<IGameEvent*>(0);
const char* keyName = scriptContext.GetArgument<const char*>(1);
if (gameEvent == nullptr) {
if (gameEvent == nullptr)
{
scriptContext.ThrowNativeError("Invalid game event");
return nullptr;
}
@@ -206,41 +235,49 @@ static void *GetPlayerController(ScriptContext &scriptContext) {
return gameEvent->GetPlayerController(keyName);
}
static void SetPlayerController(ScriptContext &scriptContext) {
static void SetPlayerController(ScriptContext& scriptContext)
{
IGameEvent* gameEvent = scriptContext.GetArgument<IGameEvent*>(0);
const char* keyName = scriptContext.GetArgument<const char*>(1);
auto* value = scriptContext.GetArgument<CEntityInstance*>(2);
if (gameEvent != nullptr) {
if (gameEvent != nullptr)
{
gameEvent->SetPlayer(keyName, value);
}
}
static void SetEntity(ScriptContext &scriptContext) {
static void SetEntity(ScriptContext& scriptContext)
{
IGameEvent* gameEvent = scriptContext.GetArgument<IGameEvent*>(0);
const char* keyName = scriptContext.GetArgument<const char*>(1);
auto* value = scriptContext.GetArgument<CEntityInstance*>(2);
if (gameEvent != nullptr) {
if (gameEvent != nullptr)
{
gameEvent->SetEntity(keyName, value);
}
}
static void SetEntityIndex(ScriptContext &scriptContext) {
static void SetEntityIndex(ScriptContext& scriptContext)
{
IGameEvent* gameEvent = scriptContext.GetArgument<IGameEvent*>(0);
const char* keyName = scriptContext.GetArgument<const char*>(1);
auto index = scriptContext.GetArgument<int>(2);
if (gameEvent != nullptr) {
if (gameEvent != nullptr)
{
gameEvent->SetEntity(keyName, CEntityIndex{ index });
}
}
static void *GetPlayerPawn(ScriptContext& scriptContext) {
static void* GetPlayerPawn(ScriptContext& scriptContext)
{
IGameEvent* gameEvent = scriptContext.GetArgument<IGameEvent*>(0);
const char* keyName = scriptContext.GetArgument<const char*>(1);
if (gameEvent == nullptr) {
if (gameEvent == nullptr)
{
scriptContext.ThrowNativeError("Invalid game event");
return nullptr;
}
@@ -248,11 +285,13 @@ static void *GetPlayerPawn(ScriptContext& scriptContext) {
return gameEvent->GetPlayerPawn(keyName);
}
static uint64 GetUint64(ScriptContext &scriptContext) {
static uint64 GetUint64(ScriptContext& scriptContext)
{
IGameEvent* gameEvent = scriptContext.GetArgument<IGameEvent*>(0);
const char* keyName = scriptContext.GetArgument<const char*>(1);
if (gameEvent == nullptr) {
if (gameEvent == nullptr)
{
scriptContext.ThrowNativeError("Invalid game event");
return 0;
}
@@ -260,17 +299,20 @@ static uint64 GetUint64(ScriptContext &scriptContext) {
return gameEvent->GetUint64(keyName);
}
static void SetUint64(ScriptContext &scriptContext) {
static void SetUint64(ScriptContext& scriptContext)
{
IGameEvent* gameEvent = scriptContext.GetArgument<IGameEvent*>(0);
const char* keyName = scriptContext.GetArgument<const char*>(1);
auto value = scriptContext.GetArgument<uint64>(2);
if (gameEvent != nullptr) {
if (gameEvent != nullptr)
{
gameEvent->SetUint64(keyName, value);
}
}
static int LoadEventsFromFile(ScriptContext &script_context) {
static int LoadEventsFromFile(ScriptContext& script_context)
{
auto [path, searchAll] = script_context.GetArguments<const char*, bool>();
return globals::gameEventManager->LoadEventsFromFile(path, searchAll);
@@ -304,7 +346,6 @@ REGISTER_NATIVES(events, {
ScriptEngine::RegisterNativeHandler("GET_EVENT_UINT64", GetUint64);
ScriptEngine::RegisterNativeHandler("SET_EVENT_UINT64", SetUint64);
ScriptEngine::RegisterNativeHandler("LOAD_EVENTS_FROM_FILE", LoadEventsFromFile);
})

View File

@@ -26,7 +26,5 @@ static void* MetaFactory(ScriptContext& script_context)
return ptr;
}
REGISTER_NATIVES(metamod, {
ScriptEngine::RegisterNativeHandler("META_FACTORY", MetaFactory);
})
REGISTER_NATIVES(metamod, { ScriptEngine::RegisterNativeHandler("META_FACTORY", MetaFactory); })
} // namespace counterstrikesharp

View File

@@ -57,12 +57,10 @@ int GetSchemaClassSize(ScriptContext& script_context)
{
auto className = script_context.GetArgument<const char*>(0);
CSchemaSystemTypeScope* pType =
globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
CSchemaSystemTypeScope* pType = globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get();
if (!pClassInfo)
return -1;
if (!pClassInfo) return -1;
return pClassInfo->m_nSize;
}
@@ -78,66 +76,52 @@ void GetSchemaValueByName(ScriptContext& script_context)
const auto m_key = schema::GetOffset(className, classKey, memberName, memberKey);
switch (returnType) {
switch (returnType)
{
case DATA_TYPE_BOOL:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<bool>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<bool>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_CHAR:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<char>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<char>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_UCHAR:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned char>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned char>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_SHORT:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<short>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<short>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_USHORT:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned short>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned short>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_INT:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<int>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<int>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_UINT:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned int>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned int>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_LONG:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<long>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<long>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_ULONG:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned long>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<unsigned long>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_LONG_LONG:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<long long>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<long long>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_ULONG_LONG:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<uint64_t>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<uint64_t>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_FLOAT:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<float>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<float>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_DOUBLE:
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<double>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(*reinterpret_cast<std::add_pointer_t<double>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_POINTER:
script_context.SetResult(reinterpret_cast<std::add_pointer_t<void>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(reinterpret_cast<std::add_pointer_t<void>>((uintptr_t)(instancePointer) + m_key.offset));
break;
case DATA_TYPE_STRING:
script_context.SetResult(reinterpret_cast<std::add_pointer_t<char>>(
(uintptr_t)(instancePointer) + m_key.offset));
script_context.SetResult(reinterpret_cast<std::add_pointer_t<char>>((uintptr_t)(instancePointer) + m_key.offset));
break;
default:
assert(!"Unknown function return type!");
@@ -152,7 +136,9 @@ void SetSchemaValueByName(ScriptContext& script_context)
auto className = script_context.GetArgument<const char*>(2);
auto memberName = script_context.GetArgument<const char*>(3);
if (globals::coreConfig->FollowCS2ServerGuidelines && std::find(schema::CS2BadList.begin(), schema::CS2BadList.end(), memberName) != schema::CS2BadList.end()) {
if (globals::coreConfig->FollowCS2ServerGuidelines &&
std::find(schema::CS2BadList.begin(), schema::CS2BadList.end(), memberName) != schema::CS2BadList.end())
{
CSSHARP_CORE_ERROR("Cannot set '{}::{}' with \"FollowCS2ServerGuidelines\" option enabled.", className, memberName);
return;
}
@@ -162,18 +148,16 @@ void SetSchemaValueByName(ScriptContext& script_context)
const auto m_key = schema::GetOffset(className, classKey, memberName, memberKey);
switch (dataType) {
switch (dataType)
{
case DATA_TYPE_BOOL:
*reinterpret_cast<std::add_pointer_t<bool>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<bool>(4);
*reinterpret_cast<std::add_pointer_t<bool>>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument<bool>(4);
break;
case DATA_TYPE_CHAR:
*reinterpret_cast<std::add_pointer_t<char>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<char>(4);
*reinterpret_cast<std::add_pointer_t<char>>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument<char>(4);
break;
case DATA_TYPE_UCHAR:
*reinterpret_cast<std::add_pointer_t<unsigned char>>((uintptr_t)(instancePointer) +
m_key.offset) =
*reinterpret_cast<std::add_pointer_t<unsigned char>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<unsigned char>(4);
break;
case DATA_TYPE_SHORT:
@@ -181,35 +165,30 @@ void SetSchemaValueByName(ScriptContext& script_context)
script_context.GetArgument<short>(4);
break;
case DATA_TYPE_USHORT:
*reinterpret_cast<std::add_pointer_t<unsigned short>>((uintptr_t)(instancePointer) +
m_key.offset) =
*reinterpret_cast<std::add_pointer_t<unsigned short>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<unsigned short>(4);
break;
case DATA_TYPE_INT:
*reinterpret_cast<std::add_pointer_t<int>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<int>(4);
*reinterpret_cast<std::add_pointer_t<int>>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument<int>(4);
break;
case DATA_TYPE_UINT:
*reinterpret_cast<std::add_pointer_t<unsigned int>>((uintptr_t)(instancePointer) +
m_key.offset) =
*reinterpret_cast<std::add_pointer_t<unsigned int>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<unsigned int>(4);
break;
case DATA_TYPE_LONG:
*reinterpret_cast<std::add_pointer_t<long>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<long>(4);
*reinterpret_cast<std::add_pointer_t<long>>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument<long>(4);
break;
case DATA_TYPE_ULONG:
*reinterpret_cast<std::add_pointer_t<unsigned long>>((uintptr_t)(instancePointer) +
m_key.offset) =
*reinterpret_cast<std::add_pointer_t<unsigned long>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<unsigned long>(4);
break;
case DATA_TYPE_LONG_LONG:
*reinterpret_cast<std::add_pointer_t<long long>>(
(uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument<long long>(4);
*reinterpret_cast<std::add_pointer_t<long long>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<long long>(4);
break;
case DATA_TYPE_ULONG_LONG:
*reinterpret_cast<std::add_pointer_t<uint64_t>>(
(uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument<uint64_t>(4);
*reinterpret_cast<std::add_pointer_t<uint64_t>>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<uint64_t>(4);
break;
case DATA_TYPE_FLOAT:
*reinterpret_cast<std::add_pointer_t<float>>((uintptr_t)(instancePointer) + m_key.offset) =
@@ -220,13 +199,12 @@ void SetSchemaValueByName(ScriptContext& script_context)
script_context.GetArgument<double>(4);
break;
case DATA_TYPE_POINTER:
*reinterpret_cast<void**>((uintptr_t)(instancePointer) + m_key.offset) =
script_context.GetArgument<void*>(4);
*reinterpret_cast<void**>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument<void*>(4);
break;
case DATA_TYPE_STRING: {
case DATA_TYPE_STRING:
{
auto duplicated = strdup(script_context.GetArgument<const char*>(4));
*reinterpret_cast<char**>((uintptr_t)(instancePointer) + m_key.offset) =
duplicated;
*reinterpret_cast<char**>((uintptr_t)(instancePointer) + m_key.offset) = duplicated;
break;
}
default:

View File

@@ -20,18 +20,13 @@
namespace counterstrikesharp {
static void *GetEconItemSystem(ScriptContext& scriptContext) {
return globals::serverManager.GetEconItemSystem();
}
static void* GetEconItemSystem(ScriptContext& scriptContext) { return globals::serverManager.GetEconItemSystem(); }
static bool IsServerPaused(ScriptContext& scriptContext)
{
return globals::serverManager.IsPaused();
}
static bool IsServerPaused(ScriptContext& scriptContext) { return globals::serverManager.IsPaused(); }
REGISTER_NATIVES(server, {
ScriptEngine::RegisterNativeHandler("GET_ECON_ITEM_SYSTEM", GetEconItemSystem);
ScriptEngine::RegisterNativeHandler("IS_SERVER_PAUSED", IsServerPaused);
})
}
} // namespace counterstrikesharp

View File

@@ -21,7 +21,8 @@
namespace counterstrikesharp {
timers::Timer *CreateTimer(ScriptContext &script_context) {
timers::Timer* CreateTimer(ScriptContext& script_context)
{
auto interval = script_context.GetArgument<float>(0);
auto callback = script_context.GetArgument<CallbackT>(1);
auto flags = script_context.GetArgument<int>(2);
@@ -29,7 +30,8 @@ timers::Timer *CreateTimer(ScriptContext &script_context) {
return globals::timerSystem.CreateTimer(interval, callback, flags);
}
void KillTimer(ScriptContext &script_context) {
void KillTimer(ScriptContext& script_context)
{
auto timer = script_context.GetArgument<timers::Timer*>(0);
globals::timerSystem.KillTimer(timer);
}

View File

@@ -13,8 +13,6 @@
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
// clang-format off
#include "core/UserMessage.h"
#include "core/globals.h"
#include "core/log.h"
@@ -24,8 +22,6 @@
#include "core/recipientfilters.h"
// clang-format on
namespace counterstrikesharp {
#define GET_MESSAGE_OR_ERR() \
@@ -620,13 +616,16 @@ static void UserMessageSend(ScriptContext& scriptContext)
CRecipientFilter filter{};
filter.AddRecipientsFromMask(message->GetRecipientMask() ? *message->GetRecipientMask() : 0);
// This is for calling send in a UM hook, if calling normal send using the UM instance from the UM hook, it will cause an inifinite loop, then crashing the server
static void (IGameEventSystem::*PostEventAbstract)(CSplitScreenSlot, bool, IRecipientFilter*, INetworkMessageInternal*, const CNetMessage*, unsigned long) = &IGameEventSystem::PostEventAbstract;
// This is for calling send in a UM hook, if calling normal send using the UM instance from the UM hook, it will cause an inifinite
// loop, then crashing the server
static void (IGameEventSystem::*PostEventAbstract)(CSplitScreenSlot, bool, IRecipientFilter*, INetworkMessageInternal*,
const CNetMessage*, unsigned long) = &IGameEventSystem::PostEventAbstract;
if (message->IsManuallyAllocated())
globals::gameEventSystem->PostEventAbstract(0, false, &filter, message->GetSerializableMessage(), message->GetProtobufMessage(), 0);
else
SH_CALL(globals::gameEventSystem, PostEventAbstract)(0, false, &filter, message->GetSerializableMessage(), message->GetProtobufMessage(), 0);
SH_CALL(globals::gameEventSystem, PostEventAbstract)(0, false, &filter, message->GetSerializableMessage(),
message->GetProtobufMessage(), 0);
}
static void UserMessageDelete(ScriptContext& scriptContext)

View File

@@ -37,7 +37,8 @@ namespace counterstrikesharp {
std::stack<std::string> errors;
void ScriptContext::ThrowNativeError(const char *msg, ...) {
void ScriptContext::ThrowNativeError(const char* msg, ...)
{
va_list arglist;
char dest[256];
va_start(arglist, msg);
@@ -54,8 +55,10 @@ void ScriptContext::ThrowNativeError(const char *msg, ...) {
*this->m_has_error = 1;
}
void ScriptContext::Reset() {
if (*m_has_error) {
void ScriptContext::Reset()
{
if (*m_has_error)
{
errors.pop();
}
@@ -63,36 +66,43 @@ void ScriptContext::Reset() {
m_numArguments = 0;
*m_has_error = 0;
for (int i = 0; i < 32; i++) {
for (int i = 0; i < 32; i++)
{
m_native_context->arguments[i] = 0;
}
m_native_context->result = 0;
}
tl::optional<TNativeHandler> ScriptEngine::GetNativeHandler(uint64_t nativeIdentifier) {
tl::optional<TNativeHandler> ScriptEngine::GetNativeHandler(uint64_t nativeIdentifier)
{
auto it = g_registeredHandlers.find(nativeIdentifier);
if (it != g_registeredHandlers.end()) {
if (it != g_registeredHandlers.end())
{
return it->second;
}
return tl::optional<TNativeHandler>();
}
tl::optional<TNativeHandler> ScriptEngine::GetNativeHandler(std::string identifier) {
tl::optional<TNativeHandler> ScriptEngine::GetNativeHandler(std::string identifier)
{
auto it = g_registeredHandlers.find(hash_string(identifier.c_str()));
if (it != g_registeredHandlers.end()) {
if (it != g_registeredHandlers.end())
{
return it->second;
}
return tl::optional<TNativeHandler>();
}
bool ScriptEngine::CallNativeHandler(uint64_t nativeIdentifier, ScriptContext &context) {
bool ScriptEngine::CallNativeHandler(uint64_t nativeIdentifier, ScriptContext& context)
{
auto h = GetNativeHandler(nativeIdentifier);
if (h) {
if (h)
{
(*h)(context);
return true;
@@ -101,23 +111,26 @@ bool ScriptEngine::CallNativeHandler(uint64_t nativeIdentifier, ScriptContext &c
return false;
}
void ScriptEngine::RegisterNativeHandlerInt(uint64_t nativeIdentifier, TNativeHandler function) {
void ScriptEngine::RegisterNativeHandlerInt(uint64_t nativeIdentifier, TNativeHandler function)
{
g_registeredHandlers[nativeIdentifier] = function;
}
void ScriptEngine::InvokeNative(counterstrikesharp::fxNativeContext &context) {
void ScriptEngine::InvokeNative(counterstrikesharp::fxNativeContext& context)
{
if (context.nativeIdentifier == 0) return;
auto nativeHandler =
counterstrikesharp::ScriptEngine::GetNativeHandler(context.nativeIdentifier);
auto nativeHandler = counterstrikesharp::ScriptEngine::GetNativeHandler(context.nativeIdentifier);
if (nativeHandler) {
if (nativeHandler)
{
counterstrikesharp::ScriptContextRaw scriptContext(context);
(*nativeHandler)(scriptContext);
} else {
CSSHARP_CORE_WARN("Native Handler was requested but not found: {0:x}",
context.nativeIdentifier);
}
else
{
CSSHARP_CORE_WARN("Native Handler was requested but not found: {0:x}", context.nativeIdentifier);
assert(false);
}
}

View File

@@ -33,41 +33,46 @@
namespace counterstrikesharp {
enum HookResult {
enum HookResult
{
Continue = 0,
Changed = 1,
Handled = 3,
Stop = 4,
};
enum HookMode {
enum HookMode
{
Pre = 0,
Post = 1,
};
inline uint32_t hash_string(const char *string) {
unsigned long result = 5381;
for (size_t i = 0; i < strlen(string); i++) {
result = ((result << 5) + result) ^ string[i];
}
return result;
}
template<size_t N>
constexpr uint32_t hash_string_const(char const (&string)[N])
inline uint32_t hash_string(const char* string)
{
unsigned long result = 5381;
for (size_t i = 0; i < N-1; i++) {
for (size_t i = 0; i < strlen(string); i++)
{
result = ((result << 5) + result) ^ string[i];
}
return result;
}
struct fxNativeContext {
template <size_t N> constexpr uint32_t hash_string_const(char const (&string)[N])
{
unsigned long result = 5381;
for (size_t i = 0; i < N - 1; i++)
{
result = ((result << 5) + result) ^ string[i];
}
return result;
}
struct fxNativeContext
{
int numArguments;
int numResults;
int hasError;
@@ -79,9 +84,14 @@ struct fxNativeContext {
typedef void (*CallbackT)(fxNativeContext*);
class ScriptContext {
class ScriptContext
{
public:
enum { MaxArguments = 32, ArgumentSize = sizeof(uint64_t) };
enum
{
MaxArguments = 32,
ArgumentSize = sizeof(uint64_t)
};
protected:
void* m_argumentBuffer;
@@ -103,50 +113,52 @@ public:
void Reset();
public:
template <int... Is>
struct index {};
template <int... Is> struct index
{
};
template <int N, int... Is>
struct gen_seq : gen_seq<N - 1, N - 1, Is...> {};
template <int N, int... Is> struct gen_seq : gen_seq<N - 1, N - 1, Is...>
{
};
template <int... Is>
struct gen_seq<0, Is...> : index<Is...> {};
template <int... Is> struct gen_seq<0, Is...> : index<Is...>
{
};
template <typename... Ts>
inline const std::tuple<Ts...> GetArguments() {
return GetArgumentsImpl<Ts...>(gen_seq<sizeof...(Ts)>());
}
template <typename... Ts> inline const std::tuple<Ts...> GetArguments() { return GetArgumentsImpl<Ts...>(gen_seq<sizeof...(Ts)>()); }
template <typename... Ts, int... Is>
inline const std::tuple<Ts...> GetArgumentsImpl(index<Is...>) {
template <typename... Ts, int... Is> inline const std::tuple<Ts...> GetArgumentsImpl(index<Is...>)
{
return std::make_tuple(GetArgument<Ts>(Is)...);
}
template <typename T>
inline const T &GetArgument(int index) {
template <typename T> inline const T& GetArgument(int index)
{
auto functionData = (uint64_t*)m_argumentBuffer;
return *reinterpret_cast<T*>(&functionData[index]);
}
template <typename T>
inline void SetArgument(int index, const T &value) {
template <typename T> inline void SetArgument(int index, const T& value)
{
auto functionData = (uint64_t*)m_argumentBuffer;
static_assert(sizeof(T) <= ArgumentSize, "Argument size of T");
if (sizeof(T) < ArgumentSize) {
if (sizeof(T) < ArgumentSize)
{
*reinterpret_cast<uint64_t*>(&functionData[index]) = 0;
}
*reinterpret_cast<T*>(&functionData[index]) = value;
}
template <typename T>
inline const T &CheckArgument(int index) {
template <typename T> inline const T& CheckArgument(int index)
{
const auto& argument = GetArgument<T>(index);
if (argument == T()) {
if (argument == T())
{
throw std::runtime_error("Argument at index %d was null.");
}
@@ -155,13 +167,14 @@ public:
inline int GetArgumentCount() { return m_numArguments; }
template <typename T>
inline void Push(const T &value) {
template <typename T> inline void Push(const T& value)
{
auto functionData = (uint64_t*)m_argumentBuffer;
static_assert(sizeof(T) <= ArgumentSize, "Argument size of T");
if (sizeof(T) < ArgumentSize) {
if (sizeof(T) < ArgumentSize)
{
*reinterpret_cast<uint64_t*>(&functionData[m_numArguments]) = 0;
}
@@ -170,17 +183,19 @@ public:
m_native_context->numArguments++;
}
inline void PushString(const char *value) {
inline void PushString(const char* value)
{
auto functionData = (uint64_t*)m_argumentBuffer;
*reinterpret_cast<const char**>(&functionData[m_numArguments]) = value;
}
template <typename T>
inline void SetResult(const T &value) {
template <typename T> inline void SetResult(const T& value)
{
auto functionData = (uint64_t*)m_result;
if (sizeof(T) < ArgumentSize) {
if (sizeof(T) < ArgumentSize)
{
*reinterpret_cast<uint64_t*>(&functionData[0]) = 0;
}
@@ -190,8 +205,8 @@ public:
m_numArguments = 0;
}
template <typename T>
inline T GetResult() {
template <typename T> inline T GetResult()
{
auto functionData = (uint64_t*)m_result;
return *reinterpret_cast<T*>(functionData);
@@ -202,9 +217,11 @@ public:
inline int GetNumArguments() { return m_native_context->numArguments; }
};
class ScriptContextRaw : public ScriptContext {
class ScriptContextRaw : public ScriptContext
{
public:
inline ScriptContextRaw(fxNativeContext &context) {
inline ScriptContextRaw(fxNativeContext& context)
{
m_argumentBuffer = context.arguments;
m_numArguments = context.numArguments;
@@ -215,7 +232,8 @@ public:
m_result = &context.result;
}
inline ScriptContextRaw() {
inline ScriptContextRaw()
{
m_numResults = 0;
m_numArguments = 0;
}
@@ -223,10 +241,10 @@ public:
using TNativeHandler = std::function<void(ScriptContext&)>;
template <typename T>
using TypedTNativeHandler = T(ScriptContext &);
template <typename T> using TypedTNativeHandler = T(ScriptContext&);
class ScriptEngine {
class ScriptEngine
{
public:
static tl::optional<TNativeHandler> GetNativeHandler(uint64_t nativeIdentifier);
static tl::optional<TNativeHandler> GetNativeHandler(std::string name);
@@ -235,11 +253,12 @@ public:
static void RegisterNativeHandlerInt(uint64_t nativeIdentifier, TNativeHandler function);
template <typename T>
static void RegisterNativeHandler(const char *nativeName, TypedTNativeHandler<T> function) {
template <typename T> static void RegisterNativeHandler(const char* nativeName, TypedTNativeHandler<T> function)
{
auto lambda = [=](counterstrikesharp::ScriptContext& context) {
auto value = function(context);
if (!context.HasError()) {
if (!context.HasError())
{
context.SetResult(value);
}
};
@@ -247,7 +266,8 @@ public:
RegisterNativeHandlerInt(hash_string(nativeName), lambda);
}
static void RegisterNativeHandler(const char *nativeName, TypedTNativeHandler<void> function) {
static void RegisterNativeHandler(const char* nativeName, TypedTNativeHandler<void> function)
{
RegisterNativeHandlerInt(hash_string(nativeName), function);
}

View File

@@ -23,7 +23,8 @@ std::wstring widen(const std::string& str)
{
std::wostringstream wstm;
const auto& ctfacet = std::use_facet<std::ctype<wchar_t>>(wstm.getloc());
for (size_t i = 0; i < str.size(); ++i) {
for (size_t i = 0; i < str.size(); ++i)
{
wstm << ctfacet.widen(str[i]);
}
return wstm.str();
@@ -39,9 +40,10 @@ std::string narrow(const std::wstring& str)
// Correct code.
const auto& ctfacet = std::use_facet<std::ctype<wchar_t>>(stm.getloc());
for (size_t i = 0; i < str.size(); ++i) {
for (size_t i = 0; i < str.size(); ++i)
{
stm << ctfacet.narrow(str[i], 0);
}
return stm.str();
}
}
} // namespace counterstrikesharp

View File

@@ -23,28 +23,31 @@
#define CALL_VIRTUAL(retType, idx, ...) vmt::CallVirtual<retType>(idx, __VA_ARGS__)
namespace vmt {
template <typename T = void *>
inline T GetVMethod(uint32 uIndex, void *pClass) {
if (!pClass) {
template <typename T = void*> inline T GetVMethod(uint32 uIndex, void* pClass)
{
if (!pClass)
{
return T();
}
void** pVTable = *static_cast<void***>(pClass);
if (!pVTable) {
if (!pVTable)
{
return T();
}
return reinterpret_cast<T>(pVTable[uIndex]);
}
template <typename T, typename... Args>
inline T CallVirtual(uint32 uIndex, void *pClass, Args... args) {
template <typename T, typename... Args> inline T CallVirtual(uint32 uIndex, void* pClass, Args... args)
{
#ifdef _WIN32
auto pFunc = GetVMethod<T(__thiscall*)(void*, Args...)>(uIndex, pClass);
#else
auto pFunc = GetVMethod<T (*)(void*, Args...)>(uIndex, pClass);
#endif
if (!pFunc) {
if (!pFunc)
{
return T();
}