Compare commits

...

3 Commits

Author SHA1 Message Date
Roflmuffin
e4cb380a61 chore: update cmakelists 2024-04-12 15:40:07 +10:00
Roflmuffin
7b84a216b7 chore: reduce usage of global header, add more forward declarations 2024-04-12 15:31:23 +10:00
Roflmuffin
965556346a chore: add cmakelists & cmake formatting 2024-04-12 14:14:45 +10:00
23 changed files with 600 additions and 522 deletions

View File

@@ -84,6 +84,7 @@ Checks: >
-readability-function-cognitive-complexity,
-readability-convert-member-functions-to-static,
-readability-implicit-bool-conversion,
-readability-redundant-access-specifiers,
-bugprone-narrowing-conversions,
-bugprone-easily-swappable-parameters,
-bugprone-implicit-widening-of-multiplication-result,
@@ -114,4 +115,3 @@ CheckOptions:
readability-identifier-naming.PointerParameterHungarianPrefix: On
readability-identifier-naming.PointerParameterCase: CamelCase
readability-identifier-naming.HungarianNotation.UserDefinedType.std::string: s

View File

@@ -12,3 +12,23 @@ trim_trailing_whitespace = true
[*.json]
indent_size = 2
[{CMakeLists.txt,*.cmake,*.rst}]
indent_size = 2
indent_style = space
ij_continuation_indent_size = 4
ij_cmake_align_command_call_r_par = false
ij_cmake_align_control_flow_r_par = false
ij_cmake_align_multiline_parameters_in_calls = true
ij_cmake_force_commands_case = 1
ij_cmake_keep_blank_lines_in_code = 1
ij_cmake_space_before_for_parentheses = false
ij_cmake_space_before_if_parentheses = false
ij_cmake_space_before_method_call_parentheses = false
ij_cmake_space_before_method_parentheses = false
ij_cmake_space_before_while_parentheses = false
ij_cmake_spaces_within_for_parentheses = false
ij_cmake_spaces_within_if_parentheses = false
ij_cmake_spaces_within_method_call_parentheses = false
ij_cmake_spaces_within_method_parentheses = false
ij_cmake_spaces_within_while_parentheses = false

View File

@@ -13,7 +13,7 @@ add_subdirectory(libraries/DynoHook)
set_property(TARGET dynohook PROPERTY DYNO_ARCH_X86 64)
set_property(TARGET funchook-static PROPERTY POSITION_INDEPENDENT_CODE ON)
SET(SOURCE_FILES
set(SOURCE_FILES
src/mm_plugin.cpp
src/mm_plugin.h
libraries/hl2sdk-cs2/tier1/convar.cpp
@@ -95,66 +95,65 @@ SET(SOURCE_FILES
src/core/game_system.cpp
)
if (LINUX)
# memoverride.cpp is not usable on CMake Windows, cuz CMake default link libraries (seems) always link ucrt.lib
set(SOURCE_FILES
${SOURCE_FILES}
libraries/hl2sdk-cs2/public/tier0/memoverride.cpp
)
if(LINUX)
# memoverride.cpp is not usable on CMake Windows, cuz CMake default link libraries (seems) always link ucrt.lib
set(SOURCE_FILES
${SOURCE_FILES}
libraries/hl2sdk-cs2/public/tier0/memoverride.cpp
)
endif()
set(PROTO_DIRS -I${CMAKE_CURRENT_SOURCE_DIR}/libraries/Protobufs/csgo)
file(GLOB PROTOS "${CMAKE_CURRENT_SOURCE_DIR}/libraries/Protobufs/csgo/*.proto")
## Generate protobuf source & headers
if (LINUX)
set(PROTOC_EXECUTABLE ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2/devtools/bin/linux/protoc)
if(LINUX)
set(PROTOC_EXECUTABLE ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2/devtools/bin/linux/protoc)
elseif(WIN32)
set(PROTOC_EXECUTABLE ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2/devtools/bin/protoc.exe)
set(PROTOC_EXECUTABLE ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2/devtools/bin/protoc.exe)
endif()
add_custom_command(
OUTPUT protobuf_output_stamp
COMMAND ${PROTOC_EXECUTABLE} --proto_path=thirdparty/protobuf-3.21.8/src --proto_path=common --cpp_out=common common/network_connection.proto
COMMENT "Generating protobuf file"
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2
VERBATIM
OUTPUT protobuf_output_stamp
COMMAND ${PROTOC_EXECUTABLE} --proto_path=thirdparty/protobuf-3.21.8/src --proto_path=common --cpp_out=common common/network_connection.proto
COMMENT "Generating protobuf file"
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2
VERBATIM
)
SET(SOURCE_FILES ${SOURCE_FILES} protobuf_output_stamp)
# set(SOURCE_FILES ${SOURCE_FILES} protobuf_output_stamp)
# Sources
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${NATIVES_SOURCES} ${CONVERSIONS_SOURCES} ${CONVERSIONS_HEADERS})
target_include_directories(
${PROJECT_NAME}
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/src/core/cs2_sdk
${PROJECT_NAME}
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/src/core/cs2_sdk
)
if (LINUX)
include("makefiles/linux.base.cmake")
set_target_properties(${PROJECT_NAME} PROPERTIES
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/addons/counterstrikesharp/bin/linuxsteamrt64"
)
if(LINUX)
include("makefiles/linux.base.cmake")
set_target_properties(
${PROJECT_NAME} PROPERTIES
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/addons/counterstrikesharp/bin/linuxsteamrt64"
)
elseif(WIN32)
include("makefiles/windows.base.cmake")
set_target_properties(${PROJECT_NAME} PROPERTIES
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/addons/counterstrikesharp/bin/win64"
)
include("makefiles/windows.base.cmake")
set_target_properties(
${PROJECT_NAME} PROPERTIES
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/addons/counterstrikesharp/bin/win64"
)
endif()
# Libraries
target_link_libraries(${PROJECT_NAME} ${COUNTER_STRIKE_SHARP_LINK_LIBRARIES})
add_custom_command(
TARGET ${PROJECT_NAME} PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/configs ${CMAKE_BINARY_DIR}
)
TARGET ${PROJECT_NAME} PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/configs ${CMAKE_BINARY_DIR}
)

View File

@@ -1,7 +1,6 @@
#set(_ITERATOR_DEBUG_LEVEL 2)
add_definitions(-D_LINUX -DPOSIX -DLINUX -DGNUC -DCOMPILER_GCC -DPLATFORM_64BITS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Dstrnicmp=strncasecmp -D_snprintf=snprintf")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp")
@@ -16,16 +15,16 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-offsetof -Wno-reorder")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpmath=sse -msse -fno-strict-aliasing")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-threadsafe-statics -v -fvisibility=default")
SET(
COUNTER_STRIKE_SHARP_LINK_LIBRARIES
${SOURCESDK_LIB}/linux64/libtier0.so
${SOURCESDK_LIB}/linux64/tier1.a
${SOURCESDK_LIB}/linux64/interfaces.a
${SOURCESDK_LIB}/linux64/mathlib.a
spdlog
dynload_s
dyncall_s
distorm
funchook-static
dynohook
)
set(
COUNTER_STRIKE_SHARP_LINK_LIBRARIES
${SOURCESDK_LIB}/linux64/libtier0.so
${SOURCESDK_LIB}/linux64/tier1.a
${SOURCESDK_LIB}/linux64/interfaces.a
${SOURCESDK_LIB}/linux64/mathlib.a
spdlog
dynload_s
dyncall_s
distorm
funchook-static
dynohook
)

View File

@@ -1,9 +1,9 @@
if (UNIX AND NOT APPLE)
set(LINUX TRUE)
if(UNIX AND NOT APPLE)
set(LINUX TRUE)
endif()
if (WIN32 AND NOT MSVC)
message(FATAL "MSVC restricted.")
if(WIN32 AND NOT MSVC)
message(FATAL "MSVC restricted.")
endif()
set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING
@@ -14,9 +14,9 @@ set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING
# TODO: Use C++20 instead.
set(CMAKE_CXX_STANDARD 17)
if (LINUX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
if(LINUX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
endif()
set(CMAKE_STATIC_LIBRARY_PREFIX "")
@@ -30,15 +30,15 @@ set(SOURCESDK_LIB ${SOURCESDK}/lib)
add_definitions(-DMETA_IS_SOURCE2)
if(DEFINED ENV{GITHUB_SHA_SHORT})
add_definitions(-DGITHUB_SHA="$ENV{GITHUB_SHA_SHORT}")
add_definitions(-DGITHUB_SHA="$ENV{GITHUB_SHA_SHORT}")
else()
add_definitions(-DGITHUB_SHA="Local")
add_definitions(-DGITHUB_SHA="Local")
endif()
if(DEFINED ENV{BUILD_NUMBER})
add_definitions(-DBUILD_NUMBER="$ENV{BUILD_NUMBER}")
add_definitions(-DBUILD_NUMBER="$ENV{BUILD_NUMBER}")
else()
add_definitions(-DBUILD_NUMBER="0")
add_definitions(-DBUILD_NUMBER="0")
endif()
include_directories(
@@ -68,4 +68,4 @@ include_directories(
libraries
)
include(${CMAKE_CURRENT_LIST_DIR}/metamod/configure_metamod.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/metamod/configure_metamod.cmake)

View File

@@ -18,4 +18,4 @@ set(COUNTER_STRIKE_SHARP_LINK_LIBRARIES
distorm
funchook-static
dynohook
)
)

View File

@@ -1,22 +1,24 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "core/coreconfig.h"
#include <fstream>
#include "core/log.h"
#include "core/coreconfig.h"
namespace counterstrikesharp {
@@ -28,11 +30,13 @@ bool CCoreConfig::Init(char* conf_error, int conf_error_size)
{
std::ifstream ifs(std::string(m_sPath + ".json"));
if (!ifs) {
if (!ifs)
{
std::ifstream exampleIfs(std::string(m_sPath + ".example.json"));
if (!exampleIfs) {
V_snprintf(conf_error, conf_error_size, "CoreConfig file not found.");
if (!exampleIfs)
{
snprintf(conf_error, conf_error_size, "CoreConfig file not found.");
return false;
}
@@ -46,25 +50,25 @@ bool CCoreConfig::Init(char* conf_error, int conf_error_size)
m_json = json::parse(ifs);
try {
try
{
PublicChatTrigger = m_json.value("PublicChatTrigger", PublicChatTrigger);
SilentChatTrigger = m_json.value("SilentChatTrigger", SilentChatTrigger);
FollowCS2ServerGuidelines = m_json.value("FollowCS2ServerGuidelines", FollowCS2ServerGuidelines);
PluginHotReloadEnabled = m_json.value("PluginHotReloadEnabled", PluginHotReloadEnabled);
PluginAutoLoadEnabled = m_json.value("PluginAutoLoadEnabled", PluginAutoLoadEnabled);
ServerLanguage = m_json.value("ServerLanguage", ServerLanguage);
} catch (const std::exception& ex) {
V_snprintf(conf_error, conf_error_size, "Failed to parse CoreConfig file: %s", ex.what());
}
catch (const std::exception& ex)
{
snprintf(conf_error, conf_error_size, "Failed to parse CoreConfig file: %s", ex.what());
return false;
}
return true;
}
const std::string CCoreConfig::GetPath() const
{
return m_sPath;
}
const std::string CCoreConfig::GetPath() const { return m_sPath; }
bool CCoreConfig::IsTriggerInternal(std::vector<std::string> triggers, const std::string& message, std::string& prefix) const
{
@@ -90,4 +94,4 @@ bool CCoreConfig::IsPublicChatTrigger(const std::string& message, std::string& p
{
return IsTriggerInternal(PublicChatTrigger, message, prefix);
}
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -1,25 +1,26 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#pragma once
#include "core/globals.h"
#include <string>
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
namespace counterstrikesharp {
class CCoreConfig

View File

@@ -29,13 +29,18 @@
#include "core/function.h"
#include "core/log.h"
#include "dyncall/dyncall/dyncall.h"
// clang-format off
#include "pch.h"
#include "dynohook/core.h"
#include "dynohook/manager.h"
#include "dynohook/conventions/x64/x64SystemVcall.h"
// clang-format on
#include <map>
#include "core/log.h"
#include "dyncall/dyncall/dyncall.h"
#include "globals.h"
namespace counterstrikesharp {
@@ -47,30 +52,30 @@ std::map<dyno::Hook*, ValveFunction*> g_HookMap;
// ============================================================================
int GetDynCallConvention(Convention_t eConv)
{
switch (eConv) {
case CONV_CUSTOM:
return -1;
case CONV_CDECL:
return DC_CALL_C_DEFAULT;
case CONV_THISCALL:
switch (eConv)
{
case CONV_CUSTOM:
return -1;
case CONV_CDECL:
return DC_CALL_C_DEFAULT;
case CONV_THISCALL:
#ifdef _WIN32
return DC_CALL_C_X86_WIN32_THIS_MS;
return DC_CALL_C_X86_WIN32_THIS_MS;
#else
return DC_CALL_C_X86_WIN32_THIS_GNU;
return DC_CALL_C_X86_WIN32_THIS_GNU;
#endif
#ifdef _WIN32
case CONV_STDCALL:
return DC_CALL_C_X86_WIN32_STD;
case CONV_FASTCALL:
return DC_CALL_C_X86_WIN32_FAST_MS;
case CONV_STDCALL:
return DC_CALL_C_X86_WIN32_STD;
case CONV_FASTCALL:
return DC_CALL_C_X86_WIN32_FAST_MS;
#endif
}
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;
@@ -82,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)
{
@@ -96,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);
@@ -113,119 +113,120 @@ 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]) {
case DATA_TYPE_BOOL:
dcArgBool(g_pCallVM, script_context.GetArgument<bool>(contextIndex));
break;
case DATA_TYPE_CHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<char>(contextIndex));
break;
case DATA_TYPE_UCHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<unsigned char>(contextIndex));
break;
case DATA_TYPE_SHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<short>(contextIndex));
break;
case DATA_TYPE_USHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<unsigned short>(contextIndex));
break;
case DATA_TYPE_INT:
dcArgInt(g_pCallVM, script_context.GetArgument<int>(contextIndex));
break;
case DATA_TYPE_UINT:
dcArgInt(g_pCallVM, script_context.GetArgument<unsigned int>(contextIndex));
break;
case DATA_TYPE_LONG:
dcArgLong(g_pCallVM, script_context.GetArgument<long>(contextIndex));
break;
case DATA_TYPE_ULONG:
dcArgLong(g_pCallVM, script_context.GetArgument<unsigned long>(contextIndex));
break;
case DATA_TYPE_LONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<long long>(contextIndex));
break;
case DATA_TYPE_ULONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<unsigned long long>(contextIndex));
break;
case DATA_TYPE_FLOAT:
dcArgFloat(g_pCallVM, script_context.GetArgument<float>(contextIndex));
break;
case DATA_TYPE_DOUBLE:
dcArgDouble(g_pCallVM, script_context.GetArgument<double>(contextIndex));
break;
case DATA_TYPE_POINTER:
dcArgPointer(g_pCallVM, script_context.GetArgument<void*>(contextIndex));
break;
case DATA_TYPE_STRING:
dcArgPointer(g_pCallVM, (void*)script_context.GetArgument<const char*>(contextIndex));
break;
default:
assert(!"Unknown function parameter type!");
break;
switch (m_Args[i])
{
case DATA_TYPE_BOOL:
dcArgBool(g_pCallVM, script_context.GetArgument<bool>(contextIndex));
break;
case DATA_TYPE_CHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<char>(contextIndex));
break;
case DATA_TYPE_UCHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<unsigned char>(contextIndex));
break;
case DATA_TYPE_SHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<short>(contextIndex));
break;
case DATA_TYPE_USHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<unsigned short>(contextIndex));
break;
case DATA_TYPE_INT:
dcArgInt(g_pCallVM, script_context.GetArgument<int>(contextIndex));
break;
case DATA_TYPE_UINT:
dcArgInt(g_pCallVM, script_context.GetArgument<unsigned int>(contextIndex));
break;
case DATA_TYPE_LONG:
dcArgLong(g_pCallVM, script_context.GetArgument<long>(contextIndex));
break;
case DATA_TYPE_ULONG:
dcArgLong(g_pCallVM, script_context.GetArgument<unsigned long>(contextIndex));
break;
case DATA_TYPE_LONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<long long>(contextIndex));
break;
case DATA_TYPE_ULONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<unsigned long long>(contextIndex));
break;
case DATA_TYPE_FLOAT:
dcArgFloat(g_pCallVM, script_context.GetArgument<float>(contextIndex));
break;
case DATA_TYPE_DOUBLE:
dcArgDouble(g_pCallVM, script_context.GetArgument<double>(contextIndex));
break;
case DATA_TYPE_POINTER:
dcArgPointer(g_pCallVM, script_context.GetArgument<void*>(contextIndex));
break;
case DATA_TYPE_STRING:
dcArgPointer(g_pCallVM, (void*)script_context.GetArgument<const char*>(contextIndex));
break;
default:
assert(!"Unknown function parameter type!");
break;
}
}
switch (m_eReturnType) {
case DATA_TYPE_VOID:
CallHelperVoid(g_pCallVM, m_ulAddr);
break;
case DATA_TYPE_BOOL:
script_context.SetResult(CallHelper<bool>(dcCallBool, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_CHAR:
script_context.SetResult(CallHelper<char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UCHAR:
script_context.SetResult(CallHelper<unsigned char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_SHORT:
script_context.SetResult(CallHelper<short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_USHORT:
script_context.SetResult(CallHelper<unsigned short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_INT:
script_context.SetResult(CallHelper<int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UINT:
script_context.SetResult(CallHelper<unsigned int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG:
script_context.SetResult(CallHelper<long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_ULONG:
script_context.SetResult(CallHelper<unsigned long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG_LONG:
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));
break;
case DATA_TYPE_FLOAT:
script_context.SetResult(CallHelper<float>(dcCallFloat, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_DOUBLE:
script_context.SetResult(CallHelper<double>(dcCallDouble, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_POINTER:
script_context.SetResult(CallHelper<void*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_STRING:
script_context.SetResult(CallHelper<const char*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
default:
assert(!"Unknown function return type!");
break;
switch (m_eReturnType)
{
case DATA_TYPE_VOID:
CallHelperVoid(g_pCallVM, m_ulAddr);
break;
case DATA_TYPE_BOOL:
script_context.SetResult(CallHelper<bool>(dcCallBool, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_CHAR:
script_context.SetResult(CallHelper<char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UCHAR:
script_context.SetResult(CallHelper<unsigned char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_SHORT:
script_context.SetResult(CallHelper<short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_USHORT:
script_context.SetResult(CallHelper<unsigned short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_INT:
script_context.SetResult(CallHelper<int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UINT:
script_context.SetResult(CallHelper<unsigned int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG:
script_context.SetResult(CallHelper<long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_ULONG:
script_context.SetResult(CallHelper<unsigned long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG_LONG:
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));
break;
case DATA_TYPE_FLOAT:
script_context.SetResult(CallHelper<float>(dcCallFloat, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_DOUBLE:
script_context.SetResult(CallHelper<double>(dcCallDouble, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_POINTER:
script_context.SetResult(CallHelper<void*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_STRING:
script_context.SetResult(CallHelper<const char*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
default:
assert(!"Unknown function return type!");
break;
}
}
@@ -235,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;
}
}
@@ -264,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)));
}
@@ -275,42 +278,51 @@ void ValveFunction::AddHook(CallbackT callable, bool post)
{
dyno::HookManager& manager = dyno::HookManager::Get();
dyno::Hook* hook = manager.hook((void*)m_ulAddr, [this] {
return new dyno::x64SystemVcall(ConvertArgsToDynoHook(m_Args),
static_cast<dyno::DataType>(this->m_eReturnType));
return new dyno::x64SystemVcall(ConvertArgsToDynoHook(m_Args), static_cast<dyno::DataType>(this->m_eReturnType));
});
g_HookMap[hook] = this;
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] {
return new dyno::x64SystemVcall(ConvertArgsToDynoHook(m_Args),
static_cast<dyno::DataType>(this->m_eReturnType));
return new dyno::x64SystemVcall(ConvertArgsToDynoHook(m_Args), static_cast<dyno::DataType>(this->m_eReturnType));
});
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);
}
}
}
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -32,7 +32,6 @@
#include "scripting/callback_manager.h"
#include "scripting/script_engine.h"
#include <map>
namespace dyno {
class Hook;
@@ -40,7 +39,8 @@ class Hook;
namespace counterstrikesharp {
enum DataType_t {
enum DataType_t
{
DATA_TYPE_VOID,
DATA_TYPE_BOOL,
DATA_TYPE_CHAR,
@@ -60,7 +60,8 @@ enum DataType_t {
DATA_TYPE_VARIANT
};
enum Protection_t {
enum Protection_t
{
PROTECTION_NONE,
PROTECTION_READ,
PROTECTION_READ_WRITE,
@@ -69,19 +70,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 {
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);
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();
@@ -110,4 +112,4 @@ public:
ScriptCallback* m_postcallback = nullptr;
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -1,19 +1,11 @@
#pragma once
#define protected public
#define private public
#include <tier1/convar.h>
#undef protected
#undef private
#include <sourcehook/sourcehook.h>
#include <thread>
#include "ISmmAPI.h"
#include "eiface.h"
#include "iserver.h"
#include <sourcehook/sourcehook.h>
class IGameEventManager2;
class IVEngineServer2;
class IPlayerInfoManager;
class IBotManager;
class IServerPluginHelpers;
@@ -38,6 +30,15 @@ class CounterStrikeSharpMMPlugin;
class CGameEntitySystem;
class IGameEventListener2;
class CSchemaSystem;
class CPlayerSlot;
class ISource2GameEntities;
class ISource2GameClients;
class ISource2Server;
class INetworkServerService;
namespace SourceMM {
class ISmmAPI;
}
namespace counterstrikesharp {
class EntityListener;
@@ -61,34 +62,34 @@ class CGameConfig;
namespace globals {
extern IVEngineServer *engine;
extern IGameEventManager2 *gameEventManager;
extern IPlayerInfoManager *playerinfoManager;
extern IBotManager *botManager;
extern IServerPluginHelpers *helpers;
extern IUniformRandomStream *randomStream;
extern IEngineTrace *engineTrace;
extern IEngineSound *engineSound;
extern IEngineServiceMgr *engineServiceManager;
extern INetworkStringTableContainer *netStringTables;
extern CGlobalVars *globalVars;
extern IFileSystem *fileSystem;
extern IServerGameDLL *serverGameDll;
extern IServerGameClients *serverGameClients;
extern INetworkServerService *networkServerService;
extern CSchemaSystem *schemaSystem;
extern IServerTools *serverTools;
extern IPhysics *physics;
extern IPhysicsCollision *physicsCollision;
extern IPhysicsSurfaceProps *physicsSurfaceProps;
extern IMDLCache *modelCache;
extern IVoiceServer *voiceServer;
extern IVEngineServer2* engine;
extern IGameEventManager2* gameEventManager;
extern IPlayerInfoManager* playerinfoManager;
extern IBotManager* botManager;
extern IServerPluginHelpers* helpers;
extern IUniformRandomStream* randomStream;
extern IEngineTrace* engineTrace;
extern IEngineSound* engineSound;
extern IEngineServiceMgr* engineServiceManager;
extern INetworkStringTableContainer* netStringTables;
extern CGlobalVars* globalVars;
extern IFileSystem* fileSystem;
extern ISource2Server* serverGameDll;
extern ISource2GameClients* serverGameClients;
extern INetworkServerService* networkServerService;
extern CSchemaSystem* schemaSystem;
extern IServerTools* serverTools;
extern IPhysics* physics;
extern IPhysicsCollision* physicsCollision;
extern IPhysicsSurfaceProps* physicsSurfaceProps;
extern IMDLCache* modelCache;
extern IVoiceServer* voiceServer;
extern CDotNetManager dotnetManager;
extern ICvar *cvars;
extern ISource2Server *server;
extern CGlobalEntityList *globalEntityList;
extern ICvar* cvars;
extern ISource2Server* server;
extern CGlobalEntityList* globalEntityList;
extern EntityListener entityListener;
extern CGameEntitySystem *entitySystem;
extern CGameEntitySystem* entitySystem;
extern EventManager eventManager;
extern UserMessageManager userMessageManager;
@@ -106,17 +107,17 @@ extern VoiceManager voiceManager;
extern TickScheduler tickScheduler;
extern HookManager hookManager;
extern SourceHook::ISourceHook *source_hook;
extern SourceHook::ISourceHook* source_hook;
extern int source_hook_pluginid;
extern IGameEventSystem *gameEventSystem;
extern CounterStrikeSharpMMPlugin *mmPlugin;
extern ISmmAPI *ismm;
extern IGameEventSystem* gameEventSystem;
extern CounterStrikeSharpMMPlugin* mmPlugin;
extern SourceMM::ISmmAPI* ismm;
extern CCoreConfig* coreConfig;
extern CGameConfig* gameConfig;
extern const float engine_fixed_tick_interval;
typedef IGameEventListener2 *GetLegacyGameEventListener_t(CPlayerSlot slot);
typedef IGameEventListener2* GetLegacyGameEventListener_t(CPlayerSlot slot);
extern bool gameLoopInitialized;
extern GetLegacyGameEventListener_t* GetLegacyGameEventListener;
@@ -125,22 +126,22 @@ extern std::thread::id gameThreadId;
void Initialize();
// Should only be called within the active game loop (i e map should be loaded
// and active) otherwise that'll be nullptr!
CGlobalVars *getGlobalVars();
} // namespace globals
CGlobalVars* getGlobalVars();
} // namespace globals
namespace modules {
class CModule;
extern CModule *engine;
extern CModule *tier0;
extern CModule *server;
extern CModule *schemasystem;
extern CModule *vscript;
} // namespace modules
extern CModule* engine;
extern CModule* tier0;
extern CModule* server;
extern CModule* schemasystem;
extern CModule* vscript;
} // namespace modules
} // namespace counterstrikesharp
} // namespace counterstrikesharp
#undef SH_GLOB_SHPTR
#define SH_GLOB_SHPTR counterstrikesharp::globals::source_hook
#undef SH_GLOB_PLUGPTR
#define SH_GLOB_PLUGPTR counterstrikesharp::globals::source_hook_pluginid
#define SH_GLOB_PLUGPTR counterstrikesharp::globals::source_hook_pluginid

View File

@@ -19,10 +19,13 @@
#include <map>
#include <vector>
#include "core/globals.h"
#include "core/global_listener.h"
#include "core/globals.h"
#include "scripting/script_engine.h"
class CBaseEntity;
class CCommand;
namespace counterstrikesharp {
class ScriptCallback;
@@ -54,16 +57,15 @@ class ChatManager : public GlobalClass
bool OnSayCommandPre(CBaseEntity* pController, CCommand& args);
void OnSayCommandPost(CBaseEntity* pController, CCommand& args);
private:
void InternalDispatch(CBaseEntity* pPlayerController, const char* szTriggerPhrase,
CCommand& pFullCommand);
void InternalDispatch(CBaseEntity* pPlayerController, const char* szTriggerPhrase, CCommand& pFullCommand);
std::vector<ChatCommandInfo*> m_cmd_list;
std::map<std::string, ChatCommandInfo*> m_cmd_lookup;
};
static void DetourHostSay(CBaseEntity* pController, CCommand& args, bool teamonly, int unk1,
const char* unk2);
static void DetourHostSay(CBaseEntity* pController, CCommand& args, bool teamonly, int unk1, const char* unk2);
static HostSay m_pHostSay = nullptr;
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -32,46 +32,47 @@
#pragma once
#include <map>
#include <string>
#include <vector>
#include "core/globals.h"
#include "convar.h"
#include "core/global_listener.h"
#include "scripting/script_engine.h"
#include <string>
#include "playerslot.h"
struct CaseInsensitiveComparator {
bool operator()(const std::string& lhs, const std::string& rhs) const {
return std::lexicographical_compare(
lhs.begin(), lhs.end(),
rhs.begin(), rhs.end(),
[](char a, char b) { return std::tolower(a) < std::tolower(b); }
);
struct CaseInsensitiveComparator
{
bool operator()(const std::string& lhs, const std::string& rhs) const
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), [](char a, char b) {
return std::tolower(a) < std::tolower(b);
});
}
};
namespace counterstrikesharp {
class ScriptCallback;
enum CommandCallingContext {
enum CommandCallingContext
{
Console = 0,
Chat = 1,
};
class ConCommandInfo {
class ConCommandInfo
{
friend class ConCommandManager;
public:
ConCommandInfo();
ConCommandInfo(bool bNoCallbacks);
public:
ConCommandInfo();
ConCommandInfo(bool bNoCallbacks);
~ConCommandInfo();
public:
public:
void HookChange(CallbackT callback, bool post);
void UnhookChange(CallbackT callback, bool post);
ScriptCallback* GetCallback() { return callback_pre; }
private:
private:
ConCommandRefAbstract p_cmd;
ConCommand* command;
ScriptCallback* callback_pre;
@@ -79,10 +80,11 @@ private:
bool server_only;
};
class ConCommandManager : public GlobalClass {
class ConCommandManager : public GlobalClass
{
friend class ConCommandInfo;
public:
public:
ConCommandManager();
~ConCommandManager();
void OnAllInitialized() override;
@@ -95,15 +97,16 @@ public:
bool RemoveValveCommand(const char* name);
void Hook_DispatchConCommand(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args);
void Hook_DispatchConCommand_Post(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args);
HookResult ExecuteCommandCallbacks(const char* name, const CCommandContext& ctx,
const CCommand& args, HookMode mode, CommandCallingContext callingContext);
HookResult ExecuteCommandCallbacks(
const char* name, const CCommandContext& ctx, const CCommand& args, HookMode mode, CommandCallingContext callingContext);
CommandCallingContext GetCommandCallingContext(CCommand* args);
private:
private:
std::vector<ConCommandInfo*> m_cmd_list;
std::map<std::string, ConCommandInfo*, CaseInsensitiveComparator> m_cmd_lookup;
std::map<const CCommand*, CommandCallingContext> m_cmd_contexts;
ConCommandInfo m_global_cmd = ConCommandInfo(true);
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -33,12 +33,20 @@
#include <string>
#include "bitvec.h"
#include "const.h"
#include "core/global_listener.h"
#include "core/globals.h"
#include "network_connection.pb.h"
#include "playerslot.h"
class CBaseEntity;
class INetChannelInfo;
class IPlayerInfo;
class CSteamID;
class QAngle;
class Vector;
class CCommand;
struct edict_t;
namespace counterstrikesharp {
@@ -143,15 +151,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;
@@ -188,4 +196,4 @@ class PlayerManager : public GlobalClass
ScriptCallback* m_on_client_authorized_callback;
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -16,10 +16,12 @@
#pragma once
#include "core/globals.h"
#include "core/global_listener.h"
#include "scripting/script_engine.h"
class CCommand;
class CPlayerSlot;
namespace counterstrikesharp {
class ScriptCallback;
@@ -32,7 +34,8 @@ class VoiceManager : public GlobalClass
void OnShutdown() override;
bool SetClientListening(CPlayerSlot iReceiver, CPlayerSlot iSender, bool bListen);
void OnClientCommand(CPlayerSlot slot, const CCommand& args);
private:
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -16,38 +16,36 @@
#include <cstdio>
#include "core/global_listener.h"
#include "core/log.h"
#include "core/coreconfig.h"
#include "core/gameconfig.h"
#include "core/game_system.h"
#include "core/timer_system.h"
#include "core/tick_scheduler.h"
#include "core/utils.h"
#include "core/gameconfig.h"
#include "core/global_listener.h"
#include "core/globals.h"
#include "core/log.h"
#include "core/managers/entity_manager.h"
#include "core/tick_scheduler.h"
#include "core/timer_system.h"
#include "core/utils.h"
#include "entity2/entitysystem.h"
#include "igameeventsystem.h"
#include "interfaces/cs2_interfaces.h"
#include "iserver.h"
#include "scripting/callback_manager.h"
#include "scripting/dotnet_host.h"
#include "scripting/script_engine.h"
#include "entity2/entitysystem.h"
#include "interfaces/cs2_interfaces.h"
#define VERSION_STRING "v" BUILD_NUMBER " @ " GITHUB_SHA
#define VERSION_STRING "v" BUILD_NUMBER " @ " GITHUB_SHA
#define BUILD_TIMESTAMP __DATE__ " " __TIME__
counterstrikesharp::GlobalClass* counterstrikesharp::GlobalClass::head = nullptr;
CGameEntitySystem *GameEntitySystem()
{
return counterstrikesharp::globals::entitySystem;
}
CGameEntitySystem* GameEntitySystem() { return counterstrikesharp::globals::entitySystem; }
// TODO: Workaround for windows, we __MUST__ have COUNTERSTRIKESHARP_API to handle it.
// like on windows it should be `extern "C" __declspec(dllexport)`, on linux it should be anything else.
DLL_EXPORT void InvokeNative(counterstrikesharp::fxNativeContext& context)
{
if (context.nativeIdentifier == 0)
if (context.nativeIdentifier == 0) // nice one
return;
if (context.nativeIdentifier != counterstrikesharp::hash_string_const("QUEUE_TASK_FOR_NEXT_FRAME") &&
@@ -72,9 +70,9 @@ class GameSessionConfiguration_t
namespace counterstrikesharp {
SH_DECL_HOOK3_void(IServerGameDLL, GameFrame, SH_NOATTRIB, 0, bool, bool, bool);
SH_DECL_HOOK3_void(INetworkServerService, StartupServer, SH_NOATTRIB, 0,
const GameSessionConfiguration_t&, ISource2WorldSession*, const char*);
SH_DECL_HOOK3_void(IEngineServiceMgr, RegisterLoopMode, SH_NOATTRIB, 0, const char *, ILoopModeFactory *, void **);
SH_DECL_HOOK3_void(
INetworkServerService, StartupServer, SH_NOATTRIB, 0, const GameSessionConfiguration_t&, ISource2WorldSession*, const char*);
SH_DECL_HOOK3_void(IEngineServiceMgr, RegisterLoopMode, SH_NOATTRIB, 0, const char*, ILoopModeFactory*, void**);
SH_DECL_HOOK1(IEngineServiceMgr, FindService, SH_NOATTRIB, 0, IEngineService*, const char*);
CounterStrikeSharpMMPlugin gPlugin;
@@ -85,8 +83,7 @@ ConVar sample_cvar("sample_cvar", "42", 0);
#endif
PLUGIN_EXPOSE(CounterStrikeSharpMMPlugin, gPlugin);
bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI* ismm, char* error, size_t maxlen,
bool late)
bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI* ismm, char* error, size_t maxlen, bool late)
{
PLUGIN_SAVEVARS();
globals::ismm = ismm;
@@ -96,26 +93,21 @@ bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI* ismm, char* error, s
CSSHARP_CORE_INFO("Initializing");
GET_V_IFACE_CURRENT(GetEngineFactory, globals::engine, IVEngineServer,
INTERFACEVERSION_VENGINESERVER);
GET_V_IFACE_CURRENT(GetEngineFactory, globals::engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
GET_V_IFACE_CURRENT(GetEngineFactory, globals::cvars, ICvar, CVAR_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetServerFactory, globals::server, IServerGameDLL,
INTERFACEVERSION_SERVERGAMEDLL);
GET_V_IFACE_ANY(GetServerFactory, globals::serverGameClients, IServerGameClients,
INTERFACEVERSION_SERVERGAMECLIENTS);
GET_V_IFACE_ANY(GetEngineFactory, globals::networkServerService, INetworkServerService,
NETWORKSERVERSERVICE_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetServerFactory, globals::server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
GET_V_IFACE_ANY(GetServerFactory, globals::serverGameClients, IServerGameClients, INTERFACEVERSION_SERVERGAMECLIENTS);
GET_V_IFACE_ANY(GetEngineFactory, globals::networkServerService, INetworkServerService, NETWORKSERVERSERVICE_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::schemaSystem, CSchemaSystem, SCHEMASYSTEM_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::gameEventSystem, IGameEventSystem,
GAMEEVENTSYSTEM_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::engineServiceManager, IEngineServiceMgr,
ENGINESERVICEMGR_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::gameEventSystem, IGameEventSystem, GAMEEVENTSYSTEM_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::engineServiceManager, IEngineServiceMgr, ENGINESERVICEMGR_INTERFACE_VERSION);
auto coreconfig_path = std::string(utils::ConfigsDirectory() + "/core");
globals::coreConfig = new CCoreConfig(coreconfig_path);
char coreconfig_error[255] = "";
if (!globals::coreConfig->Init(coreconfig_error, sizeof(coreconfig_error))) {
if (!globals::coreConfig->Init(coreconfig_error, sizeof(coreconfig_error)))
{
CSSHARP_CORE_ERROR("Could not read \'{}\'. Error: {}", coreconfig_path, coreconfig_error);
return false;
}
@@ -126,7 +118,8 @@ bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI* ismm, char* error, s
globals::gameConfig = new CGameConfig(gamedata_path);
char conf_error[255] = "";
if (!globals::gameConfig->Init(conf_error, sizeof(conf_error))) {
if (!globals::gameConfig->Init(conf_error, sizeof(conf_error)))
{
CSSHARP_CORE_ERROR("Could not read \'{}\'. Error: {}", gamedata_path, conf_error);
return false;
}
@@ -140,18 +133,21 @@ bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI* ismm, char* error, s
on_activate_callback = globals::callbackManager.CreateCallback("OnMapStart");
SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this,
&CounterStrikeSharpMMPlugin::Hook_GameFrame, true);
SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this, &CounterStrikeSharpMMPlugin::Hook_GameFrame, true);
SH_ADD_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService, this,
&CounterStrikeSharpMMPlugin::Hook_StartupServer, true);
SH_ADD_HOOK_MEMFUNC(IEngineServiceMgr, RegisterLoopMode, globals::engineServiceManager, this, &CounterStrikeSharpMMPlugin::Hook_RegisterLoopMode, false);
SH_ADD_HOOK_MEMFUNC(IEngineServiceMgr, FindService, globals::engineServiceManager, this, &CounterStrikeSharpMMPlugin::Hook_FindService, true);
SH_ADD_HOOK_MEMFUNC(IEngineServiceMgr, RegisterLoopMode, globals::engineServiceManager, this,
&CounterStrikeSharpMMPlugin::Hook_RegisterLoopMode, false);
SH_ADD_HOOK_MEMFUNC(IEngineServiceMgr, FindService, globals::engineServiceManager, this, &CounterStrikeSharpMMPlugin::Hook_FindService,
true);
if (!globals::dotnetManager.Initialize()) {
if (!globals::dotnetManager.Initialize())
{
CSSHARP_CORE_ERROR("Failed to initialize .NET runtime");
}
if (!InitGameSystems()) {
if (!InitGameSystems())
{
CSSHARP_CORE_ERROR("Failed to initialize GameSystem!");
return false;
}
@@ -166,8 +162,7 @@ bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI* ismm, char* error, s
return true;
}
void CounterStrikeSharpMMPlugin::Hook_StartupServer(const GameSessionConfiguration_t& config,
ISource2WorldSession*, const char*)
void CounterStrikeSharpMMPlugin::Hook_StartupServer(const GameSessionConfiguration_t& config, ISource2WorldSession*, const char*)
{
globals::entitySystem = interfaces::pGameResourceServiceServer->GetGameEntitySystem();
globals::entitySystem->AddListenerEntity(&globals::entityManager.entityListener);
@@ -180,10 +175,9 @@ void CounterStrikeSharpMMPlugin::Hook_StartupServer(const GameSessionConfigurati
bool CounterStrikeSharpMMPlugin::Unload(char* error, size_t maxlen)
{
SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this,
&CounterStrikeSharpMMPlugin::Hook_GameFrame, true);
SH_REMOVE_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService,
this, &CounterStrikeSharpMMPlugin::Hook_StartupServer, true);
SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this, &CounterStrikeSharpMMPlugin::Hook_GameFrame, true);
SH_REMOVE_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService, this,
&CounterStrikeSharpMMPlugin::Hook_StartupServer, true);
globals::callbackManager.ReleaseCallback(on_activate_callback);
@@ -216,35 +210,39 @@ void CounterStrikeSharpMMPlugin::Hook_GameFrame(bool simulating, bool bFirstTick
auto size = m_nextTasks.try_dequeue_bulk(out_list.begin(), 1024);
if (size > 0) {
CSSHARP_CORE_TRACE("Executing queued tasks of size: {0} on tick number {1}", size,
globals::getGlobalVars()->tickcount);
if (size > 0)
{
CSSHARP_CORE_TRACE("Executing queued tasks of size: {0} on tick number {1}", size, globals::getGlobalVars()->tickcount);
for (size_t i = 0; i < size; i++) {
for (size_t i = 0; i < size; i++)
{
out_list[i]();
}
}
auto callbacks = globals::tickScheduler.getCallbacks(globals::getGlobalVars()->tickcount);
if (callbacks.size() > 0) {
if (callbacks.size() > 0)
{
CSSHARP_CORE_TRACE("Executing frame specific tasks of size: {0} on tick number {1}", callbacks.size(),
globals::getGlobalVars()->tickcount);
for (auto& callback : callbacks) {
for (auto& callback : callbacks)
{
callback();
}
}
}
// Potentially might not work
void CounterStrikeSharpMMPlugin::OnLevelInit(char const* pMapName, char const* pMapEntities,
char const* pOldLevel, char const* pLandmarkName,
bool loadGame, bool background)
void CounterStrikeSharpMMPlugin::OnLevelInit(
char const* pMapName, char const* pMapEntities, char const* pOldLevel, char const* pLandmarkName, bool loadGame, bool background)
{
CSSHARP_CORE_TRACE("name={0},mapname={1}", "LevelInit", pMapName);
}
void CounterStrikeSharpMMPlugin::Hook_RegisterLoopMode(const char *pszLoopModeName, ILoopModeFactory *pLoopModeFactory, void **ppGlobalPointer)
void CounterStrikeSharpMMPlugin::Hook_RegisterLoopMode(const char* pszLoopModeName,
ILoopModeFactory* pLoopModeFactory,
void** ppGlobalPointer)
{
if (strcmp(pszLoopModeName, "game") == 0)
{
@@ -256,7 +254,7 @@ void CounterStrikeSharpMMPlugin::Hook_RegisterLoopMode(const char *pszLoopModeNa
IEngineService* CounterStrikeSharpMMPlugin::Hook_FindService(const char* serviceName)
{
IEngineService *pService = META_RESULT_ORIG_RET(IEngineService *);
IEngineService* pService = META_RESULT_ORIG_RET(IEngineService*);
return pService;
}
@@ -277,15 +275,9 @@ const char* CounterStrikeSharpMMPlugin::GetLogTag() { return "CSSHARP"; }
const char* CounterStrikeSharpMMPlugin::GetAuthor() { return "Roflmuffin"; }
const char* CounterStrikeSharpMMPlugin::GetDescription()
{
return "Counter Strike .NET Scripting Runtime";
}
const char* CounterStrikeSharpMMPlugin::GetDescription() { return "Counter Strike .NET Scripting Runtime"; }
const char* CounterStrikeSharpMMPlugin::GetName() { return "CounterStrikeSharp"; }
const char* CounterStrikeSharpMMPlugin::GetURL()
{
return "https://github.com/roflmuffin/CounterStrikeSharp";
}
const char* CounterStrikeSharpMMPlugin::GetURL() { return "https://github.com/roflmuffin/CounterStrikeSharp"; }
} // namespace counterstrikesharp

View File

@@ -17,32 +17,33 @@
#pragma once
#include "core/global_listener.h"
#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 { \
public: \
void OnAllInitialized() override method \
}; \
\
#define REGISTER_NATIVES(name, method) \
class Natives##name : public counterstrikesharp::GlobalClass \
{ \
public: \
void OnAllInitialized() override method \
}; \
\
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; \
}
#define CREATE_STATIC_GETTER_FUNCTION(parameter_name, parameter_type, getter) \
static parameter_type Get##parameter_name(ScriptContext &script_context) { return getter; }
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

@@ -15,9 +15,12 @@
*/
#include "scripting/callback_manager.h"
#include "core/log.h"
#include <algorithm>
#include "core/globals.h"
#include "core/log.h"
namespace counterstrikesharp {
ScriptCallback::ScriptCallback(const char* szName) : m_root_context(fxNativeContext{})
@@ -28,30 +31,29 @@ ScriptCallback::ScriptCallback(const char* szName) : m_root_context(fxNativeCont
ScriptCallback::~ScriptCallback() { m_functions.clear(); }
void ScriptCallback::AddListener(CallbackT fnPluginFunction)
{
m_functions.push_back(fnPluginFunction);
}
void ScriptCallback::AddListener(CallbackT fnPluginFunction) { m_functions.push_back(fnPluginFunction); }
bool ScriptCallback::RemoveListener(CallbackT fnPluginFunction)
{
bool bSuccess = true;
m_functions.erase(std::remove(m_functions.begin(), m_functions.end(), fnPluginFunction),
m_functions.end());
m_functions.erase(std::remove(m_functions.begin(), m_functions.end(), fnPluginFunction), m_functions.end());
return bSuccess;
}
void ScriptCallback::Execute(bool bResetContext)
{
for (auto fnMethodToCall : m_functions) {
if (fnMethodToCall) {
for (auto fnMethodToCall : m_functions)
{
if (fnMethodToCall)
{
fnMethodToCall(&ScriptContextStruct());
}
}
if (bResetContext) {
if (bResetContext)
{
Reset();
}
}
@@ -71,8 +73,10 @@ ScriptCallback* CallbackManager::CreateCallback(const char* szName)
ScriptCallback* CallbackManager::FindCallback(const char* szName)
{
for (auto* pMarshal : m_managed) {
if (strcmp(pMarshal->GetName().c_str(), szName) == 0) {
for (auto* pMarshal : m_managed)
{
if (strcmp(pMarshal->GetName().c_str(), szName) == 0)
{
return pMarshal;
}
}
@@ -82,18 +86,19 @@ ScriptCallback* CallbackManager::FindCallback(const char* szName)
void CallbackManager::ReleaseCallback(ScriptCallback* pCallback)
{
auto I = std::remove_if(m_managed.begin(), m_managed.end(),
[pCallback](ScriptCallback* pI) { return pCallback == pI; });
auto I = std::remove_if(m_managed.begin(), m_managed.end(), [pCallback](ScriptCallback* pI) {
return pCallback == pI;
});
if (I != m_managed.end())
m_managed.erase(I, m_managed.end());
if (I != m_managed.end()) m_managed.erase(I, m_managed.end());
delete pCallback;
}
bool CallbackManager::TryAddFunction(const char* szName, CallbackT fnCallable)
{
auto* pCallback = FindCallback(szName);
if (pCallback) {
if (pCallback)
{
pCallback->AddListener(fnCallable);
return true;
}
@@ -104,7 +109,8 @@ bool CallbackManager::TryAddFunction(const char* szName, CallbackT fnCallable)
bool CallbackManager::TryRemoveFunction(const char* szName, CallbackT fnCallable)
{
auto* pCallback = FindCallback(szName);
if (pCallback) {
if (pCallback)
{
return pCallback->RemoveListener(fnCallable);
}
@@ -114,7 +120,8 @@ bool CallbackManager::TryRemoveFunction(const char* szName, CallbackT fnCallable
void CallbackManager::PrintCallbackDebug()
{
CSSHARP_CORE_INFO("----CALLBACKS----");
for (auto* pCallback : m_managed) {
for (auto* pCallback : m_managed)
{
CSSHARP_CORE_INFO("{0} ({0})\n", pCallback->GetName().c_str(), 1);
}
}
@@ -126,7 +133,8 @@ CallbackPair::CallbackPair()
CallbackPair::CallbackPair(bool bNoCallbacks)
{
if (!bNoCallbacks) {
if (!bNoCallbacks)
{
pre = globals::callbackManager.CreateCallback("");
post = globals::callbackManager.CreateCallback("");
}
@@ -138,4 +146,4 @@ CallbackPair::~CallbackPair()
globals::callbackManager.ReleaseCallback(post);
}
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -19,7 +19,6 @@
#include <vector>
#include "core/global_listener.h"
#include "core/globals.h"
#include "scripting/script_engine.h"
namespace counterstrikesharp {
@@ -69,12 +68,11 @@ class CallbackPair
CallbackPair();
CallbackPair(bool bNoCallbacks);
~CallbackPair();
bool HasCallbacks() const
{ return pre->GetFunctionCount() > 0 || post->GetFunctionCount() > 0; }
bool HasCallbacks() const { return pre->GetFunctionCount() > 0 || post->GetFunctionCount() > 0; }
public:
ScriptCallback* pre;
ScriptCallback* post;
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -14,21 +14,24 @@
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "core/globals.h"
#include "scripting//callback_manager.h"
#include "scripting/autonative.h"
#include "scripting/script_engine.h"
namespace counterstrikesharp {
static bool AddListener(ScriptContext &script_context) {
auto name = script_context.GetArgument<const char *>(0);
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) {
auto name = script_context.GetArgument<const char *>(0);
static bool RemoveListener(ScriptContext& script_context)
{
auto name = script_context.GetArgument<const char*>(0);
auto callback = script_context.GetArgument<CallbackT>(1);
return globals::callbackManager.TryRemoveFunction(name, callback);
@@ -38,4 +41,4 @@ REGISTER_NATIVES(callbacks, {
ScriptEngine::RegisterNativeHandler("ADD_LISTENER", AddListener);
ScriptEngine::RegisterNativeHandler("REMOVE_LISTENER", RemoveListener);
})
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -14,24 +14,28 @@
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include <cstdint>
#include <ios>
#include <sstream>
#include "scripting/autonative.h"
#include "core/function.h"
#include "scripting/script_engine.h"
#include "core/memory.h"
#include "core/log.h"
#include "core/memory.h"
#include "entityhandle.h"
#include "scripting/autonative.h"
#include "scripting/script_engine.h"
#include "utlvector.h"
namespace counterstrikesharp {
std::vector<ValveFunction*> m_managed_ptrs;
byte* ConvertToByteArray(const char* str, size_t* outLength)
uint8_t* ConvertToByteArray(const char* str, size_t* outLength)
{
size_t len = strlen(str) / 4; // Every byte is represented as \xHH
byte* result = (byte*)malloc(len);
uint8_t* result = (uint8_t*)malloc(len);
for (size_t i = 0, j = 0; i < len; ++i, j += 4) {
for (size_t i = 0, j = 0; i < len; ++i, j += 4)
{
sscanf(str + j, "\\x%2hhx", &result[i]);
}
@@ -57,21 +61,22 @@ ValveFunction* CreateVirtualFunctionBySignature(ScriptContext& script_context)
auto* function_addr = FindSignature(binary_name, signature_hex_string);
if (function_addr == nullptr) {
if (function_addr == nullptr)
{
script_context.ThrowNativeError("Could not find signature %s", signature_hex_string);
return nullptr;
}
auto args = std::vector<DataType_t>();
for (int i = 0; i < num_arguments; i++) {
for (int i = 0; i < num_arguments; i++)
{
args.push_back(script_context.GetArgument<DataType_t>(5 + i));
}
auto function = new ValveFunction(function_addr, CONV_CDECL, args, return_type);
function->SetSignature(signature_hex_string);
CSSHARP_CORE_TRACE("Created virtual function, pointer found at {}, signature {}", function_addr,
signature_hex_string);
CSSHARP_CORE_TRACE("Created virtual function, pointer found at {}, signature {}", function_addr, signature_hex_string);
m_managed_ptrs.push_back(function);
return function;
@@ -85,7 +90,8 @@ ValveFunction* CreateVirtualFunction(ScriptContext& script_context)
auto return_type = script_context.GetArgument<DataType_t>(3);
void** vtable = *(void***)ptr;
if (!vtable) {
if (!vtable)
{
script_context.ThrowNativeError("Failed to get the virtual function table.");
return nullptr;
}
@@ -93,7 +99,8 @@ ValveFunction* CreateVirtualFunction(ScriptContext& script_context)
auto function_addr = (void*)vtable[vtable_offset];
auto args = std::vector<DataType_t>();
for (int i = 0; i < num_arguments; i++) {
for (int i = 0; i < num_arguments; i++)
{
args.push_back(script_context.GetArgument<DataType_t>(4 + i));
}
@@ -110,7 +117,8 @@ void HookFunction(ScriptContext& script_context)
auto callback = script_context.GetArgument<CallbackT>(1);
auto post = script_context.GetArgument<bool>(2);
if (!function) {
if (!function)
{
script_context.ThrowNativeError("Invalid function pointer");
return;
}
@@ -124,7 +132,8 @@ void UnhookFunction(ScriptContext& script_context)
auto callback = script_context.GetArgument<CallbackT>(1);
auto post = script_context.GetArgument<bool>(2);
if (!function) {
if (!function)
{
script_context.ThrowNativeError("Invalid function pointer");
return;
}
@@ -136,7 +145,8 @@ void ExecuteVirtualFunction(ScriptContext& script_context)
{
auto function = script_context.GetArgument<ValveFunction*>(0);
if (!function) {
if (!function)
{
script_context.ThrowNativeError("Invalid function pointer");
return;
}
@@ -168,8 +178,7 @@ void RemoveAllNetworkVectorElements(ScriptContext& script_context)
REGISTER_NATIVES(memory, {
ScriptEngine::RegisterNativeHandler("CREATE_VIRTUAL_FUNCTION", CreateVirtualFunction);
ScriptEngine::RegisterNativeHandler("CREATE_VIRTUAL_FUNCTION_BY_SIGNATURE",
CreateVirtualFunctionBySignature);
ScriptEngine::RegisterNativeHandler("CREATE_VIRTUAL_FUNCTION_BY_SIGNATURE", CreateVirtualFunctionBySignature);
ScriptEngine::RegisterNativeHandler("EXECUTE_VIRTUAL_FUNCTION", ExecuteVirtualFunction);
ScriptEngine::RegisterNativeHandler("HOOK_FUNCTION", HookFunction);
ScriptEngine::RegisterNativeHandler("UNHOOK_FUNCTION", UnhookFunction);

View File

@@ -17,11 +17,13 @@
#include <scripting/autonative.h>
#include <scripting/script_engine.h>
#include "core/globals.h"
#include "core/timer_system.h"
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,8 +31,9 @@ timers::Timer *CreateTimer(ScriptContext &script_context) {
return globals::timerSystem.CreateTimer(interval, callback, flags);
}
void KillTimer(ScriptContext &script_context) {
auto timer = script_context.GetArgument<timers::Timer *>(0);
void KillTimer(ScriptContext& script_context)
{
auto timer = script_context.GetArgument<timers::Timer*>(0);
globals::timerSystem.KillTimer(timer);
}
@@ -38,4 +41,4 @@ REGISTER_NATIVES(timers, {
ScriptEngine::RegisterNativeHandler("CREATE_TIMER", CreateTimer);
ScriptEngine::RegisterNativeHandler("KILL_TIMER", KillTimer);
})
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -14,6 +14,9 @@
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include <mathlib.h>
#include <mathlib/vector.h>
#include <vector>
#include "scripting/autonative.h"
@@ -21,55 +24,62 @@
namespace counterstrikesharp {
CREATE_GETTER_FUNCTION(Vector, float, Length, Vector *, obj->Length());
CREATE_GETTER_FUNCTION(Vector, float, Length2D, Vector *, obj->Length2D());
CREATE_GETTER_FUNCTION(Vector, float, LengthSqr, Vector *, obj->LengthSqr());
CREATE_GETTER_FUNCTION(Vector, float, Length2DSqr, Vector *, obj->Length2DSqr());
CREATE_GETTER_FUNCTION(Vector, float, IsZero, Vector *, obj->IsZero());
CREATE_GETTER_FUNCTION(Vector, float, Length, Vector*, obj->Length());
CREATE_GETTER_FUNCTION(Vector, float, Length2D, Vector*, obj->Length2D());
CREATE_GETTER_FUNCTION(Vector, float, LengthSqr, Vector*, obj->LengthSqr());
CREATE_GETTER_FUNCTION(Vector, float, Length2DSqr, Vector*, obj->Length2DSqr());
CREATE_GETTER_FUNCTION(Vector, float, IsZero, Vector*, obj->IsZero());
CREATE_GETTER_FUNCTION(Vector, float, X, Vector *, obj->x);
CREATE_GETTER_FUNCTION(Vector, float, Y, Vector *, obj->y);
CREATE_GETTER_FUNCTION(Vector, float, Z, Vector *, obj->z);
CREATE_GETTER_FUNCTION(Vector, float, X, Vector*, obj->x);
CREATE_GETTER_FUNCTION(Vector, float, Y, Vector*, obj->y);
CREATE_GETTER_FUNCTION(Vector, float, Z, Vector*, obj->z);
CREATE_SETTER_FUNCTION(Vector, float, X, Vector *, obj->x = value);
CREATE_SETTER_FUNCTION(Vector, float, Y, Vector *, obj->y = value);
CREATE_SETTER_FUNCTION(Vector, float, Z, Vector *, obj->z = value);
CREATE_SETTER_FUNCTION(Vector, float, X, Vector*, obj->x = value);
CREATE_SETTER_FUNCTION(Vector, float, Y, Vector*, obj->y = value);
CREATE_SETTER_FUNCTION(Vector, float, Z, Vector*, obj->z = value);
// TODO: These need to be cleared out somehow
std::vector<Vector *> managed_vectors;
std::vector<Vector*> managed_vectors;
Vector *VectorNew(ScriptContext &script_context) {
Vector* VectorNew(ScriptContext& script_context)
{
auto vec = new Vector();
managed_vectors.push_back(vec);
return vec;
}
// TODO: These need to be cleared out somehow
std::vector<QAngle *> managed_angles;
std::vector<QAngle*> managed_angles;
QAngle *AngleNew(ScriptContext &script_context) {
QAngle* AngleNew(ScriptContext& script_context)
{
auto ang = new QAngle();
managed_angles.push_back(ang);
return ang;
}
void NativeVectorAngles(ScriptContext &script_context) {
auto vec = script_context.GetArgument<Vector *>(0);
auto pseudoUpVector = script_context.GetArgument<Vector *>(1);
auto outAngle = script_context.GetArgument<QAngle *>(2);
void NativeVectorAngles(ScriptContext& script_context)
{
auto vec = script_context.GetArgument<Vector*>(0);
auto pseudoUpVector = script_context.GetArgument<Vector*>(1);
auto outAngle = script_context.GetArgument<QAngle*>(2);
if (!pseudoUpVector) {
if (!pseudoUpVector)
{
VectorAngles(*vec, *outAngle);
} else {
}
else
{
VectorAngles(*vec, *pseudoUpVector, *outAngle);
}
}
void NativeAngleVectors(ScriptContext &script_context) {
auto vec = script_context.GetArgument<QAngle *>(0);
auto fwd = script_context.GetArgument<Vector *>(1);
auto right = script_context.GetArgument<Vector *>(2);
auto up = script_context.GetArgument<Vector *>(3);
void NativeAngleVectors(ScriptContext& script_context)
{
auto vec = script_context.GetArgument<QAngle*>(0);
auto fwd = script_context.GetArgument<Vector*>(1);
auto right = script_context.GetArgument<Vector*>(2);
auto up = script_context.GetArgument<Vector*>(3);
AngleVectors(*vec, fwd, right, up);
}
@@ -94,4 +104,4 @@ REGISTER_NATIVES(vector, {
ScriptEngine::RegisterNativeHandler("VECTOR_LENGTH_2D_SQR", VectorGetLength2DSqr);
ScriptEngine::RegisterNativeHandler("VECTOR_IS_ZERO", VectorGetLengthSqr);
})
} // namespace counterstrikesharp
} // namespace counterstrikesharp