mirror of
https://github.com/roflmuffin/CounterStrikeSharp.git
synced 2025-12-06 08:03:12 -08:00
Compare commits
54 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44a85d1201 | ||
|
|
20f50289ee | ||
|
|
bb5fb5de72 | ||
|
|
6147739cfa | ||
|
|
3ab5893f22 | ||
|
|
50ce09a7b3 | ||
|
|
9c7944e6f1 | ||
|
|
bc71aa7739 | ||
|
|
16a1efc0cb | ||
|
|
8ae85cedf4 | ||
|
|
8e2234ff25 | ||
|
|
04e7ed682a | ||
|
|
15e1260146 | ||
|
|
517607d962 | ||
|
|
0f72631eb0 | ||
|
|
75fcf21fb7 | ||
|
|
0ddf6bcdfa | ||
|
|
98661cd069 | ||
|
|
86a5699b40 | ||
|
|
414710d05c | ||
|
|
b09c2b62c8 | ||
|
|
31760518ed | ||
|
|
6a160bcc3d | ||
|
|
9c8e9db56e | ||
|
|
e2e0eab87d | ||
|
|
43292bb1d2 | ||
|
|
12c54cd4fc | ||
|
|
e155a70873 | ||
|
|
69d9b5d2c8 | ||
|
|
933fdf9d81 | ||
|
|
18e9e37a98 | ||
|
|
fe236806e1 | ||
|
|
2c4e9bca42 | ||
|
|
8f3e0c226b | ||
|
|
5f6ccf2839 | ||
|
|
6c2f56793b | ||
|
|
cc7dd5ca96 | ||
|
|
ebc361b2f8 | ||
|
|
c72eff2546 | ||
|
|
4b432e9efc | ||
|
|
22bbf835c7 | ||
|
|
092a6077c3 | ||
|
|
4430060efd | ||
|
|
77ea6fd80d | ||
|
|
f18df3df2b | ||
|
|
4ce1ec2cf5 | ||
|
|
9005f3c29c | ||
|
|
b7ace4256a | ||
|
|
b725f7f79a | ||
|
|
cb6d86a54d | ||
|
|
d4a2ae68e1 | ||
|
|
82c92f555b | ||
|
|
19a0923559 | ||
|
|
cef9758c12 |
204
.github/workflows/cmake-single-platform.yml
vendored
204
.github/workflows/cmake-single-platform.yml
vendored
@@ -5,87 +5,193 @@ on:
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
branches: [ "main" ]
|
||||
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
|
||||
jobs:
|
||||
build:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest
|
||||
|
||||
build_windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Prepare env
|
||||
shell: bash
|
||||
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
|
||||
|
||||
- name: Setup protobuf
|
||||
shell: bash
|
||||
run: sudo apt-get update && sudo apt install -y protobuf-compiler
|
||||
- name: Visual Studio environment
|
||||
shell: cmd
|
||||
run: |
|
||||
:: See https://github.com/microsoft/vswhere/wiki/Find-VC
|
||||
for /f "usebackq delims=*" %%i in (`vswhere -latest -property installationPath`) do (
|
||||
call "%%i"\Common7\Tools\vsdevcmd.bat -arch=x64 -host_arch=x64
|
||||
)
|
||||
|
||||
:: Loop over all environment variables and make them global.
|
||||
for /f "delims== tokens=1,2" %%a in ('set') do (
|
||||
echo>>"%GITHUB_ENV%" %%a=%%b
|
||||
)
|
||||
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Generate build number
|
||||
id: buildnumber
|
||||
uses: onyxmueller/build-tag-number@v1
|
||||
with:
|
||||
token: ${{secrets.github_token}}
|
||||
|
||||
- uses: actions/setup-dotnet@v3
|
||||
with:
|
||||
dotnet-version: '7.0.x'
|
||||
- run: dotnet publish -c Release /p:Version=1.0.${{ env.BUILD_NUMBER }} managed/CounterStrikeSharp.API
|
||||
|
||||
- name: Configure CMake
|
||||
run: cmake -B build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
|
||||
|
||||
- name: Build
|
||||
# Build your program with the given configuration
|
||||
run: cmake --build build --config ${{env.BUILD_TYPE}}
|
||||
run: |
|
||||
mkdir -p build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} ..
|
||||
cmake --build . --config ${{env.BUILD_TYPE}} -- /m:16
|
||||
|
||||
- name: Clean build directory
|
||||
run: |
|
||||
mkdir -p build/addons/counterstrikesharp/bin/win64
|
||||
mv build/${{env.BUILD_TYPE}}/*.dll build/addons/counterstrikesharp/bin/win64
|
||||
mkdir build/output/
|
||||
mv build/addons build/output
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: counterstrikesharp-build-windows-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: build/output/
|
||||
|
||||
build_linux:
|
||||
runs-on: ubuntu-latest
|
||||
# Could not figure out how to run in a container only on some matrix paths, so I've split it out into its own build.
|
||||
container:
|
||||
image: registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest
|
||||
steps:
|
||||
- name: Prepare env
|
||||
shell: bash
|
||||
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
|
||||
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
mkdir -p build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} ..
|
||||
cmake --build . --config ${{env.BUILD_TYPE}} -- -j16
|
||||
|
||||
- name: Clean build directory
|
||||
run: |
|
||||
mkdir build/output/
|
||||
mv build/addons build/output
|
||||
|
||||
- name: Add API to Artifacts
|
||||
run: |
|
||||
mkdir -p build/output/addons/counterstrikesharp/api
|
||||
mkdir -p build/output/addons/counterstrikesharp/plugins
|
||||
cp -r managed/CounterStrikeSharp.API/bin/Release/net7.0/publish/* build/output/addons/counterstrikesharp/api
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: counterstrikesharp-build-linux-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: build/output/
|
||||
|
||||
build_managed:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
buildnumber: ${{ steps.buildnumber.outputs.build_number }}
|
||||
steps:
|
||||
- name: Prepare env
|
||||
shell: bash
|
||||
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
|
||||
|
||||
- name: Fallback build number
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
run: echo "BUILD_NUMBER=0" >> $GITHUB_ENV
|
||||
|
||||
# We don't need expensive submodules for the managed side.
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Generate build number
|
||||
if: github.event_name == 'push'
|
||||
id: buildnumber
|
||||
uses: onyxmueller/build-tag-number@v1
|
||||
with:
|
||||
token: ${{secrets.github_token}}
|
||||
|
||||
- name: Build runtime v${{ env.BUILD_NUMBER }}
|
||||
uses: actions/setup-dotnet@v3
|
||||
with:
|
||||
dotnet-version: '7.0.x'
|
||||
|
||||
- run: |
|
||||
dotnet publish -c Release /p:Version=1.0.${{ env.BUILD_NUMBER }} managed/CounterStrikeSharp.API
|
||||
dotnet pack -c Release /p:Version=1.0.${{ env.BUILD_NUMBER }} managed/CounterStrikeSharp.API
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: counterstrikesharp-build-${{ env.BUILD_NUMBER }}-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: build/output/
|
||||
name: counterstrikesharp-build-api-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: managed/CounterStrikeSharp.API/bin/Release
|
||||
|
||||
- name: Zip CounterStrikeSharp Build
|
||||
run: (cd build/output && zip -qq -r ../../counterstrikesharp-build-${{ env.BUILD_NUMBER }}-${{ env.GITHUB_SHA_SHORT }}.zip *)
|
||||
publish:
|
||||
if: github.event_name == 'push'
|
||||
permissions:
|
||||
contents: write
|
||||
needs: [ "build_linux", "build_windows", "build_managed" ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Prepare env
|
||||
shell: bash
|
||||
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
|
||||
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: counterstrikesharp-build-windows-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: build/windows
|
||||
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: counterstrikesharp-build-linux-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: build/linux
|
||||
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: counterstrikesharp-build-api-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: build/api
|
||||
|
||||
# TODO: This stuff should really be in a matrix
|
||||
- name: Add API to Artifacts
|
||||
run: |
|
||||
mkdir -p build/linux/addons/counterstrikesharp/api
|
||||
mkdir -p build/windows/addons/counterstrikesharp/api
|
||||
cp -r build/api/net7.0/publish/* build/linux/addons/counterstrikesharp/api
|
||||
cp -r build/api/net7.0/publish/* build/windows/addons/counterstrikesharp/api
|
||||
|
||||
- name: Zip Builds
|
||||
run: |
|
||||
(cd build/linux && zip -qq -r ../../counterstrikesharp-build-${{ needs.build_managed.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip *)
|
||||
(cd build/windows && zip -qq -r ../../counterstrikesharp-build-${{ needs.build_managed.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip *)
|
||||
|
||||
- name: Add dotnet runtime
|
||||
run: |
|
||||
mkdir -p build/output/addons/counterstrikesharp/dotnet
|
||||
mkdir -p build/linux/addons/counterstrikesharp/dotnet
|
||||
curl -s -L https://download.visualstudio.microsoft.com/download/pr/dc2c0a53-85a8-4fda-a283-fa28adb5fbe2/8ccade5bc400a5bb40cd9240f003b45c/aspnetcore-runtime-7.0.11-linux-x64.tar.gz \
|
||||
| tar xvz -C build/output/addons/counterstrikesharp/dotnet
|
||||
mv build/output/addons/counterstrikesharp/dotnet/shared/Microsoft.NETCore.App/7.0.11/* build/output/addons/counterstrikesharp/dotnet/shared/Microsoft.NETCore.App/
|
||||
| tar xvz -C build/linux/addons/counterstrikesharp/dotnet
|
||||
mv build/linux/addons/counterstrikesharp/dotnet/shared/Microsoft.NETCore.App/7.0.11/* build/linux/addons/counterstrikesharp/dotnet/shared/Microsoft.NETCore.App/
|
||||
|
||||
mkdir -p build/windows/addons/counterstrikesharp/dotnet
|
||||
curl -s -L https://download.visualstudio.microsoft.com/download/pr/a99861c8-2e00-4587-aaef-60366ca77307/a44ceec2c5d34165ae881600f52edc43/aspnetcore-runtime-7.0.11-win-x64.zip -o dotnet.zip
|
||||
unzip -qq dotnet.zip -d build/windows/addons/counterstrikesharp/dotnet
|
||||
|
||||
- name: Zip CounterStrikeSharp Runtime Build
|
||||
run: (cd build/output && zip -qq -r ../../counterstrikesharp-with-runtime-build-${{ env.BUILD_NUMBER }}-${{ env.GITHUB_SHA_SHORT }}.zip *)
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: counterstrikesharp-with-runtime-build-${{ env.BUILD_NUMBER }}-${{ env.GITHUB_SHA_SHORT }}
|
||||
path: build/output/
|
||||
- name: Zip Builds
|
||||
run: |
|
||||
(cd build/linux && zip -qq -r ../../counterstrikesharp-with-runtime-build-${{ needs.build_managed.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip *)
|
||||
(cd build/windows && zip -qq -r ../../counterstrikesharp-with-runtime-build-${{ needs.build_managed.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip *)
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: v${{ env.BUILD_NUMBER }}
|
||||
tag_name: v${{ needs.build_managed.outputs.buildnumber }}
|
||||
files: |
|
||||
counterstrikesharp-build-${{ env.BUILD_NUMBER }}-${{ env.GITHUB_SHA_SHORT }}.zip
|
||||
counterstrikesharp-with-runtime-build-${{ env.BUILD_NUMBER }}-${{ env.GITHUB_SHA_SHORT }}.zip
|
||||
counterstrikesharp-build-${{ needs.build_managed.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip
|
||||
counterstrikesharp-with-runtime-build-${{ needs.build_managed.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip
|
||||
counterstrikesharp-build-${{ needs.build_managed.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip
|
||||
counterstrikesharp-with-runtime-build-${{ needs.build_managed.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip
|
||||
|
||||
- name: Publish NuGet package
|
||||
run: |
|
||||
dotnet nuget push build/api/CounterStrikeSharp.API.1.0.${{ needs.build_managed.outputs.buildnumber }}.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
|
||||
dotnet nuget push build/api/CounterStrikeSharp.API.1.0.${{ needs.build_managed.outputs.buildnumber }}.snupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
|
||||
53
.github/workflows/pr-checks.yml
vendored
53
.github/workflows/pr-checks.yml
vendored
@@ -1,53 +0,0 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest
|
||||
permissions:
|
||||
pull-requests: read
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- uses: dorny/paths-filter@v2
|
||||
id: changes
|
||||
with:
|
||||
filters: |
|
||||
csharp:
|
||||
- managed/**/*
|
||||
- src/scripting/natives/**/*
|
||||
cpp:
|
||||
- src/**/*
|
||||
|
||||
- uses: actions/setup-dotnet@v3
|
||||
if: steps.changes.outputs.csharp == 'true'
|
||||
with:
|
||||
dotnet-version: '7.0.x'
|
||||
|
||||
- if: steps.changes.outputs.csharp == 'true'
|
||||
run: dotnet build -c Release managed/CounterStrikeSharp.API
|
||||
|
||||
- name: Setup protobuf
|
||||
shell: bash
|
||||
if: steps.changes.outputs.cpp == 'true'
|
||||
run: sudo apt-get update && sudo apt install -y protobuf-compiler
|
||||
|
||||
- name: Configure CMake
|
||||
if: steps.changes.outputs.cpp == 'true'
|
||||
run: cmake -B build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
|
||||
|
||||
- name: Build
|
||||
# Build your program with the given configuration
|
||||
if: steps.changes.outputs.cpp == 'true'
|
||||
run: cmake --build build --config ${{env.BUILD_TYPE}}
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -5,8 +5,13 @@ cmake-build-debug/
|
||||
.vscode/
|
||||
generated/
|
||||
|
||||
# configure_file auto generated.
|
||||
configs/addons/metamod/counterstrikesharp.vdf
|
||||
|
||||
libraries/mono/
|
||||
|
||||
CMakeSettings.json
|
||||
|
||||
build/
|
||||
build_test/
|
||||
|
||||
|
||||
202
CMakeLists.txt
202
CMakeLists.txt
@@ -1,6 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.18)
|
||||
|
||||
Project(counterstrikesharp C CXX)
|
||||
# You must set ASM, otherwise CMAKE_ASM_COMPILE_OBJECT will not work on MSVC
|
||||
project(counterstrikesharp C CXX ASM)
|
||||
|
||||
include("makefiles/shared.cmake")
|
||||
|
||||
@@ -11,89 +12,105 @@ add_subdirectory(libraries/funchook)
|
||||
set_property(TARGET funchook-static PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
SET(SOURCE_FILES
|
||||
src/mm_plugin.cpp
|
||||
src/mm_plugin.h
|
||||
libraries/hl2sdk-cs2/tier1/convar.cpp
|
||||
libraries/hl2sdk-cs2/tier1/generichash.cpp
|
||||
libraries/hl2sdk-cs2/entity2/entitysystem.cpp
|
||||
libraries/hl2sdk-cs2/public/tier0/memoverride.cpp
|
||||
libraries/dotnet/hostfxr.h
|
||||
libraries/dotnet/coreclr_delegates.h
|
||||
"libraries/metamod-source/core/sourcehook/sourcehook.cpp"
|
||||
"libraries/metamod-source/core/sourcehook/sourcehook_impl_chookidman.cpp"
|
||||
"libraries/metamod-source/core/sourcehook/sourcehook_impl_chookmaninfo.cpp"
|
||||
"libraries/metamod-source/core/sourcehook/sourcehook_impl_cvfnptr.cpp"
|
||||
"libraries/metamod-source/core/sourcehook/sourcehook_impl_cproto.cpp"
|
||||
src/scripting/dotnet_host.h
|
||||
src/scripting/dotnet_host.cpp
|
||||
src/core/utils.h
|
||||
src/core/globals.h
|
||||
src/core/globals.cpp
|
||||
src/core/log.h
|
||||
src/core/log.cpp
|
||||
src/scripting/script_engine.h
|
||||
src/scripting/script_engine.cpp
|
||||
src/core/global_listener.h
|
||||
src/scripting/callback_manager.h
|
||||
src/scripting/callback_manager.cpp
|
||||
src/core/managers/event_manager.h
|
||||
src/core/managers/event_manager.cpp
|
||||
src/core/timer_system.h
|
||||
src/core/timer_system.cpp
|
||||
src/scripting/autonative.h
|
||||
src/scripting/natives/natives_engine.cpp
|
||||
src/core/engine_trace.h
|
||||
src/core/engine_trace.cpp
|
||||
src/scripting/natives/natives_callbacks.cpp
|
||||
src/core/managers/player_manager.h
|
||||
src/core/managers/player_manager.cpp
|
||||
src/scripting/natives/natives_vector.cpp
|
||||
src/scripting/natives/natives_timers.cpp
|
||||
src/utils/virtual.h
|
||||
src/scripting/natives/natives_events.cpp
|
||||
src/core/memory.cpp
|
||||
src/core/memory.h
|
||||
src/core/managers/con_command_manager.cpp
|
||||
src/core/managers/con_command_manager.h
|
||||
src/scripting/natives/natives_commands.cpp
|
||||
src/core/memory_module.h
|
||||
src/core/cs2_sdk/interfaces/cgameresourceserviceserver.h
|
||||
src/core/cs2_sdk/interfaces/cschemasystem.h
|
||||
src/core/cs2_sdk/interfaces/cs2_interfaces.h
|
||||
src/core/cs2_sdk/interfaces/cs2_interfaces.cpp
|
||||
src/core/cs2_sdk/schema.h
|
||||
src/core/cs2_sdk/schema.cpp
|
||||
src/core/function.cpp
|
||||
src/core/function.h
|
||||
src/scripting/natives/natives_memory.cpp
|
||||
src/scripting/natives/natives_schema.cpp
|
||||
src/scripting/natives/natives_entities.cpp
|
||||
src/core/managers/entity_manager.cpp
|
||||
src/core/managers/entity_manager.h
|
||||
src/core/managers/chat_manager.cpp
|
||||
src/core/managers/chat_manager.h
|
||||
src/core/managers/client_command_manager.cpp
|
||||
src/core/managers/client_command_manager.h
|
||||
src/core/managers/server_manager.cpp
|
||||
src/core/managers/server_manager.h
|
||||
src/scripting/natives/natives_server.cpp
|
||||
libraries/nlohmann/json.hpp
|
||||
src/mm_plugin.cpp
|
||||
src/mm_plugin.h
|
||||
libraries/hl2sdk-cs2/tier1/convar.cpp
|
||||
libraries/hl2sdk-cs2/tier1/generichash.cpp
|
||||
libraries/hl2sdk-cs2/entity2/entitysystem.cpp
|
||||
libraries/dotnet/hostfxr.h
|
||||
libraries/dotnet/coreclr_delegates.h
|
||||
libraries/metamod-source/core/sourcehook/sourcehook.cpp
|
||||
libraries/metamod-source/core/sourcehook/sourcehook_impl_chookidman.cpp
|
||||
libraries/metamod-source/core/sourcehook/sourcehook_impl_chookmaninfo.cpp
|
||||
libraries/metamod-source/core/sourcehook/sourcehook_impl_cvfnptr.cpp
|
||||
libraries/metamod-source/core/sourcehook/sourcehook_impl_cproto.cpp
|
||||
src/scripting/dotnet_host.h
|
||||
src/scripting/dotnet_host.cpp
|
||||
src/core/utils.h
|
||||
src/core/globals.h
|
||||
src/core/globals.cpp
|
||||
src/core/coreconfig.h
|
||||
src/core/coreconfig.cpp
|
||||
src/core/gameconfig.h
|
||||
src/core/gameconfig.cpp
|
||||
src/core/log.h
|
||||
src/core/log.cpp
|
||||
src/scripting/script_engine.h
|
||||
src/scripting/script_engine.cpp
|
||||
src/core/global_listener.h
|
||||
src/scripting/callback_manager.h
|
||||
src/scripting/callback_manager.cpp
|
||||
src/core/managers/event_manager.h
|
||||
src/core/managers/event_manager.cpp
|
||||
src/core/timer_system.h
|
||||
src/core/timer_system.cpp
|
||||
src/scripting/autonative.h
|
||||
src/scripting/natives/natives_engine.cpp
|
||||
src/core/engine_trace.h
|
||||
src/core/engine_trace.cpp
|
||||
src/scripting/natives/natives_callbacks.cpp
|
||||
src/core/managers/player_manager.h
|
||||
src/core/managers/player_manager.cpp
|
||||
src/scripting/natives/natives_vector.cpp
|
||||
src/scripting/natives/natives_timers.cpp
|
||||
src/utils/virtual.h
|
||||
src/scripting/natives/natives_events.cpp
|
||||
src/core/memory.cpp
|
||||
src/core/memory.h
|
||||
src/core/managers/con_command_manager.cpp
|
||||
src/core/managers/con_command_manager.h
|
||||
src/scripting/natives/natives_commands.cpp
|
||||
src/core/memory_module.h
|
||||
src/core/memory_module.cpp
|
||||
src/core/cs2_sdk/interfaces/cgameresourceserviceserver.h
|
||||
src/core/cs2_sdk/interfaces/cschemasystem.h
|
||||
src/core/cs2_sdk/interfaces/cs2_interfaces.h
|
||||
src/core/cs2_sdk/interfaces/cs2_interfaces.cpp
|
||||
src/core/cs2_sdk/schema.h
|
||||
src/core/cs2_sdk/schema.cpp
|
||||
src/core/function.cpp
|
||||
src/core/function.h
|
||||
src/scripting/natives/natives_memory.cpp
|
||||
src/scripting/natives/natives_schema.cpp
|
||||
src/scripting/natives/natives_entities.cpp
|
||||
src/core/managers/entity_manager.cpp
|
||||
src/core/managers/entity_manager.h
|
||||
src/core/managers/chat_manager.cpp
|
||||
src/core/managers/chat_manager.h
|
||||
src/core/managers/server_manager.cpp
|
||||
src/core/managers/server_manager.h
|
||||
src/scripting/natives/natives_server.cpp
|
||||
libraries/nlohmann/json.hpp
|
||||
)
|
||||
|
||||
|
||||
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/GameTracking-CS2/Protobufs)
|
||||
file(GLOB PROTOS "${CMAKE_CURRENT_SOURCE_DIR}/libraries/GameTracking-CS2/Protobufs/*.proto")
|
||||
|
||||
## Generate protobuf source & headers
|
||||
#add_custom_command(
|
||||
# OUTPUT protobuf_output_stamp
|
||||
# COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/src/protobuf/compile.sh
|
||||
# COMMENT "Generating protobuf files using compile.sh script"
|
||||
# WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src/protobuf
|
||||
# DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/protobuf/compile.sh
|
||||
# VERBATIM
|
||||
#)
|
||||
#
|
||||
#SET(SOURCE_FILES ${SOURCE_FILES} protobuf_output_stamp)
|
||||
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)
|
||||
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
|
||||
)
|
||||
|
||||
SET(SOURCE_FILES ${SOURCE_FILES} protobuf_output_stamp)
|
||||
|
||||
# Sources
|
||||
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${NATIVES_SOURCES} ${CONVERSIONS_SOURCES} ${CONVERSIONS_HEADERS})
|
||||
@@ -105,16 +122,27 @@ target_include_directories(
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/core/cs2_sdk
|
||||
)
|
||||
|
||||
include("makefiles/linux.base.cmake")
|
||||
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"
|
||||
)
|
||||
endif()
|
||||
|
||||
|
||||
|
||||
# Libraries
|
||||
target_link_libraries(${PROJECT_NAME} ${COUNTER_STRIKE_SHARP_LINK_LIBRARIES})
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||
PREFIX ""
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/addons/counterstrikesharp/bin/linuxsteamrt64"
|
||||
)
|
||||
add_custom_target(build-time-make-directory ALL
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_BINARY_DIR}/addons/metamod")
|
||||
configure_file(configs/counterstrikesharp.vdf "${CMAKE_BINARY_DIR}/addons/metamod/counterstrikesharp.vdf" COPYONLY)
|
||||
configure_file(configs/gamedata.json "${CMAKE_BINARY_DIR}/addons/counterstrikesharp/gamedata/gamedata.json" COPYONLY)
|
||||
|
||||
add_custom_command(
|
||||
TARGET ${PROJECT_NAME} PRE_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
${CMAKE_SOURCE_DIR}/configs ${CMAKE_BINARY_DIR}
|
||||
)
|
||||
30
README.md
30
README.md
@@ -2,32 +2,29 @@
|
||||
|
||||
CounterStrikeSharp is a server side modding framework for Counter-Strike: Global Offensive. This project attempts to implement a .NET Core scripting layer on top of a Metamod Source Plugin, allowing developers to create plugins that interact with the game server in a modern language (C#) to facilitate the creation of maintainable and testable code.
|
||||
|
||||
[Come and join our Discord](https://discord.gg/X7r3PmuYKq)
|
||||
|
||||
## History
|
||||
|
||||
This project is an ongoing migration of a previous project (titled [VSP.NET](https://github.com/roflmuffin/vspdotnet)) whereby a scripting layer was added to a Valve Server Plugin for CSGO.
|
||||
|
||||
Due to the architectural changes of CS2, the plugin is being rebuilt on the ground up, to support Linux 64-bit, something which was previously impossible.
|
||||
|
||||
## Philosophy
|
||||
|
||||
As a result, there are a few key philosophies and trade-offs that drive the project.
|
||||
- Only 64 bit is supported.
|
||||
- .NET only supports x64 on Linux; CSGO previously only supported 32 bit servers, but CS2 supports 64 bit on Linux.
|
||||
- Supporting both platforms is a lot of work for 1 person, so there are no real plans to support Windows.
|
||||
|
||||
## Install
|
||||
Development builds are currently available through GitHub actions, you can download the latest build from [there](https://github.com/roflmuffin/CounterStrikeSharp/actions/workflows/cmake-single-platform.yml).
|
||||
|
||||
Download the latest build from [here](https://github.com/roflmuffin/CounterStrikeSharp/releases). (Download the with runtime version if this is your first time installing).
|
||||
|
||||
Detailed installation instructions can be found in the [docs](https://docs.cssharp.dev/guides/getting-started/).
|
||||
|
||||
## What works?
|
||||
|
||||
_(Note, these were features in the previous VSP.NET project, but have not been implemented yet in this project)_
|
||||
|
||||
These features are the core of the platform and work pretty well/have a low risk of causing issues.
|
||||
|
||||
- [x] Console Commands, Server Commands (e.g. css_mycommand)
|
||||
- [x] Chat Commands with `!` and `/` prefixes (e.g. !mycommand)
|
||||
- [ ] **(In Progress)** Console Variables
|
||||
- [x] Console Commands, Server Commands (e.g. css_mycommand)
|
||||
- [x] Chat Commands with `!` and `/` prefixes (e.g. !mycommand)
|
||||
- [ ] **(In Progress)** Console Variables
|
||||
- [x] Game Event Handlers & Custom Events (e.g. player_death)
|
||||
- [x] Basic event value get/set (string, bool, int32, float)
|
||||
- [x] Complex event values get/set (ehandle, pawn, player controller)
|
||||
@@ -38,9 +35,10 @@ These features are the core of the platform and work pretty well/have a low risk
|
||||
- [x] OnMapStart
|
||||
- [x] OnTick
|
||||
- [x] Server Information (current map, game time, tick rate, model precaching)
|
||||
- [x] Schema System Access (access player values like current weapon, money, location etc.)
|
||||
- [x] Schema System Access (access player values like current weapon, money, location etc.)
|
||||
|
||||
## Links
|
||||
|
||||
- [Join the Discord](https://discord.gg/X7r3PmuYKq): Ask questions, provide suggestions
|
||||
- [Read the docs](https://docs.cssharp.dev/): Getting started guide, hello world plugin example
|
||||
- [Issue tracker](https://github.com/roflmuffin/CounterStrikeSharp/issues): Raise any issues here
|
||||
@@ -67,14 +65,14 @@ public class HelloWorldPlugin : BasePlugin
|
||||
|
||||
public override void Load(bool hotReload)
|
||||
{
|
||||
Console.WriteLine("Hello World!");
|
||||
Logger.LogInformation("Plugin loaded successfully!");
|
||||
}
|
||||
|
||||
[GameEventHandler]
|
||||
public HookResult OnPlayerConnect(EventPlayerConnect @event, GameEventInfo info)
|
||||
{
|
||||
// Userid will give you a reference to a CCSPlayerController class
|
||||
Log($"Player {@event.Userid.PlayerName} has connected!");
|
||||
Logger.LogInformation("Player {Name} has connected!", @event.Userid.PlayerName);
|
||||
|
||||
return HookResult.Continue;
|
||||
}
|
||||
@@ -82,7 +80,7 @@ public class HelloWorldPlugin : BasePlugin
|
||||
[ConsoleCommand("issue_warning", "Issue warning to player")]
|
||||
public void OnCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
Log("You shouldn't be doing that!");
|
||||
Logger.LogWarning("Player shouldn't be doing that");
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -94,7 +92,7 @@ I've also used the scripting context & native system that is implemented in Five
|
||||
|
||||
## How to Build
|
||||
|
||||
Building requires CMake on Linux.
|
||||
Building requires CMake.
|
||||
|
||||
Clone the repository
|
||||
|
||||
|
||||
23
configs/addons/counterstrikesharp/configs/admin_groups.json
Normal file
23
configs/addons/counterstrikesharp/configs/admin_groups.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"#css/admin": {
|
||||
"flags": [
|
||||
"@css/reservation",
|
||||
"@css/generic",
|
||||
"@css/kick",
|
||||
"@css/ban",
|
||||
"@css/unban",
|
||||
"@css/vip",
|
||||
"@css/slay",
|
||||
"@css/changemap",
|
||||
"@css/cvar",
|
||||
"@css/config",
|
||||
"@css/chat",
|
||||
"@css/vote",
|
||||
"@css/password",
|
||||
"@css/rcon",
|
||||
"@css/cheats",
|
||||
"@css/root"
|
||||
],
|
||||
"immunity": 100
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"example_command": {
|
||||
"flags": [
|
||||
"@css/custom-permission"
|
||||
],
|
||||
"check_type": "all",
|
||||
"enabled": true
|
||||
}
|
||||
}
|
||||
21
configs/addons/counterstrikesharp/configs/admins.json
Normal file
21
configs/addons/counterstrikesharp/configs/admins.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"Erikj": {
|
||||
"identity": "76561197960265731",
|
||||
"immunity": 100,
|
||||
"flags": [
|
||||
"@css/custom-flag-1",
|
||||
"@css/custom-flag-2"
|
||||
],
|
||||
"groups": [
|
||||
"#css/admin"
|
||||
],
|
||||
"command_overrides": {
|
||||
"css_plugins": true,
|
||||
"css": false
|
||||
}
|
||||
},
|
||||
"Another erikj": {
|
||||
"identity": "STEAM_0:1:1",
|
||||
"flags": ["@mycustomplugin/admin"]
|
||||
}
|
||||
}
|
||||
5
configs/addons/counterstrikesharp/configs/core.json
Normal file
5
configs/addons/counterstrikesharp/configs/core.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"PublicChatTrigger": [ "!" ],
|
||||
"SilentChatTrigger": [ "/" ],
|
||||
"FollowCS2ServerGuidelines": true
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
Place your plugin configurations here.
|
||||
|
||||
TestPlugin/TestPlugin.json
|
||||
AnotherPlugin/AnotherPlugin.json
|
||||
127
configs/addons/counterstrikesharp/gamedata/gamedata.json
Normal file
127
configs/addons/counterstrikesharp/gamedata/gamedata.json
Normal file
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"UTIL_ClientPrintAll": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x89\\x5C\\x24\\x08\\x48\\x89\\x6C\\x24\\x10\\x48\\x89\\x74\\x24\\x18\\x57\\x48\\x81\\xEC\\x70\\x01\\x2A\\x2A\\x8B\\xE9",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x49\\x89\\xD7\\x41\\x56\\x49\\x89\\xF6\\x41\\x55\\x41\\x89\\xFD"
|
||||
}
|
||||
},
|
||||
"ClientPrint": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x85\\xC9\\x0F\\x84\\x2A\\x2A\\x2A\\x2A\\x48\\x8B\\xC4\\x48\\x89\\x58\\x18",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x49\\x89\\xCF\\x41\\x56\\x49\\x89\\xD6\\x41\\x55\\x41\\x89\\xF5\\x41\\x54\\x4C\\x8D\\xA5\\xA0\\xFE\\xFF\\xFF"
|
||||
}
|
||||
},
|
||||
"CCSPlayerController_SwitchTeam": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x40\\x56\\x57\\x48\\x81\\xEC\\x2A\\x2A\\x2A\\x2A\\x48\\x8B\\xF9\\x8B\\xF2\\x8B\\xCA",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x55\\x49\\x89\\xFD\\x89\\xF7"
|
||||
}
|
||||
},
|
||||
"CCSPlayerController_ChangeTeam": {
|
||||
"offsets": {
|
||||
"windows": 90,
|
||||
"linux": 89
|
||||
}
|
||||
},
|
||||
"GiveNamedItem": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x89\\x5C\\x24\\x18\\x48\\x89\\x74\\x24\\x20\\x55\\x57\\x41\\x54\\x41\\x56\\x41\\x57\\x48\\x8D\\x6C\\x24\\xD9",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x41\\x56\\x49\\x89\\xCE\\x41\\x55\\x49\\x89\\xF5\\x41\\x54\\x49\\x89\\xD4"
|
||||
}
|
||||
},
|
||||
"UTIL_Remove": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x85\\xC9\\x74\\x2A\\x48\\x8B\\xD1\\x48\\x8B\\x0D\\x2A\\x2A\\x2A\\x2A",
|
||||
"linux": "\\x48\\x89\\xFE\\x48\\x85\\xFF\\x74\\x2A\\x48\\x8D\\x05\\x2A\\x2A\\x2A\\x2A\\x48"
|
||||
}
|
||||
},
|
||||
"Host_Say": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x44\\x89\\x4C\\x24\\x20\\x44\\x88\\x44\\x24\\x18",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x49\\x89\\xFF\\x41\\x56\\x41\\x55\\x41\\x54\\x4D\\x89\\xC4"
|
||||
}
|
||||
},
|
||||
"CBaseModelEntity_SetModel": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x89\\x5C\\x24\\x10\\x48\\x89\\x7C\\x24\\x20\\x55\\x48\\x8B\\xEC\\x48\\x83\\xEC\\x50",
|
||||
"linux": "\\x55\\x48\\x89\\xF2\\x48\\x89\\xE5\\x41\\x54\\x49\\x89\\xFC\\x48\\x8D\\x7D\\xE0\\x48\\x83\\xEC\\x18\\x48\\x8D\\x05\\xA5"
|
||||
}
|
||||
},
|
||||
"CCSPlayer_ItemServices_DropActivePlayerWeapon": {
|
||||
"offsets": {
|
||||
"windows": 20,
|
||||
"linux": 19
|
||||
}
|
||||
},
|
||||
"CCSPlayer_ItemServices_RemoveWeapons": {
|
||||
"offsets": {
|
||||
"windows": 21,
|
||||
"linux": 20
|
||||
}
|
||||
},
|
||||
"CGameSceneNode_GetSkeletonInstance": {
|
||||
"offsets": {
|
||||
"windows": 8,
|
||||
"linux": 8
|
||||
}
|
||||
},
|
||||
"CCSGameRules_TerminateRound": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x8B\\xC4\\x4C\\x89\\x48\\x20\\x55\\x56",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x41\\x56\\x41\\x55\\x49\\x89\\xFD\\x41\\x54\\x53\\x48\\x81\\xEC\\xE8"
|
||||
}
|
||||
},
|
||||
"UTIL_CreateEntityByName": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x83\\xEC\\x48\\xC6\\x44\\x24\\x30\\x00\\x4C\\x8B\\xC1",
|
||||
"linux": "\\x48\\x8D\\x05\\xC9\\xC2\\xBC"
|
||||
}
|
||||
},
|
||||
"CBaseEntity_DispatchSpawn": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x89\\x5C\\x24\\x10\\x57\\x48\\x83\\xEC\\x30\\x48\\x8B\\xDA\\x48\\x8B\\xF9\\x48\\x85\\xC9",
|
||||
"linux": "\\x48\\x85\\xFF\\x74\\x4B\\x55\\x48\\x89\\xE5\\x41\\x56"
|
||||
}
|
||||
},
|
||||
"LegacyGameEventListener": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"windows": "\\x48\\x8B\\x15\\x2A\\x2A\\x2A\\x2A\\x48\\x85\\xD2\\x74\\x2A\\x85\\xC9\\x74",
|
||||
"linux": "\\x48\\x8B\\x05\\x2A\\x2A\\x2A\\x2A\\x48\\x85\\xC0\\x74\\x2A\\x83\\xFF\\x3F\\x76\\x2A\\x31\\xC0"
|
||||
}
|
||||
},
|
||||
"CBasePlayerPawn_CommitSuicide": {
|
||||
"offsets": {
|
||||
"windows": 356,
|
||||
"linux": 356
|
||||
}
|
||||
},
|
||||
"CBaseEntity_Teleport": {
|
||||
"offsets": {
|
||||
"windows": 148,
|
||||
"linux": 147
|
||||
}
|
||||
},
|
||||
"GameEntitySystem": {
|
||||
"offsets": {
|
||||
"windows": 88,
|
||||
"linux": 80
|
||||
}
|
||||
},
|
||||
"GameEventManager": {
|
||||
"offsets": {
|
||||
"windows": 91,
|
||||
"linux": 91
|
||||
}
|
||||
}
|
||||
}
|
||||
4
configs/addons/counterstrikesharp/plugins/README.txt
Normal file
4
configs/addons/counterstrikesharp/plugins/README.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
Place plugins in this folder. Each plugin should be in its own subfolder, e.g.
|
||||
|
||||
TestPlugin/TestPlugin.dll
|
||||
AnotherPlugin/AnotherPlugin.dll
|
||||
1
configs/addons/counterstrikesharp/source/README.txt
Normal file
1
configs/addons/counterstrikesharp/source/README.txt
Normal file
@@ -0,0 +1 @@
|
||||
Place your source code for plugins here.
|
||||
@@ -1,5 +0,0 @@
|
||||
"Metamod Plugin"
|
||||
{
|
||||
"alias" "counterstrikesharp"
|
||||
"file" "addons/counterstrikesharp/bin/linuxsteamrt64/counterstrikesharp"
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
{
|
||||
"UTIL_ClientPrintAll": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x49\\x89\\xD7\\x41\\x56\\x49\\x89\\xF6\\x41\\x55\\x41\\x89\\xFD"
|
||||
}
|
||||
},
|
||||
"ClientPrint": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x49\\x89\\xCF\\x41\\x56\\x49\\x89\\xD6\\x41\\x55\\x41\\x89\\xF5\\x41\\x54\\x4C\\x8D\\xA5\\xA0\\xFE\\xFF\\xFF"
|
||||
}
|
||||
},
|
||||
"CCSPlayerController_SwitchTeam": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x55\\x49\\x89\\xFD\\x89\\xF7"
|
||||
}
|
||||
},
|
||||
"CCSPlayerController_ChangeTeam": {
|
||||
"offsets": {
|
||||
"linux": 89
|
||||
}
|
||||
},
|
||||
"GiveNamedItem": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x41\\x56\\x49\\x89\\xCE\\x41\\x55\\x49\\x89\\xF5\\x41\\x54\\x49\\x89\\xD4"
|
||||
}
|
||||
},
|
||||
"UTIL_Remove": {
|
||||
"signatures": {
|
||||
"library": "server",
|
||||
"linux": "\\x48\\x89\\xFE\\x48\\x85\\xFF\\x74\\x2A\\x48\\x8D\\x05\\x2A\\x2A\\x2A\\x2A\\x48"
|
||||
}
|
||||
},
|
||||
"CBasePlayerPawn_CommitSuicide": {
|
||||
"offsets": {
|
||||
"linux": 355
|
||||
}
|
||||
},
|
||||
"CBaseEntity_Teleport": {
|
||||
"offsets": {
|
||||
"linux": 147
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,10 @@ export default defineConfig({
|
||||
label: 'Features',
|
||||
autogenerate: { directory: 'features' },
|
||||
},
|
||||
{
|
||||
label: 'Admin Framework',
|
||||
autogenerate: { directory: 'admin-framework' },
|
||||
},
|
||||
{
|
||||
label: 'Reference',
|
||||
autogenerate: { directory: 'reference' },
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Admin Command Attributes
|
||||
description: A guide on using the Admin Command Attributes in plugins.
|
||||
---
|
||||
|
||||
## Assigning permissions to a Command
|
||||
|
||||
Assigning permissions to a Command is as easy as tagging the Command method (function callback) with either a `RequiresPermissions` or `RequiresPermissionsOr` attribute. The difference between the two attributes is that `RequiresPermissionsOr` needs only one permission to be present on the caller to be passed, while `RequiresPermissions` needs the caller to have all permissions listed. CounterStrikeSharp handles all of the permission checks behind the scenes for you.
|
||||
|
||||
```csharp
|
||||
[RequiresPermissions("@css/slay", "@custom/permission")]
|
||||
public void OnMyCommand(CCSPlayerController? caller, CommandInfo info)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
```csharp
|
||||
[RequiresPermissionsOr("@css/ban", "@custom/permission-2")]
|
||||
public void OnMyOtherCommand(CCSPlayerController? caller, CommandInfo info)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
You can even stack the attributes on top of each other, and all of them will be checked.
|
||||
|
||||
```csharp
|
||||
// Requires (@css/cvar AND @custom/permission-1) AND either (@custom/permission-1 OR @custom/permission-2).
|
||||
[RequiresPermissions("@css/cvar", "@custom/permission-1")]
|
||||
[RequiresPermissionsOr("@css/ban", "@custom/permission-2")]
|
||||
public void OnMyComplexCommand(CCSPlayerController? caller, CommandInfo info)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
You can also check for groups using the same attributes.
|
||||
|
||||
```csharp
|
||||
[RequiresPermissions("#css/simple-admin")]
|
||||
public void OnMyGroupCommand(CCSPlayerController? caller, CommandInfo info)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
56
docs/src/content/docs/admin-framework/defining-admins.md
Normal file
56
docs/src/content/docs/admin-framework/defining-admins.md
Normal file
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Defining Admins
|
||||
description: A guide on how to define admins for CounterStrikeSharp.
|
||||
---
|
||||
|
||||
## Admin Framework
|
||||
|
||||
CounterStrikeSharp has a basic framework which allows plugin developers to assign permissions to commands. When CSS is initialized, a list of admins are loaded from `configs/admins.json`.
|
||||
|
||||
## Adding Admins
|
||||
|
||||
Adding an Admin is as simple as creating a new entry in the `configs/admins.json` file. The important things you need to declare are the SteamID identifier and the permissions they have. CounterStrikeSharp will do all the heavy-lifting to decipher your SteamID. If you're familiar with SourceMod, permission definitions are slightly different as they're defined by an array of strings instead of a string of characters.
|
||||
|
||||
```json
|
||||
{
|
||||
"ZoNiCaL": {
|
||||
"identity": "76561198808392634",
|
||||
"flags": ["@css/changemap", "@css/generic"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can also manually assign permissions to players in code with `AdminManager.AddPlayerPermissions` and `AdminManager.RemovePlayerPermissions`. These changes are not saved to `configs/admins.json`.
|
||||
|
||||
:::note
|
||||
All user permissions MUST start with an at-symbol @ character, otherwise CounterStrikeSharp will not recognize the permission.
|
||||
:::
|
||||
|
||||
### Standard Permissions
|
||||
|
||||
Because the flag system is just a list of strings associated with a user, there is no real list of letter based flags like there was previously in something like SourceMod. This means as a plugin author you can declare your own flags, scoped with an `@` symbol, like `@roflmuffin/guns`, which might be the permission to allow spawning of guns in a given command.
|
||||
|
||||
However there is a somewhat standardized list of flags that it is advised you use if you are adding functionality that aligns with their purpose, and these are based on the original SourceMod flags:
|
||||
|
||||
```shell
|
||||
@css/reservation # Reserved slot access.
|
||||
@css/generic # Generic admin.
|
||||
@css/kick # Kick other players.
|
||||
@css/ban # Ban other players.
|
||||
@css/unban # Remove bans.
|
||||
@css/vip # General vip status.
|
||||
@css/slay # Slay/harm other players.
|
||||
@css/changemap # Change the map or major gameplay features.
|
||||
@css/cvar # Change most cvars.
|
||||
@css/config # Execute config files.
|
||||
@css/chat # Special chat privileges.
|
||||
@css/vote # Start or create votes.
|
||||
@css/password # Set a password on the server.
|
||||
@css/rcon # Use RCON commands.
|
||||
@css/cheats # Change sv_cheats or use cheating commands.
|
||||
@css/root # Magically enables all flags and ignores immunity values.
|
||||
```
|
||||
|
||||
:::note
|
||||
CounterStrikeSharp does not implement traditional admin command such as `!slay`, `!kick`, and `!ban`. It is up to individual plugins to implement these commands.
|
||||
:::
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
title: Defining Command Overrides
|
||||
description: A guide on how to define command overrides for CounterStrikeSharp.
|
||||
---
|
||||
|
||||
## Defining Admin and Group specific overrides
|
||||
|
||||
Command permissions can be overriden so specific admins or groups can execute the command, regardless of any permissions they may or may not have. You can define command overrides by adding the `command_overrides` key to each admin in `configs/admins.json` or group in `configs/admin_groups.json`. Command overrides can either be set to `true`, meaning the admin/group can execute the command, or `false`, meaning the admin/group cannot execute the command at all.
|
||||
|
||||
```json
|
||||
{
|
||||
"ZoNiCaL": {
|
||||
"identity": "76561198808392634",
|
||||
"flags": ["@css/changemap", "@css/generic"],
|
||||
"immunity": 100,
|
||||
"command_overrides": {
|
||||
"example_command": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
"#css/simple-admin": {
|
||||
"flags": [
|
||||
"@css/generic",
|
||||
"@css/reservation",
|
||||
"@css/ban",
|
||||
"@css/slay",
|
||||
],
|
||||
"command_overrides": {
|
||||
"example_command_2": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can set a command override for a player in code using `AdminManager.SetPlayerCommandOverride`.
|
||||
|
||||
## Replacing Command permissions
|
||||
|
||||
Command permissions can be entirely replaced. These are defined in `configs/admin_overrides.json`. The important things you need to declare are what commands are being changed and what their new flags are. Command overrides can be set to be enabled or disabled, and you can toggle them in code with `AdminManager.SetCommandOverrideState`. You can also specify whether the command override requires the caller to have all of the new permissions (similar to a `RequiresPermissions` attribute check) or only one or more permissions (similar to a `RequirePermissionsOr` attribute check). You cannot stack permission checks.
|
||||
|
||||
```json
|
||||
"css": {
|
||||
"flags": [
|
||||
"@css/custom-permission"
|
||||
],
|
||||
"check_type": "all",
|
||||
"enabled": true
|
||||
}
|
||||
```
|
||||
|
||||
You can check if a command has been overriden in code using `AdminManager.CommandIsOverriden`, and you can manipulate the command override permissions using `AdminManager.AddPermissionOverride` and `AdminManager.RemovePermissionOverride`.
|
||||
25
docs/src/content/docs/admin-framework/defining-groups.md
Normal file
25
docs/src/content/docs/admin-framework/defining-groups.md
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Defining Admin Groups
|
||||
description: A guide on how to define admin groups for CounterStrikeSharp.
|
||||
---
|
||||
|
||||
## Adding Groups
|
||||
|
||||
Groups can be created to group a series of permissions together under one tag. They are defined in `configs/admin_groups.json`. The important things you need to declare is the name of the group and the permissions they have.
|
||||
|
||||
```json
|
||||
"#css/simple-admin": {
|
||||
"flags": [
|
||||
"@css/generic",
|
||||
"@css/reservation",
|
||||
"@css/ban",
|
||||
"@css/slay",
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
:::note
|
||||
All group names MUST start with a hashtag # character, otherwise CounterStrikeSharp will recognize the group.
|
||||
:::
|
||||
|
||||
Admins can be assigned to multiple groups and they will inherit their flags. You can manually assign groups to players in code with `AdminManager.AddPlayerToGroup` and `AdminManager.RemovePlayerFromGroup`.
|
||||
36
docs/src/content/docs/admin-framework/defining-immunity.md
Normal file
36
docs/src/content/docs/admin-framework/defining-immunity.md
Normal file
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: Defining Admin Immunity
|
||||
description: A guide on how to define immunity for admins for CounterStrikeSharp.
|
||||
---
|
||||
|
||||
## Player Immunity
|
||||
|
||||
Admins can be assigned an immunity value, similar to SourceMod. If an admin or player with a lower immunity value targets another admin or player with a larger immunity value, then the command will fail. You can define an immunity value by adding the `immunity` key to each admin in `configs/admins.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
"ZoNiCaL": {
|
||||
"identity": "76561198808392634",
|
||||
"flags": ["@css/changemap", "@css/generic"],
|
||||
"immunity": 100
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can even assign an immunity value to groups. If an admin has a lower immunity value, the group's value will be used instead.
|
||||
|
||||
```json
|
||||
"#css/simple-admin": {
|
||||
"flags": [
|
||||
"@css/generic",
|
||||
"@css/reservation",
|
||||
"@css/ban",
|
||||
"@css/slay",
|
||||
],
|
||||
"immunity": 100
|
||||
}
|
||||
```
|
||||
|
||||
:::note
|
||||
CounterStrikeSharp does not automatically handle immunity checking. It is up to individual plugins to handle immunity checks as they can implement different ways of targeting players. This can be done in code with `AdminManager.CanPlayerTarget`. You can also set a player's immunity in code with `AdminManager.SetPlayerImmunity`.
|
||||
:::
|
||||
@@ -64,3 +64,39 @@ Command String: custom_command "Test Quoted" 5 13
|
||||
First Argument: custom_command
|
||||
Second Argument: Test Quoted
|
||||
```
|
||||
|
||||
## Helper Attribute
|
||||
|
||||
CounterStrikeSharp provides the `CommandHelper` attribute for Command methods (function callback) to simplify the process of checking for the correct amount of arguments and to restrict commands to being executed by the server console or by players (or both!).
|
||||
|
||||
```csharp
|
||||
[ConsoleCommand("freeze", "Freezes a client.")]
|
||||
[CommandHelper(minArgs: 1, usage: "[target]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
public void OnFreezeCommand(CCSPlayerController? caller, CommandInfo command)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
If a client tries to execute the command without the `[target]` argument, it will print a message to them in chat:
|
||||
|
||||
```shell
|
||||
[CSS] Expected usage: "!freeze [target]".
|
||||
```
|
||||
|
||||
If a command is executed by the wrong user, it will print a message to them:
|
||||
|
||||
```shell
|
||||
[CSS] This command can only be executed by clients.
|
||||
```
|
||||
|
||||
Valid `CommandUsage` values:
|
||||
|
||||
```csharp
|
||||
public enum CommandUsage
|
||||
{
|
||||
CLIENT_AND_SERVER = 0,
|
||||
CLIENT_ONLY,
|
||||
SERVER_ONLY
|
||||
}
|
||||
```
|
||||
|
||||
@@ -18,7 +18,7 @@ The first parameter type must be a subclass of the `GameEvent` class. The names
|
||||
public HookResult OnPlayerConnect(EventPlayerConnect @event, GameEventInfo info)
|
||||
{
|
||||
// Userid will give you a reference to a CCSPlayerController class
|
||||
Log($"Player {@event.Userid.PlayerName} has connected!");
|
||||
Logger.LogInformation("Player {Name} has connected!", @event.Userid.PlayerName);
|
||||
|
||||
return HookResult.Continue;
|
||||
}
|
||||
@@ -33,7 +33,7 @@ public override void Load(bool hotReload)
|
||||
{
|
||||
RegisterEventHandler<EventRoundStart>((@event, info) =>
|
||||
{
|
||||
Console.WriteLine($"Round has started with time limit of {@event.Timelimit}");
|
||||
Logger.LogInformation("Round has started with time limit of {Timelimit}", @event.Timelimit);
|
||||
|
||||
return HookResult.Continue;
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ public override void Load(bool hotReload)
|
||||
projectile.SmokeColor.X = Random.Shared.NextSingle() * 255.0f;
|
||||
projectile.SmokeColor.Y = Random.Shared.NextSingle() * 255.0f;
|
||||
projectile.SmokeColor.Z = Random.Shared.NextSingle() * 255.0f;
|
||||
Log($"Smoke grenade spawned with color {projectile.SmokeColor}");
|
||||
Logger.LogInformation("Smoke grenade spawned with color {SmokeColor}", projectile.SmokeColor);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,6 +34,13 @@ Use your IDE (Visual Studio/Rider) to add a reference to the `CounterStrikeSharp
|
||||
</Project>
|
||||
```
|
||||
|
||||
:::tip
|
||||
Instead of manually adding a reference to `CounterStrikeSharp.Api.dll`, you can install the NuGet package `CounterStrikeSharp.Api` using the following:
|
||||
```shell
|
||||
dotnet add package CounterStrikeSharp.API
|
||||
```
|
||||
:::
|
||||
|
||||
### Creating a Plugin File
|
||||
|
||||
Rename the default class file that came with your new project (by default it should be `Class1.cs`) to something more accurate, like `HelloWorldPlugin.cs`. Inside this file, we will insert the stub hello world plugin. Be sure to change the name and namespace so it matches your project name.
|
||||
|
||||
@@ -27,14 +27,14 @@ public class HelloWorldPlugin : BasePlugin
|
||||
|
||||
public override void Load(bool hotReload)
|
||||
{
|
||||
Console.WriteLine("Hello World!");
|
||||
Logger.LogInformation("Plugin loaded successfully!");
|
||||
}
|
||||
|
||||
[GameEventHandler]
|
||||
public HookResult OnPlayerConnect(EventPlayerConnect @event, GameEventInfo info)
|
||||
{
|
||||
// Userid will give you a reference to a CCSPlayerController class
|
||||
Log($"Player {@event.Userid.PlayerName} has connected!");
|
||||
Logger.LogInformation("Player {Name} has connected!", @event.Userid.PlayerName);
|
||||
|
||||
return HookResult.Continue;
|
||||
}
|
||||
@@ -42,7 +42,7 @@ public class HelloWorldPlugin : BasePlugin
|
||||
[ConsoleCommand("issue_warning", "Issue warning to player")]
|
||||
public void OnCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
Log("You shouldn't be doing that!");
|
||||
Logger.LogWarning("Player shouldn't be doing that");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
26
docs/src/content/docs/reference/core-configuration.md
Normal file
26
docs/src/content/docs/reference/core-configuration.md
Normal file
@@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Core Configuration
|
||||
description: Summary for core configuration values
|
||||
---
|
||||
|
||||
## PublicChatTrigger
|
||||
|
||||
List of characters to use for public chat triggers.
|
||||
|
||||
## SilentChatTrigger
|
||||
|
||||
List of characters to use for silent chat triggers.
|
||||
|
||||
## FollowCS2ServerGuidelines
|
||||
|
||||
Per [CS2 Server Guidelines](https://blog.counter-strike.net/index.php/server_guidelines/), certain plugin
|
||||
functionality will trigger all of the game server owner's Game Server Login Tokens
|
||||
(GSLTs) to get banned when executed on a Counter-Strike 2 game server.
|
||||
|
||||
Enabling this option will block plugins from using functionality that is known to cause this.
|
||||
This option only has any effect on CS2. Note that this does NOT guarantee that you cannot
|
||||
receive a ban.
|
||||
|
||||
:::note
|
||||
Disable this option at your own risk.
|
||||
:::
|
||||
@@ -19,7 +19,9 @@
|
||||
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\managed\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj" />
|
||||
<ProjectReference Include="..\..\managed\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj">
|
||||
<Private>false</Private>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
|
||||
Submodule libraries/hl2sdk-cs2 updated: 492b8f9663...1d394d3365
@@ -1,34 +1,29 @@
|
||||
include("makefiles/shared.cmake")
|
||||
|
||||
#SET(_ITERATOR_DEBUG_LEVEL 2)
|
||||
#set(_ITERATOR_DEBUG_LEVEL 2)
|
||||
add_definitions(-D_LINUX -DPOSIX -DLINUX -DGNUC -DCOMPILER_GCC -DPLATFORM_64BITS)
|
||||
#Add_Definitions(-DCOMPILER_MSVC -DCOMPILER_MSVC32 -D_WIN32 -D_WINDOWS -D_ALLOW_KEYWORD_MACROS -D__STDC_LIMIT_MACROS)
|
||||
|
||||
# Set(CMAKE_CXX_FLAGS_RELEASE "/D_NDEBUG /MD /wd4005 /MP")
|
||||
|
||||
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")
|
||||
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")
|
||||
|
||||
# Warnings
|
||||
Set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-uninitialized -Wno-switch -Wno-unused")
|
||||
Set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-non-virtual-dtor -Wno-overloaded-virtual")
|
||||
Set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-conversion-null -Wno-write-strings")
|
||||
Set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-offsetof -Wno-reorder")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-uninitialized -Wno-switch -Wno-unused")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-non-virtual-dtor -Wno-overloaded-virtual")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-conversion-null -Wno-write-strings")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-offsetof -Wno-reorder")
|
||||
|
||||
# Others
|
||||
Set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpmath=sse -msse -fno-strict-aliasing")
|
||||
Set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -fno-threadsafe-statics -v -fvisibility=default")
|
||||
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
|
||||
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
|
||||
)
|
||||
10
makefiles/metamod/configure_metamod.cmake
Normal file
10
makefiles/metamod/configure_metamod.cmake
Normal file
@@ -0,0 +1,10 @@
|
||||
if (WIN32)
|
||||
set(COUNTERSTRIKESHARP_VDF_PLATFORM "win64")
|
||||
else()
|
||||
set(COUNTERSTRIKESHARP_VDF_PLATFORM "linuxsteamrt64")
|
||||
endif()
|
||||
|
||||
configure_file(
|
||||
${CMAKE_CURRENT_LIST_DIR}/counterstrikesharp.vdf.in
|
||||
${PROJECT_SOURCE_DIR}/configs/addons/metamod/counterstrikesharp.vdf
|
||||
)
|
||||
5
makefiles/metamod/counterstrikesharp.vdf.in
Normal file
5
makefiles/metamod/counterstrikesharp.vdf.in
Normal file
@@ -0,0 +1,5 @@
|
||||
"Metamod Plugin"
|
||||
{
|
||||
"alias" "counterstrikesharp"
|
||||
"file" "addons/counterstrikesharp/bin/${COUNTERSTRIKESHARP_VDF_PLATFORM}/counterstrikesharp"
|
||||
}
|
||||
@@ -1,40 +1,55 @@
|
||||
Set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING
|
||||
"Only do Release and Debug"
|
||||
FORCE
|
||||
if (UNIX AND NOT APPLE)
|
||||
set(LINUX TRUE)
|
||||
endif()
|
||||
|
||||
if (WIN32 AND NOT MSVC)
|
||||
message(FATAL "MSVC restricted.")
|
||||
endif()
|
||||
|
||||
set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING
|
||||
"Only do Release and Debug"
|
||||
FORCE
|
||||
)
|
||||
|
||||
Set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
|
||||
# TODO: Use C++20 instead.
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
|
||||
set(CMAKE_STATIC_LIBRARY_PREFIX "")
|
||||
|
||||
Set(SOURCESDK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2)
|
||||
Set(METAMOD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libraries/metamod-source)
|
||||
set(SOURCESDK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libraries/hl2sdk-cs2)
|
||||
set(METAMOD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libraries/metamod-source)
|
||||
|
||||
Set(SOURCESDK ${SOURCESDK_DIR}/${BRANCH})
|
||||
Set(SOURCESDK_LIB ${SOURCESDK}/lib)
|
||||
set(SOURCESDK ${SOURCESDK_DIR}/${BRANCH})
|
||||
set(SOURCESDK_LIB ${SOURCESDK}/lib)
|
||||
|
||||
add_definitions(-DMETA_IS_SOURCE2)
|
||||
|
||||
include_directories(
|
||||
${SOURCESDK}
|
||||
${SOURCESDK}/common
|
||||
${SOURCESDK}/game/shared
|
||||
${SOURCESDK}/game/server
|
||||
${SOURCESDK}/public
|
||||
${SOURCESDK}/public/engine
|
||||
${SOURCESDK}/public/mathlib
|
||||
${SOURCESDK}/public/tier0
|
||||
${SOURCESDK}/public/tier1
|
||||
${SOURCESDK}/public/entity2
|
||||
${SOURCESDK}/public/game/server
|
||||
${SOURCESDK}/public/entity2
|
||||
${METAMOD_DIR}/core
|
||||
${METAMOD_DIR}/core/sourcehook
|
||||
libraries/dyncall/dynload
|
||||
libraries/dyncall/dyncall
|
||||
libraries/spdlog/include
|
||||
libraries/tl
|
||||
libraries/funchook/include
|
||||
libraries
|
||||
${SOURCESDK}
|
||||
${SOURCESDK}/thirdparty/protobuf-3.21.8/src
|
||||
${SOURCESDK}/common
|
||||
${SOURCESDK}/game/shared
|
||||
${SOURCESDK}/game/server
|
||||
${SOURCESDK}/public
|
||||
${SOURCESDK}/public/engine
|
||||
${SOURCESDK}/public/mathlib
|
||||
${SOURCESDK}/public/tier0
|
||||
${SOURCESDK}/public/tier1
|
||||
${SOURCESDK}/public/entity2
|
||||
${SOURCESDK}/public/game/server
|
||||
${SOURCESDK}/public/entity2
|
||||
${METAMOD_DIR}/core
|
||||
${METAMOD_DIR}/core/sourcehook
|
||||
libraries/dyncall/dynload
|
||||
libraries/dyncall/dyncall
|
||||
libraries/spdlog/include
|
||||
libraries/tl
|
||||
libraries/funchook/include
|
||||
libraries
|
||||
)
|
||||
|
||||
Project(counterstrikesharp C CXX)
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/metamod/configure_metamod.cmake)
|
||||
|
||||
if (LINUX)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
|
||||
endif()
|
||||
20
makefiles/windows.base.cmake
Normal file
20
makefiles/windows.base.cmake
Normal file
@@ -0,0 +1,20 @@
|
||||
add_definitions(
|
||||
-DCOMPILER_MSVC -DCOMPILER_MSVC64 -D_WIN32 -D_WINDOWS -D_ALLOW_KEYWORD_MACROS -D__STDC_LIMIT_MACROS
|
||||
-D_CRT_SECURE_NO_WARNINGS=1 -D_CRT_SECURE_NO_DEPRECATE=1 -D_CRT_NONSTDC_NO_DEPRECATE=1
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Zi")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4819 /wd4828 /wd5033 /permissive- /utf-8 /wd4005 /MP")
|
||||
set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /OPT:REF /OPT:ICF")
|
||||
|
||||
set(COUNTER_STRIKE_SHARP_LINK_LIBRARIES
|
||||
${SOURCESDK_LIB}/public/win64/tier0.lib
|
||||
${SOURCESDK_LIB}/public/win64/tier1.lib
|
||||
${SOURCESDK_LIB}/public/win64/interfaces.lib
|
||||
${SOURCESDK_LIB}/public/win64/mathlib.lib
|
||||
spdlog
|
||||
dynload_s
|
||||
dyncall_s
|
||||
distorm
|
||||
funchook-static
|
||||
)
|
||||
@@ -30,7 +30,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
}
|
||||
}
|
||||
|
||||
public static IntPtr AddCommand(string name, string description, bool serveronly, int flags, InputArgument callback){
|
||||
public static void AddCommand(string name, string description, bool serveronly, int flags, InputArgument callback){
|
||||
lock (ScriptContext.GlobalScriptContext.Lock) {
|
||||
ScriptContext.GlobalScriptContext.Reset();
|
||||
ScriptContext.GlobalScriptContext.Push(name);
|
||||
@@ -41,7 +41,6 @@ namespace CounterStrikeSharp.API.Core
|
||||
ScriptContext.GlobalScriptContext.SetIdentifier(0x807C6B9C);
|
||||
ScriptContext.GlobalScriptContext.Invoke();
|
||||
ScriptContext.GlobalScriptContext.CheckErrors();
|
||||
return (IntPtr)ScriptContext.GlobalScriptContext.GetResult(typeof(IntPtr));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -553,6 +552,17 @@ namespace CounterStrikeSharp.API.Core
|
||||
}
|
||||
}
|
||||
|
||||
public static void FireEventToClient(IntPtr gameevent, int clientindex){
|
||||
lock (ScriptContext.GlobalScriptContext.Lock) {
|
||||
ScriptContext.GlobalScriptContext.Reset();
|
||||
ScriptContext.GlobalScriptContext.Push(gameevent);
|
||||
ScriptContext.GlobalScriptContext.Push(clientindex);
|
||||
ScriptContext.GlobalScriptContext.SetIdentifier(0x40B7C06C);
|
||||
ScriptContext.GlobalScriptContext.Invoke();
|
||||
ScriptContext.GlobalScriptContext.CheckErrors();
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetEventName(IntPtr gameevent){
|
||||
lock (ScriptContext.GlobalScriptContext.Lock) {
|
||||
ScriptContext.GlobalScriptContext.Reset();
|
||||
|
||||
@@ -24,10 +24,15 @@ using System.Runtime.InteropServices;
|
||||
using System.Runtime.Loader;
|
||||
using CounterStrikeSharp.API.Core.Attributes;
|
||||
using CounterStrikeSharp.API.Core.Attributes.Registration;
|
||||
using CounterStrikeSharp.API.Modules.Admin;
|
||||
using CounterStrikeSharp.API.Modules.Commands;
|
||||
using CounterStrikeSharp.API.Modules.Events;
|
||||
using CounterStrikeSharp.API.Modules.Entities;
|
||||
using CounterStrikeSharp.API.Modules.Listeners;
|
||||
using CounterStrikeSharp.API.Modules.Timers;
|
||||
using McMaster.NETCore.Plugins;
|
||||
using CounterStrikeSharp.API.Modules.Config;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
@@ -49,6 +54,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
public string ModulePath { get; internal set; }
|
||||
|
||||
public string ModuleDirectory => Path.GetDirectoryName(ModulePath);
|
||||
public ILogger Logger { get; set; }
|
||||
|
||||
public virtual void Load(bool hotReload)
|
||||
{
|
||||
@@ -154,19 +160,78 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
var wrappedHandler = new Action<int, IntPtr>((i, ptr) =>
|
||||
{
|
||||
if (i == -1)
|
||||
var caller = (i != -1) ? new CCSPlayerController(NativeAPI.GetEntityFromIndex(i + 1)) : null;
|
||||
var command = new CommandInfo(ptr, caller);
|
||||
|
||||
var methodInfo = handler?.GetMethodInfo();
|
||||
|
||||
if (!AdminManager.CommandIsOverriden(name))
|
||||
{
|
||||
handler?.Invoke(null, new CommandInfo(ptr, null));
|
||||
return;
|
||||
// Do not execute command if we do not have the correct permissions.
|
||||
var permissions = methodInfo?.GetCustomAttributes<BaseRequiresPermissions>();
|
||||
if (permissions != null)
|
||||
{
|
||||
foreach (var attr in permissions)
|
||||
{
|
||||
attr.Command = name;
|
||||
if (!attr.CanExecuteCommand(caller))
|
||||
{
|
||||
command.ReplyToCommand("[CSS] You do not have the correct permissions to execute this command.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// If this command has it's permissions overriden, we will do an AND check for all permissions.
|
||||
else
|
||||
{
|
||||
// I don't know if this is the most sane implementation of this, can be edited in code review.
|
||||
var data = AdminManager.GetCommandOverrideData(name);
|
||||
if (data != null)
|
||||
{
|
||||
var attrType = (data.CheckType == "all") ? typeof(RequiresPermissions) : typeof(RequiresPermissionsOr);
|
||||
var attr = (BaseRequiresPermissions)Activator.CreateInstance(attrType, args: AdminManager.GetPermissionOverrides(name));
|
||||
attr.Command = name;
|
||||
if (!attr.CanExecuteCommand(caller))
|
||||
{
|
||||
command.ReplyToCommand("[CSS] You do not have the correct permissions to execute this command.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var entity = new CCSPlayerController(NativeAPI.GetEntityFromIndex(i + 1));
|
||||
var command = new CommandInfo(ptr, entity);
|
||||
handler?.Invoke(entity.IsValid ? entity : null, command);
|
||||
// Do not execute if we shouldn't be calling this command.
|
||||
var helperAttribute = methodInfo?.GetCustomAttribute<CommandHelperAttribute>();
|
||||
if (helperAttribute != null)
|
||||
{
|
||||
switch (helperAttribute.WhoCanExcecute)
|
||||
{
|
||||
case CommandUsage.CLIENT_AND_SERVER: break; // Allow command through.
|
||||
case CommandUsage.CLIENT_ONLY:
|
||||
if (caller == null || !caller.IsValid) { command.ReplyToCommand("[CSS] This command can only be executed by clients."); return; } break;
|
||||
case CommandUsage.SERVER_ONLY:
|
||||
if (caller != null && caller.IsValid) { command.ReplyToCommand("[CSS] This command can only be executed by the server."); return; } break;
|
||||
default: throw new ArgumentException("Unrecognised CommandUsage value passed in CommandHelperAttribute.");
|
||||
}
|
||||
|
||||
// Technically the command itself counts as the first argument,
|
||||
// but we'll just ignore that for this check.
|
||||
if (helperAttribute.MinArgs != 0 && command.ArgCount - 1 < helperAttribute.MinArgs)
|
||||
{
|
||||
command.ReplyToCommand($"[CSS] Expected usage: \"!{command.ArgByIndex(0)} {helperAttribute.Usage}\".");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
handler?.Invoke(caller, command);
|
||||
});
|
||||
|
||||
var methodInfo = handler?.GetMethodInfo();
|
||||
var helperAttribute = methodInfo?.GetCustomAttribute<CommandHelperAttribute>();
|
||||
|
||||
var subscriber = new CallbackSubscriber(handler, wrappedHandler, () => { RemoveCommand(name, handler); });
|
||||
NativeAPI.AddCommand(name, description, false, (int)ConCommandFlags.FCVAR_LINKED_CONCOMMAND, subscriber.GetInputArgument());
|
||||
NativeAPI.AddCommand(name, description, (helperAttribute?.WhoCanExcecute == CommandUsage.SERVER_ONLY),
|
||||
(int)ConCommandFlags.FCVAR_LINKED_CONCOMMAND, subscriber.GetInputArgument());
|
||||
CommandHandlers[handler] = subscriber;
|
||||
}
|
||||
|
||||
@@ -174,14 +239,10 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
var wrappedHandler = new Func<int, IntPtr, HookResult>((i, ptr) =>
|
||||
{
|
||||
if (i == -1)
|
||||
{
|
||||
return HookResult.Continue;
|
||||
}
|
||||
var caller = (i != -1) ? new CCSPlayerController(NativeAPI.GetEntityFromIndex(i + 1)) : null;
|
||||
|
||||
var entity = new CCSPlayerController(NativeAPI.GetEntityFromIndex(i + 1));
|
||||
var command = new CommandInfo(ptr, entity);
|
||||
return handler.Invoke(entity.IsValid ? entity : null, command);
|
||||
var command = new CommandInfo(ptr, caller);
|
||||
return handler.Invoke(caller, command);
|
||||
});
|
||||
|
||||
var subscriber = new CallbackSubscriber(handler, wrappedHandler, () => { RemoveCommandListener(name, handler, mode); });
|
||||
@@ -255,7 +316,8 @@ namespace CounterStrikeSharp.API.Core
|
||||
.Select(p => p.GetCustomAttribute<CastFromAttribute>()?.Type)
|
||||
.ToArray();
|
||||
|
||||
Console.WriteLine($"Registering listener for {listenerName} with {parameterTypes.Length}");
|
||||
GlobalContext.Instance.Logger.LogDebug("Registering listener for {ListenerName} with {ParameterCount} parameters",
|
||||
listenerName, parameterTypes.Length);
|
||||
|
||||
var wrappedHandler = new Action<ScriptContext>(context =>
|
||||
{
|
||||
@@ -300,6 +362,31 @@ namespace CounterStrikeSharp.API.Core
|
||||
this.RegisterConsoleCommandAttributeHandlers(instance);
|
||||
}
|
||||
|
||||
public void InitializeConfig(object instance, Type pluginType)
|
||||
{
|
||||
Type[] interfaces = pluginType.GetInterfaces();
|
||||
Func<Type, bool> predicate = (i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IPluginConfig<>));
|
||||
|
||||
// if the plugin has set a configuration type (implements IPluginConfig<>)
|
||||
if (interfaces.Any(predicate))
|
||||
{
|
||||
// IPluginConfig<>
|
||||
Type @interface = interfaces.Where(predicate).FirstOrDefault()!;
|
||||
|
||||
// custom config type passed as generic
|
||||
Type genericType = @interface!.GetGenericArguments().First();
|
||||
|
||||
var config = typeof(ConfigManager)
|
||||
.GetMethod("Load")!
|
||||
.MakeGenericMethod(genericType)
|
||||
.Invoke(null, new object[] { Path.GetFileName(ModuleDirectory) }) as IBasePluginConfig;
|
||||
|
||||
// we KNOW that we can do this "safely"
|
||||
pluginType.GetRuntimeMethod("OnConfigParsed", new Type[] { genericType })
|
||||
.Invoke(instance, new object[] { config });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers all game event handlers that are decorated with the `[GameEventHandler]` attribute.
|
||||
/// </summary>
|
||||
|
||||
32
managed/CounterStrikeSharp.API/Core/BasePluginConfig.cs
Normal file
32
managed/CounterStrikeSharp.API/Core/BasePluginConfig.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
public interface IBasePluginConfig
|
||||
{
|
||||
[JsonPropertyName("ConfigVersion")]
|
||||
int Version { get; set; }
|
||||
}
|
||||
|
||||
public class BasePluginConfig : IBasePluginConfig
|
||||
{
|
||||
[JsonPropertyName("ConfigVersion")]
|
||||
public virtual int Version { get; set; } = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,37 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core;
|
||||
|
||||
public static class Constants
|
||||
{
|
||||
public const string ROOT_BINARY_PATH = "/bin/linuxsteamrt64/";
|
||||
public const string GAME_BINARY_PATH = "/csgo/bin/linuxsteamrt64/";
|
||||
public static string ModulePrefix { get; }
|
||||
|
||||
public static string ModuleSuffix { get; }
|
||||
|
||||
public static string RootBinaryPath { get; }
|
||||
|
||||
public static string GameBinaryPath { get; }
|
||||
|
||||
static Constants()
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
ModulePrefix = "";
|
||||
ModuleSuffix = ".dll";
|
||||
GameBinaryPath = "/csgo/bin/win64/";
|
||||
RootBinaryPath = "/bin/win64";
|
||||
}
|
||||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
{
|
||||
ModulePrefix = "lib";
|
||||
ModuleSuffix = ".so";
|
||||
GameBinaryPath = "/csgo/bin/linuxsteamrt64/";
|
||||
RootBinaryPath = "/bin/linuxsteamrt64/";
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException($"""Current platform is "{RuntimeInformation.OSDescription}", but does not supported.""");
|
||||
}
|
||||
}
|
||||
}
|
||||
126
managed/CounterStrikeSharp.API/Core/CoreConfig.cs
Normal file
126
managed/CounterStrikeSharp.API/Core/CoreConfig.cs
Normal file
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using CounterStrikeSharp.API.Modules.Admin;
|
||||
using CounterStrikeSharp.API.Modules.Commands;
|
||||
using System.Collections.Generic;
|
||||
using CounterStrikeSharp.API.Core.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Serializable instance of the CoreConfig
|
||||
/// </summary>
|
||||
internal sealed partial class CoreConfigData
|
||||
{
|
||||
[JsonPropertyName("PublicChatTrigger")] public IEnumerable<string> PublicChatTrigger { get; set; } = new HashSet<string>() { "!" };
|
||||
|
||||
[JsonPropertyName("SilentChatTrigger")] public IEnumerable<string> SilentChatTrigger { get; set; } = new HashSet<string>() { "/" };
|
||||
|
||||
[JsonPropertyName("FollowCS2ServerGuidelines")] public bool FollowCS2ServerGuidelines { get; set; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configuration related to the Core API.
|
||||
/// </summary>
|
||||
public static partial class CoreConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// List of characters to use for public chat triggers.
|
||||
/// </summary>
|
||||
public static IEnumerable<string> PublicChatTrigger => _coreConfig.PublicChatTrigger;
|
||||
|
||||
/// <summary>
|
||||
/// List of characters to use for silent chat triggers.
|
||||
/// </summary>
|
||||
public static IEnumerable<string> SilentChatTrigger => _coreConfig.SilentChatTrigger;
|
||||
|
||||
/// <summary>
|
||||
/// <para>
|
||||
/// Per <see href="http://blog.counter-strike.net/index.php/server_guidelines/"/>, certain plugin
|
||||
/// functionality will trigger all of the game server owner's Game Server Login Tokens
|
||||
/// (GSLTs) to get banned when executed on a Counter-Strike 2 game server.
|
||||
/// </para>
|
||||
///
|
||||
/// <para>
|
||||
/// Enabling this option will block plugins from using functionality that is known to cause this.
|
||||
///
|
||||
/// Note that this does NOT guarantee that you cannot
|
||||
///
|
||||
/// receive a ban.
|
||||
/// </para>
|
||||
///
|
||||
/// <para>
|
||||
/// Disable this option at your own risk.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static bool FollowCS2ServerGuidelines => _coreConfig.FollowCS2ServerGuidelines;
|
||||
}
|
||||
|
||||
public static partial class CoreConfig
|
||||
{
|
||||
private static CoreConfigData _coreConfig = new CoreConfigData();
|
||||
|
||||
// TODO: ServiceCollection
|
||||
private static ILogger _logger = CoreLogging.Factory.CreateLogger("CoreConfig");
|
||||
|
||||
static CoreConfig()
|
||||
{
|
||||
CommandUtils.AddStandaloneCommand("css_core_reload", "Reloads the core configuration file.", ReloadCoreConfigCommand);
|
||||
}
|
||||
|
||||
[RequiresPermissions("@css/config")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private static void ReloadCoreConfigCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
var rootDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.Parent;
|
||||
Load(Path.Combine(rootDir.FullName, "configs", "core.json"));
|
||||
}
|
||||
|
||||
public static void Load(string coreConfigPath)
|
||||
{
|
||||
if (!File.Exists(coreConfigPath))
|
||||
{
|
||||
_logger.LogWarning("Core configuration could not be found at path \"{CoreConfigPath}\", fallback values will be used.", coreConfigPath);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var data = JsonSerializer.Deserialize<CoreConfigData>(File.ReadAllText(coreConfigPath), new JsonSerializerOptions() { ReadCommentHandling = JsonCommentHandling.Skip });
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
_coreConfig = data;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Successfully loaded core configuration.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to load core configuration, fallback values will be used");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
@@ -76,7 +77,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
GlobalContext.Instance.Logger.LogError(e, "Error invoking callback");
|
||||
}
|
||||
});
|
||||
s_callback = dg;
|
||||
@@ -140,10 +141,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
ms_references.Remove(reference);
|
||||
|
||||
Console.BackgroundColor = ConsoleColor.Blue;
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.WriteLine($"Removing function/callback reference: {reference}");
|
||||
Console.ResetColor();
|
||||
GlobalContext.Instance.Logger.LogDebug("Removing function/callback reference: {Reference}", reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core;
|
||||
|
||||
class LoadedGameData
|
||||
{
|
||||
[JsonPropertyName("signatures")] public Signatures? Signatures { get; set; }
|
||||
|
||||
|
||||
[JsonPropertyName("offsets")] public Offsets? Offsets { get; set; }
|
||||
}
|
||||
|
||||
@@ -37,36 +37,70 @@ public static class GameData
|
||||
|
||||
public static void Load(string gameDataPath)
|
||||
{
|
||||
_methods = JsonSerializer.Deserialize<Dictionary<string, LoadedGameData>>(File.ReadAllText(gameDataPath));
|
||||
try
|
||||
{
|
||||
_methods = JsonSerializer.Deserialize<Dictionary<string, LoadedGameData>>(File.ReadAllText(gameDataPath))!;
|
||||
|
||||
Console.WriteLine($"Loaded game data with {_methods.Count} methods.");
|
||||
GlobalContext.Instance.Logger.LogInformation("Loaded game data with {Count} methods.", _methods.Count);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
GlobalContext.Instance.Logger.LogError(ex, "Failed to load game data");
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetSignature(string key)
|
||||
{
|
||||
if (!_methods.ContainsKey(key)) throw new Exception($"Method {key} not found in gamedata.json");
|
||||
if (_methods[key].Signatures == null) throw new Exception($"No signatures found for {key} in gamedata.json");
|
||||
|
||||
var methodMetadata = _methods[key];
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
GlobalContext.Instance.Logger.LogDebug("Getting signature: {Key}", key);
|
||||
if (!_methods.ContainsKey(key))
|
||||
{
|
||||
return methodMetadata.Signatures!.Linux;
|
||||
throw new ArgumentException($"Method {key} not found in gamedata.json");
|
||||
}
|
||||
|
||||
return methodMetadata.Signatures!.Windows;
|
||||
var methodMetadata = _methods[key];
|
||||
if (methodMetadata.Signatures == null)
|
||||
{
|
||||
throw new InvalidOperationException($"No signatures found for {key} in gamedata.json");
|
||||
}
|
||||
|
||||
string signature;
|
||||
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
{
|
||||
signature = methodMetadata.Signatures?.Linux ?? throw new InvalidOperationException($"No Linux signature for {key} in gamedata.json");
|
||||
}
|
||||
else
|
||||
{
|
||||
signature = methodMetadata.Signatures?.Windows ?? throw new InvalidOperationException($"No Windows signature for {key} in gamedata.json");
|
||||
}
|
||||
|
||||
return signature;
|
||||
}
|
||||
|
||||
public static int GetOffset(string key)
|
||||
{
|
||||
if (!_methods.ContainsKey(key)) throw new Exception($"Method {key} not found in gamedata.json");
|
||||
if (_methods[key].Offsets == null) throw new Exception($"No offsets found for {key} in gamedata.json");
|
||||
|
||||
var methodMetadata = _methods[key];
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
if (!_methods.ContainsKey(key))
|
||||
{
|
||||
return methodMetadata.Offsets!.Linux;
|
||||
throw new Exception($"Method {key} not found in gamedata.json");
|
||||
}
|
||||
|
||||
return methodMetadata.Offsets!.Windows;
|
||||
var methodMetadata = _methods[key];
|
||||
|
||||
if (methodMetadata.Offsets == null)
|
||||
{
|
||||
throw new Exception($"No offsets found for {key} in gamedata.json");
|
||||
}
|
||||
|
||||
int offset;
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
{
|
||||
offset = methodMetadata.Offsets?.Linux ?? throw new InvalidOperationException($"No Linux offset for {key} in gamedata.json");
|
||||
}
|
||||
else
|
||||
{
|
||||
offset = methodMetadata.Offsets?.Windows ?? throw new InvalidOperationException($"No Windows offset for {key} in gamedata.json");
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
@@ -20,16 +20,25 @@ using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using CounterStrikeSharp.API.Core.Logging;
|
||||
using CounterStrikeSharp.API.Modules.Admin;
|
||||
using CounterStrikeSharp.API.Modules.Commands;
|
||||
using CounterStrikeSharp.API.Modules.Menu;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
public sealed class GlobalContext
|
||||
{
|
||||
private static GlobalContext _instance = null;
|
||||
|
||||
public ILogger Logger { get; }
|
||||
public static GlobalContext Instance => _instance;
|
||||
|
||||
public static string RootDirectory => _instance.rootDir.FullName;
|
||||
private DirectoryInfo rootDir;
|
||||
|
||||
private readonly List<PluginContext> _loadedPlugins = new();
|
||||
@@ -38,6 +47,9 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
rootDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.Parent;
|
||||
_instance = this;
|
||||
Logger = CoreLogging.Factory.CreateLogger("Core");
|
||||
|
||||
Logger.LogInformation("CounterStrikeSharp is starting up...");
|
||||
}
|
||||
|
||||
~GlobalContext()
|
||||
@@ -57,32 +69,52 @@ namespace CounterStrikeSharp.API.Core
|
||||
}
|
||||
public void InitGlobalContext()
|
||||
{
|
||||
Console.WriteLine("Loading GameData");
|
||||
GameData.Load(Path.Combine(rootDir.FullName, "gamedata", "gamedata.json"));
|
||||
var coreConfigPath = Path.Combine(rootDir.FullName, "configs", "core.json");
|
||||
Logger.LogInformation("Loading CoreConfig from {Path}", coreConfigPath);
|
||||
CoreConfig.Load(coreConfigPath);
|
||||
|
||||
for (int i = 1; i <= 9; i++)
|
||||
var gameDataPath = Path.Combine(rootDir.FullName, "gamedata", "gamedata.json");
|
||||
Logger.LogInformation("Loading GameData from {Path}", gameDataPath);
|
||||
GameData.Load(gameDataPath);
|
||||
|
||||
|
||||
var adminGroupsPath = Path.Combine(rootDir.FullName, "configs", "admin_groups.json");
|
||||
Logger.LogInformation("Loading Admin Groups from {Path}", adminGroupsPath);
|
||||
AdminManager.LoadAdminGroups(adminGroupsPath);
|
||||
|
||||
var adminPath = Path.Combine(rootDir.FullName, "configs", "admins.json");
|
||||
Logger.LogInformation("Loading Admins from {Path}", adminPath);
|
||||
AdminManager.LoadAdminData(adminPath);
|
||||
|
||||
var overridePath = Path.Combine(rootDir.FullName, "configs", "admin_overrides.json");
|
||||
Logger.LogInformation("Loading Admin Command Overrides from {Path}", overridePath);
|
||||
AdminManager.LoadCommandOverrides(overridePath);
|
||||
|
||||
AdminManager.MergeGroupPermsIntoAdmins();
|
||||
|
||||
for (var i = 1; i <= 9; i++)
|
||||
{
|
||||
AddCommand("css_" + i, "Command Key Handler", (player, info) =>
|
||||
CommandUtils.AddStandaloneCommand("css_" + i, "Command Key Handler", (player, info) =>
|
||||
{
|
||||
if (player == null) return;
|
||||
var key = Convert.ToInt32(info.GetArg(0).Split("_")[1]);
|
||||
ChatMenus.OnKeyPress(player, key);
|
||||
}, false);
|
||||
});
|
||||
}
|
||||
|
||||
Console.WriteLine("Loading C# plugins...");
|
||||
int pluginCount = LoadAllPlugins();
|
||||
Console.WriteLine($"All managed modules were loaded. {pluginCount} plugins loaded.");
|
||||
|
||||
Logger.LogInformation("Loading C# plugins...");
|
||||
var pluginCount = LoadAllPlugins();
|
||||
Logger.LogInformation("All managed modules were loaded. {PluginCount} plugins loaded.", pluginCount);
|
||||
|
||||
RegisterPluginCommands();
|
||||
}
|
||||
|
||||
public void LoadPlugin(string path)
|
||||
private void LoadPlugin(string path)
|
||||
{
|
||||
var existingPlugin = FindPluginByModulePath(path);
|
||||
if (existingPlugin != null)
|
||||
{
|
||||
throw new Exception("Plugin is already loaded.");
|
||||
throw new FileLoadException("Plugin is already loaded.");
|
||||
}
|
||||
|
||||
var plugin = new PluginContext(path, _loadedPlugins.Select(x => x.PluginId).DefaultIfEmpty(0).Max() + 1);
|
||||
@@ -90,35 +122,36 @@ namespace CounterStrikeSharp.API.Core
|
||||
_loadedPlugins.Add(plugin);
|
||||
}
|
||||
|
||||
public int LoadAllPlugins()
|
||||
private int LoadAllPlugins()
|
||||
{
|
||||
DirectoryInfo modules_directory_info;
|
||||
DirectoryInfo modulesDirectoryInfo;
|
||||
try
|
||||
{
|
||||
modules_directory_info = new DirectoryInfo(Path.Combine(rootDir.FullName, "plugins"));
|
||||
modulesDirectoryInfo = new DirectoryInfo(Path.Combine(rootDir.FullName, "plugins"));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(
|
||||
"Unable to access .NET modules directory: " + e.GetType().ToString() + " " + e.Message);
|
||||
Logger.LogError(e, "Error finding plugin path");
|
||||
return 0;
|
||||
}
|
||||
|
||||
DirectoryInfo[] proper_modules_directories;
|
||||
DirectoryInfo[] properModulesDirectories;
|
||||
try
|
||||
{
|
||||
proper_modules_directories = modules_directory_info.GetDirectories();
|
||||
properModulesDirectories = modulesDirectoryInfo.GetDirectories();
|
||||
}
|
||||
catch
|
||||
{
|
||||
proper_modules_directories = new DirectoryInfo[0];
|
||||
properModulesDirectories = Array.Empty<DirectoryInfo>();
|
||||
}
|
||||
|
||||
var filePaths = proper_modules_directories
|
||||
|
||||
var filePaths = properModulesDirectories
|
||||
.Where(d => d.GetFiles().Any((f) => f.Name == d.Name + ".dll"))
|
||||
.Select(d => d.GetFiles().First((f) => f.Name == d.Name + ".dll").FullName)
|
||||
.ToArray();
|
||||
|
||||
|
||||
foreach (var path in filePaths)
|
||||
{
|
||||
try
|
||||
@@ -127,7 +160,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"Failed to load plugin {path} with error {e}");
|
||||
Logger.LogError(e, "Failed to load plugin from {Path}", path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +198,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
|
||||
private PluginContext? FindPluginByIdOrName(string query)
|
||||
{
|
||||
|
||||
|
||||
PluginContext? plugin = null;
|
||||
if (Int32.TryParse(query, out var pluginNumber))
|
||||
{
|
||||
@@ -178,21 +211,34 @@ namespace CounterStrikeSharp.API.Core
|
||||
return plugin;
|
||||
}
|
||||
|
||||
[RequiresPermissions("@css/generic")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private void OnCSSCommand(CCSPlayerController? caller, CommandInfo info)
|
||||
{
|
||||
Utilities.ReplyToCommand(caller, " CounterStrikeSharp was created and is maintained by Michael \"roflmuffin\" Wilson.\n" +
|
||||
var currentVersion = Api.GetVersion();
|
||||
|
||||
info.ReplyToCommand(" CounterStrikeSharp was created and is maintained by Michael \"roflmuffin\" Wilson.\n" +
|
||||
" Counter-Strike Sharp uses code borrowed from SourceMod, Source.Python, FiveM, Saul Rennison and CS2Fixes.\n" +
|
||||
" See ACKNOWLEDGEMENTS.md for more information.", true);
|
||||
" See ACKNOWLEDGEMENTS.md for more information.\n" +
|
||||
" Current API Version: " + currentVersion, true);
|
||||
return;
|
||||
}
|
||||
|
||||
[RequiresPermissions("@css/generic")]
|
||||
[CommandHelper(minArgs: 1,
|
||||
usage: "[option]\n" +
|
||||
" list - List all plugins currently loaded.\n" +
|
||||
" start / load - Loads a plugin not currently loaded.\n" +
|
||||
" stop / unload - Unloads a plugin currently loaded.\n" +
|
||||
" restart / reload - Reloads a plugin currently loaded.",
|
||||
whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private void OnCSSPluginCommand(CCSPlayerController? caller, CommandInfo info)
|
||||
{
|
||||
switch (info.GetArg(1))
|
||||
{
|
||||
case "list":
|
||||
{
|
||||
Utilities.ReplyToCommand(caller, $" List of all plugins currently loaded by CounterStrikeSharp: {_loadedPlugins.Count} plugins loaded.", true);
|
||||
info.ReplyToCommand($" List of all plugins currently loaded by CounterStrikeSharp: {_loadedPlugins.Count} plugins loaded.", true);
|
||||
|
||||
foreach (var plugin in _loadedPlugins)
|
||||
{
|
||||
@@ -205,7 +251,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
sb.Append(" ");
|
||||
sb.Append(plugin.Description);
|
||||
}
|
||||
Utilities.ReplyToCommand(caller, sb.ToString(), true);
|
||||
info.ReplyToCommand(sb.ToString(), true);
|
||||
|
||||
}
|
||||
|
||||
@@ -216,7 +262,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
if (info.ArgCount < 2)
|
||||
{
|
||||
Utilities.ReplyToCommand(caller, "Valid usage: css_plugins start/load [relative plugin path || absolute plugin path] (e.g \"TestPlugin\", \"plugins/TestPlugin/TestPlugin.dll\")\n", true);
|
||||
info.ReplyToCommand("Valid usage: css_plugins start/load [relative plugin path || absolute plugin path] (e.g \"TestPlugin\", \"plugins/TestPlugin/TestPlugin.dll\")\n", true);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -231,16 +277,16 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
path = Path.Combine(rootDir.FullName, path);
|
||||
}
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
LoadPlugin(path);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"Failed to load plugin {path} with error {e}");
|
||||
Logger.LogError(e, "Failed to load plugin from {Path}", path);
|
||||
}
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -249,7 +295,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
if (info.ArgCount < 2)
|
||||
{
|
||||
Utilities.ReplyToCommand(caller, "Valid usage: css_plugins stop/unload [plugin name || #plugin id] (e.g \"TestPlugin\", \"1\")\n", true);
|
||||
info.ReplyToCommand("Valid usage: css_plugins stop/unload [plugin name || #plugin id] (e.g \"TestPlugin\", \"1\")\n", true);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -257,7 +303,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
PluginContext? plugin = FindPluginByIdOrName(pluginIdentifier);
|
||||
if (plugin == null)
|
||||
{
|
||||
Utilities.ReplyToCommand(caller, $"Could not unload plugin \"{pluginIdentifier}\")", true);
|
||||
info.ReplyToCommand($"Could not unload plugin \"{pluginIdentifier}\")", true);
|
||||
break;
|
||||
}
|
||||
plugin.Unload();
|
||||
@@ -270,7 +316,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
if (info.ArgCount < 2)
|
||||
{
|
||||
Utilities.ReplyToCommand(caller, "Valid usage: css_plugins restart/reload [plugin name || #plugin id] (e.g \"TestPlugin\", \"#1\")\n", true);
|
||||
info.ReplyToCommand("Valid usage: css_plugins restart/reload [plugin name || #plugin id] (e.g \"TestPlugin\", \"#1\")\n", true);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -279,7 +325,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
|
||||
if (plugin == null)
|
||||
{
|
||||
Utilities.ReplyToCommand(caller, $"Could not reload plugin \"{pluginIdentifier}\")", true);
|
||||
info.ReplyToCommand($"Could not reload plugin \"{pluginIdentifier}\")", true);
|
||||
break;
|
||||
}
|
||||
plugin.Unload(true);
|
||||
@@ -288,7 +334,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
}
|
||||
|
||||
default:
|
||||
Utilities.ReplyToCommand(caller, "Valid usage: css_plugins [option]\n" +
|
||||
info.ReplyToCommand("Valid usage: css_plugins [option]\n" +
|
||||
" list - List all plugins currently loaded.\n" +
|
||||
" start / load - Loads a plugin not currently loaded.\n" +
|
||||
" stop / unload - Unloads a plugin currently loaded.\n" +
|
||||
@@ -299,35 +345,11 @@ namespace CounterStrikeSharp.API.Core
|
||||
|
||||
}
|
||||
|
||||
public void RegisterPluginCommands()
|
||||
private void RegisterPluginCommands()
|
||||
{
|
||||
AddCommand("css", "Counter-Strike Sharp options.", OnCSSCommand, false);
|
||||
AddCommand("css_plugins", "Counter-Strike Sharp plugin options.", OnCSSPluginCommand, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Temporary way for base CSS to add commands without a plugin context
|
||||
*/
|
||||
private void AddCommand(string name, string description, CommandInfo.CommandCallback handler, bool serverOnly)
|
||||
{
|
||||
var wrappedHandler = new Action<int, IntPtr>((i, ptr) =>
|
||||
{
|
||||
if (i == -1)
|
||||
{
|
||||
handler?.Invoke(null, new CommandInfo(ptr, null));
|
||||
return;
|
||||
}
|
||||
|
||||
if (serverOnly) return;
|
||||
|
||||
var entity = new CCSPlayerController(NativeAPI.GetEntityFromIndex(i + 1));
|
||||
var command = new CommandInfo(ptr, entity);
|
||||
handler?.Invoke(entity.IsValid ? entity : null, command);
|
||||
});
|
||||
|
||||
var subscriber = new BasePlugin.CallbackSubscriber(handler, wrappedHandler, () => { });
|
||||
NativeAPI.AddCommand(name, description, serverOnly, (int)ConCommandFlags.FCVAR_LINKED_CONCOMMAND,
|
||||
subscriber.GetInputArgument());
|
||||
CommandUtils.AddStandaloneCommand("css", "Counter-Strike Sharp options.", OnCSSCommand);
|
||||
CommandUtils.AddStandaloneCommand("css_plugins", "Counter-Strike Sharp plugin options.", OnCSSPluginCommand);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e.StackTrace);
|
||||
Console.WriteLine(e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
28
managed/CounterStrikeSharp.API/Core/IPluginConfig.cs
Normal file
28
managed/CounterStrikeSharp.API/Core/IPluginConfig.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// An interface that describes a plugin configuration.
|
||||
/// </summary>
|
||||
public interface IPluginConfig<T> where T: IBasePluginConfig, new()
|
||||
{
|
||||
T Config { get; set; }
|
||||
|
||||
public void OnConfigParsed(T config);
|
||||
}
|
||||
}
|
||||
29
managed/CounterStrikeSharp.API/Core/Logging/CoreLogging.cs
Normal file
29
managed/CounterStrikeSharp.API/Core/Logging/CoreLogging.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core.Logging;
|
||||
|
||||
public static class CoreLogging
|
||||
{
|
||||
public static ILoggerFactory Factory { get; }
|
||||
|
||||
static CoreLogging()
|
||||
{
|
||||
var logger = new LoggerConfiguration()
|
||||
.Enrich.FromLogContext()
|
||||
.Enrich.With<SourceContextEnricher>()
|
||||
.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u4}] (cssharp:{SourceContext}) {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.File(Path.Join(new[] {GlobalContext.RootDirectory, "logs", $"log-cssharp.txt"}), rollingInterval: RollingInterval.Day, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u4}] (cssharp:{SourceContext}) {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.File(Path.Join(new[] {GlobalContext.RootDirectory, "logs", $"log-all.txt"}), rollingInterval: RollingInterval.Day, shared: true, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u4}] (cssharp:{SourceContext}) {Message:lj}{NewLine}{Exception}")
|
||||
.CreateLogger();
|
||||
|
||||
Factory =
|
||||
LoggerFactory.Create(builder =>
|
||||
{
|
||||
builder.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
32
managed/CounterStrikeSharp.API/Core/Logging/PluginLogging.cs
Normal file
32
managed/CounterStrikeSharp.API/Core/Logging/PluginLogging.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using System.IO;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core.Logging;
|
||||
|
||||
public class PluginLogging
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a logger scoped to a specific plugin
|
||||
/// <remarks>Eventually this should probably come from a service collection</remarks>
|
||||
/// </summary>
|
||||
public static ILogger CreatePluginLogger(PluginContext pluginContext)
|
||||
{
|
||||
var logger = new LoggerConfiguration()
|
||||
.Enrich.FromLogContext()
|
||||
.Enrich.With(new PluginNameEnricher(pluginContext))
|
||||
.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u4}] (plugin:{PluginName}) {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.File(Path.Join(new[] {GlobalContext.RootDirectory, "logs", $"log-{pluginContext.PluginType.Name}.txt"}), rollingInterval: RollingInterval.Day, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u4}] plugin:{PluginName} {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.File(Path.Join(new[] {GlobalContext.RootDirectory, "logs", $"log-all.txt"}), rollingInterval: RollingInterval.Day, shared: true, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u4}] plugin:{PluginName} {Message:lj}{NewLine}{Exception}")
|
||||
.CreateLogger();
|
||||
|
||||
using ILoggerFactory loggerFactory =
|
||||
LoggerFactory.Create(builder =>
|
||||
{
|
||||
builder.AddSerilog(logger);
|
||||
});
|
||||
|
||||
return loggerFactory.CreateLogger(pluginContext.PluginType);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core.Logging;
|
||||
|
||||
public class PluginNameEnricher : ILogEventEnricher
|
||||
{
|
||||
public const string PropertyName = "PluginName";
|
||||
|
||||
public PluginNameEnricher(PluginContext pluginContext)
|
||||
{
|
||||
Context = pluginContext;
|
||||
}
|
||||
|
||||
public PluginContext Context { get; }
|
||||
|
||||
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
|
||||
{
|
||||
var property = propertyFactory.CreateProperty(PropertyName, Context.PluginType.Name);
|
||||
logEvent.AddPropertyIfAbsent(property);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Linq;
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core.Logging;
|
||||
|
||||
public class SourceContextEnricher : ILogEventEnricher
|
||||
{
|
||||
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
|
||||
{
|
||||
if (logEvent.Properties.TryGetValue("SourceContext", out var property))
|
||||
{
|
||||
var scalarValue = property as ScalarValue;
|
||||
var value = scalarValue?.Value as string;
|
||||
|
||||
if (value?.StartsWith("CounterStrikeSharp") ?? false)
|
||||
{
|
||||
var lastElement = value.Split(".").LastOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(lastElement))
|
||||
{
|
||||
logEvent.AddOrUpdateProperty(new LogEventProperty("SourceContext", new ScalarValue(lastElement)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,11 @@ public partial class CBaseEntity
|
||||
Handle, position.Handle, angles.Handle, velocity.Handle);
|
||||
}
|
||||
|
||||
public void DispatchSpawn()
|
||||
{
|
||||
VirtualFunctions.CBaseEntity_DispatchSpawn(Handle, IntPtr.Zero);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shorthand for accessing an entity's CBodyComponent?.SceneNode?.AbsOrigin;
|
||||
/// </summary>
|
||||
|
||||
@@ -18,9 +18,10 @@ using CounterStrikeSharp.API.Modules.Memory;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core;
|
||||
|
||||
public partial class CGlowProperty
|
||||
public partial class CBaseModelEntity
|
||||
{
|
||||
// m_bGlowing
|
||||
public ref bool IsGlowing => ref Schema.GetRef<bool>(this.Handle, "CGlowProperty", "m_bGlowing");
|
||||
|
||||
}
|
||||
public void SetModel(string model)
|
||||
{
|
||||
VirtualFunctions.SetModel(Handle, model);
|
||||
}
|
||||
}
|
||||
31
managed/CounterStrikeSharp.API/Core/Model/CCSGameRules.cs
Normal file
31
managed/CounterStrikeSharp.API/Core/Model/CCSGameRules.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
using CounterStrikeSharp.API.Modules.Entities.Constants;
|
||||
using CounterStrikeSharp.API.Modules.Memory;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core;
|
||||
|
||||
public partial class CCSGameRules
|
||||
{
|
||||
/// <summary>
|
||||
/// Terminate the round with the given delay and reason.
|
||||
/// </summary>
|
||||
public void TerminateRound(float delay, RoundEndReason roundEndReason)
|
||||
{
|
||||
VirtualFunctions.TerminateRound(Handle, roundEndReason, delay);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ public partial class CCSPlayerController
|
||||
|
||||
public void PrintToConsole(string message)
|
||||
{
|
||||
NativeAPI.PrintToConsole((int)EntityIndex.Value.Value, message);
|
||||
NativeAPI.PrintToConsole((int)EntityIndex.Value.Value, $"{message}\n\0");
|
||||
}
|
||||
|
||||
public void PrintToChat(string message)
|
||||
@@ -47,9 +47,37 @@ public partial class CCSPlayerController
|
||||
Duration = 5,
|
||||
Userid = this
|
||||
};
|
||||
@event.FireEvent(false);
|
||||
@event.FireEventToClient(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drops the active player weapon on the ground.
|
||||
/// </summary>
|
||||
public void DropActiveWeapon()
|
||||
{
|
||||
if (!PlayerPawn.IsValid) return;
|
||||
if (!PlayerPawn.Value.IsValid) return;
|
||||
if (PlayerPawn.Value.ItemServices == null) return;
|
||||
if (PlayerPawn.Value.WeaponServices == null) return;
|
||||
if (!PlayerPawn.Value.WeaponServices.ActiveWeapon.IsValid) return;
|
||||
|
||||
CCSPlayer_ItemServices itemServices = new CCSPlayer_ItemServices(PlayerPawn.Value.ItemServices.Handle);
|
||||
CCSPlayer_WeaponServices weponServices = new CCSPlayer_WeaponServices(PlayerPawn.Value.WeaponServices.Handle);
|
||||
itemServices.DropActivePlayerWeapon(weponServices.ActiveWeapon.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every weapon from the player.
|
||||
/// </summary>
|
||||
public void RemoveWeapons()
|
||||
{
|
||||
if (!PlayerPawn.IsValid) return;
|
||||
if (!PlayerPawn.Value.IsValid) return;
|
||||
if (PlayerPawn.Value.ItemServices == null) return;
|
||||
|
||||
CCSPlayer_ItemServices itemServices = new CCSPlayer_ItemServices(PlayerPawn.Value.ItemServices.Handle);
|
||||
itemServices.RemoveWeapons();
|
||||
}
|
||||
|
||||
public bool IsBot => ((PlayerFlags)Flags).HasFlag(PlayerFlags.FL_FAKECLIENT);
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
using CounterStrikeSharp.API.Modules.Memory;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core;
|
||||
|
||||
public partial class CCSPlayer_ItemServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Drops the active player weapon on the ground.
|
||||
/// </summary>
|
||||
public void DropActivePlayerWeapon(CBasePlayerWeapon activeWeapon)
|
||||
{
|
||||
VirtualFunction.CreateVoid<nint, nint>(Handle, GameData.GetOffset("CCSPlayer_ItemServices_DropActivePlayerWeapon"))(Handle, activeWeapon.Handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every weapon from the player.
|
||||
/// </summary>
|
||||
public void RemoveWeapons()
|
||||
{
|
||||
VirtualFunction.CreateVoid<nint>(Handle, GameData.GetOffset("CCSPlayer_ItemServices_RemoveWeapons"))(Handle);
|
||||
}
|
||||
}
|
||||
30
managed/CounterStrikeSharp.API/Core/Model/CGameSceneNode.cs
Normal file
30
managed/CounterStrikeSharp.API/Core/Model/CGameSceneNode.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
using CounterStrikeSharp.API.Modules.Memory;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core;
|
||||
|
||||
public partial class CGameSceneNode
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the <see cref="CSkeletonInstance"/> instance from the node.
|
||||
/// </summary>
|
||||
public CSkeletonInstance GetSkeletonInstance()
|
||||
{
|
||||
return new CSkeletonInstance(VirtualFunction.Create<nint, nint>(Handle, GameData.GetOffset("CGameSceneNode_GetSkeletonInstance"))(Handle));
|
||||
}
|
||||
}
|
||||
@@ -355,6 +355,13 @@ public enum BrushSolidities_e : uint
|
||||
BRUSHSOLID_ALWAYS = 0x2,
|
||||
}
|
||||
|
||||
public enum C4LightEffect_t : uint
|
||||
{
|
||||
eLightEffectNone = 0x0,
|
||||
eLightEffectDropped = 0x1,
|
||||
eLightEffectThirdPersonHeld = 0x2,
|
||||
}
|
||||
|
||||
public enum CAnimationGraphVisualizerPrimitiveType : uint
|
||||
{
|
||||
ANIMATIONGRAPHVISUALIZERPRIMITIVETYPE_Text = 0x0,
|
||||
@@ -2773,6 +2780,7 @@ public enum TakeDamageFlags_t : uint
|
||||
DFLAG_RADIUS_DMG = 0x400,
|
||||
DMG_LASTDFLAG = 0x400,
|
||||
DFLAG_IGNORE_ARMOR = 0x800,
|
||||
DFLAG_SUPPRESS_UTILREMOVE = 0x1000,
|
||||
}
|
||||
|
||||
public enum TextureRepetitionMode_t : uint
|
||||
@@ -3927,6 +3935,9 @@ public partial class CBaseCSGrenadeProjectile : CBaseGrenade
|
||||
{
|
||||
public CBaseCSGrenadeProjectile (IntPtr pointer) : base(pointer) {}
|
||||
|
||||
// m_vInitialPosition
|
||||
public Vector InitialPosition => Schema.GetDeclaredClass<Vector>(this.Handle, "CBaseCSGrenadeProjectile", "m_vInitialPosition");
|
||||
|
||||
// m_vInitialVelocity
|
||||
public Vector InitialVelocity => Schema.GetDeclaredClass<Vector>(this.Handle, "CBaseCSGrenadeProjectile", "m_vInitialVelocity");
|
||||
|
||||
@@ -3972,6 +3983,12 @@ public partial class CBaseCSGrenadeProjectile : CBaseGrenade
|
||||
// m_nTicksAtZeroVelocity
|
||||
public ref Int32 TicksAtZeroVelocity => ref Schema.GetRef<Int32>(this.Handle, "CBaseCSGrenadeProjectile", "m_nTicksAtZeroVelocity");
|
||||
|
||||
// m_bHasEverHitPlayer
|
||||
public ref bool HasEverHitPlayer => ref Schema.GetRef<bool>(this.Handle, "CBaseCSGrenadeProjectile", "m_bHasEverHitPlayer");
|
||||
|
||||
// m_bClearFromPlayers
|
||||
public ref bool ClearFromPlayers => ref Schema.GetRef<bool>(this.Handle, "CBaseCSGrenadeProjectile", "m_bClearFromPlayers");
|
||||
|
||||
}
|
||||
|
||||
public partial class CBaseDMStart : CPointEntity
|
||||
@@ -7099,8 +7116,8 @@ public partial class CCSGameRules : CTeamplayRules
|
||||
// m_nShorthandedBonusLastEvalRound
|
||||
public ref Int32 ShorthandedBonusLastEvalRound => ref Schema.GetRef<Int32>(this.Handle, "CCSGameRules", "m_nShorthandedBonusLastEvalRound");
|
||||
|
||||
// m_bMatchAbortedDueToPlayerBan
|
||||
public ref bool MatchAbortedDueToPlayerBan => ref Schema.GetRef<bool>(this.Handle, "CCSGameRules", "m_bMatchAbortedDueToPlayerBan");
|
||||
// m_nMatchAbortedEarlyReason
|
||||
public ref Int32 MatchAbortedEarlyReason => ref Schema.GetRef<Int32>(this.Handle, "CCSGameRules", "m_nMatchAbortedEarlyReason");
|
||||
|
||||
// m_bHasTriggeredRoundStartMusic
|
||||
public ref bool HasTriggeredRoundStartMusic => ref Schema.GetRef<bool>(this.Handle, "CCSGameRules", "m_bHasTriggeredRoundStartMusic");
|
||||
@@ -7515,6 +7532,12 @@ public partial class CCSPlayer_MovementServices : CPlayer_MovementServices_Human
|
||||
// m_flStamina
|
||||
public ref float Stamina => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flStamina");
|
||||
|
||||
// m_flHeightAtJumpStart
|
||||
public ref float HeightAtJumpStart => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flHeightAtJumpStart");
|
||||
|
||||
// m_flMaxJumpHeightThisJump
|
||||
public ref float MaxJumpHeightThisJump => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flMaxJumpHeightThisJump");
|
||||
|
||||
}
|
||||
|
||||
public partial class CCSPlayer_PingServices : CPlayerPawnComponent
|
||||
@@ -7792,6 +7815,9 @@ public partial class CCSPlayerController : CBasePlayerController
|
||||
// m_uiAbandonRecordedReason
|
||||
public ref UInt32 UiAbandonRecordedReason => ref Schema.GetRef<UInt32>(this.Handle, "CCSPlayerController", "m_uiAbandonRecordedReason");
|
||||
|
||||
// m_bCannotBeKicked
|
||||
public ref bool CannotBeKicked => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bCannotBeKicked");
|
||||
|
||||
// m_bEverFullyConnected
|
||||
public ref bool EverFullyConnected => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bEverFullyConnected");
|
||||
|
||||
@@ -7909,9 +7935,15 @@ public partial class CCSPlayerController : CBasePlayerController
|
||||
// m_bGaveTeamDamageWarningThisRound
|
||||
public ref bool GaveTeamDamageWarningThisRound => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bGaveTeamDamageWarningThisRound");
|
||||
|
||||
// m_dblLastReceivedPacketPlatFloatTime
|
||||
public ref double DblLastReceivedPacketPlatFloatTime => ref Schema.GetRef<double>(this.Handle, "CCSPlayerController", "m_dblLastReceivedPacketPlatFloatTime");
|
||||
|
||||
// m_LastTeamDamageWarningTime
|
||||
public ref float LastTeamDamageWarningTime => ref Schema.GetRef<float>(this.Handle, "CCSPlayerController", "m_LastTeamDamageWarningTime");
|
||||
|
||||
// m_LastTimePlayerWasDisconnectedForPawnsRemove
|
||||
public ref float LastTimePlayerWasDisconnectedForPawnsRemove => ref Schema.GetRef<float>(this.Handle, "CCSPlayerController", "m_LastTimePlayerWasDisconnectedForPawnsRemove");
|
||||
|
||||
}
|
||||
|
||||
public partial class CCSPlayerController_ActionTrackingServices : CPlayerControllerComponent
|
||||
@@ -8046,6 +8078,9 @@ public partial class CCSPlayerPawn : CCSPlayerPawnBase
|
||||
set { Schema.SetString(this.Handle, "CCSPlayerPawn", "m_szLastPlaceName", value); }
|
||||
}
|
||||
|
||||
// m_bInHostageResetZone
|
||||
public ref bool InHostageResetZone => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerPawn", "m_bInHostageResetZone");
|
||||
|
||||
// m_bInBuyZone
|
||||
public ref bool InBuyZone => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerPawn", "m_bInBuyZone");
|
||||
|
||||
@@ -12825,6 +12860,9 @@ public partial class CHostage : CHostageExpresserShim
|
||||
// m_vecSpawnGroundPos
|
||||
public Vector SpawnGroundPos => Schema.GetDeclaredClass<Vector>(this.Handle, "CHostage", "m_vecSpawnGroundPos");
|
||||
|
||||
// m_vecHostageResetPosition
|
||||
public Vector HostageResetPosition => Schema.GetDeclaredClass<Vector>(this.Handle, "CHostage", "m_vecHostageResetPosition");
|
||||
|
||||
}
|
||||
|
||||
public partial class CHostageAlias_info_hostage_spawn : CHostage
|
||||
@@ -14153,6 +14191,28 @@ public partial class CLogicDistanceCheck : CLogicalEntity
|
||||
|
||||
}
|
||||
|
||||
public partial class CLogicEventListener : CLogicalEntity
|
||||
{
|
||||
public CLogicEventListener (IntPtr pointer) : base(pointer) {}
|
||||
|
||||
// m_strEventName
|
||||
public string StrEventName
|
||||
{
|
||||
get { return Schema.GetUtf8String(this.Handle, "CLogicEventListener", "m_strEventName"); }
|
||||
set { Schema.SetString(this.Handle, "CLogicEventListener", "m_strEventName", value); }
|
||||
}
|
||||
|
||||
// m_bIsEnabled
|
||||
public ref bool IsEnabled => ref Schema.GetRef<bool>(this.Handle, "CLogicEventListener", "m_bIsEnabled");
|
||||
|
||||
// m_nTeam
|
||||
public ref Int32 Team => ref Schema.GetRef<Int32>(this.Handle, "CLogicEventListener", "m_nTeam");
|
||||
|
||||
// m_OnEventFired
|
||||
public CEntityIOOutput OnEventFired => Schema.GetDeclaredClass<CEntityIOOutput>(this.Handle, "CLogicEventListener", "m_OnEventFired");
|
||||
|
||||
}
|
||||
|
||||
public partial class CLogicGameEvent : CLogicalEntity
|
||||
{
|
||||
public CLogicGameEvent (IntPtr pointer) : base(pointer) {}
|
||||
@@ -20138,6 +20198,12 @@ public partial class CTriggerGravity : CBaseTrigger
|
||||
|
||||
}
|
||||
|
||||
public partial class CTriggerHostageReset : CBaseTrigger
|
||||
{
|
||||
public CTriggerHostageReset (IntPtr pointer) : base(pointer) {}
|
||||
|
||||
}
|
||||
|
||||
public partial class CTriggerHurt : CBaseTrigger
|
||||
{
|
||||
public CTriggerHurt (IntPtr pointer) : base(pointer) {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
@@ -20,8 +20,9 @@ using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using CounterStrikeSharp.API.Core.Attributes;
|
||||
using CounterStrikeSharp.API.Modules.Events;
|
||||
using CounterStrikeSharp.API.Core.Logging;
|
||||
using McMaster.NETCore.Plugins;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
@@ -42,6 +43,9 @@ namespace CounterStrikeSharp.API.Core
|
||||
private readonly string _path;
|
||||
private readonly FileSystemWatcher _fileWatcher;
|
||||
|
||||
// TOOD: ServiceCollection
|
||||
private ILogger _logger = CoreLogging.Factory.CreateLogger<PluginContext>();
|
||||
|
||||
public PluginContext(string path, int id)
|
||||
{
|
||||
_path = path;
|
||||
@@ -62,7 +66,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
if (e.FullPath == path)
|
||||
{
|
||||
Console.WriteLine($"Plugin {Name} has been deleted, unloading...");
|
||||
_logger.LogInformation("Plugin {Name} has been deleted, unloading...", Name);
|
||||
Unload(true);
|
||||
}
|
||||
};
|
||||
@@ -74,7 +78,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
|
||||
private Task OnReloadedAsync(object sender, PluginReloadedEventArgs eventargs)
|
||||
{
|
||||
Console.WriteLine($"Reloading plugin {Name}");
|
||||
_logger.LogInformation("Reloading plugin {Name}", Name);
|
||||
_assemblyLoader = eventargs.Loader;
|
||||
Unload(hotReload: true);
|
||||
Load(hotReload: true);
|
||||
@@ -99,13 +103,15 @@ namespace CounterStrikeSharp.API.Core
|
||||
throw new Exception(
|
||||
$"Plugin \"{Path.GetFileName(_path)}\" requires a newer version of CounterStrikeSharp. The plugin expects version [{minimumApiVersion}] but the current version is [{currentVersion}].");
|
||||
|
||||
Console.WriteLine($"Loading plugin: {pluginType.Name}");
|
||||
_logger.LogInformation("Loading plugin {Name}", pluginType.Name);
|
||||
_plugin = (BasePlugin)Activator.CreateInstance(pluginType)!;
|
||||
_plugin.ModulePath = _path;
|
||||
_plugin.RegisterAllAttributes(_plugin);
|
||||
_plugin.Logger = PluginLogging.CreatePluginLogger(this);
|
||||
_plugin.InitializeConfig(_plugin, pluginType);
|
||||
_plugin.Load(hotReload);
|
||||
|
||||
Console.WriteLine($"Finished loading plugin: {Name}");
|
||||
_logger.LogInformation("Finished loading plugin {Name}", Name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +119,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
{
|
||||
var cachedName = Name;
|
||||
|
||||
Console.WriteLine($"Unloading plugin {Name}");
|
||||
_logger.LogInformation("Unloading plugin {Name}", Name);
|
||||
|
||||
_plugin.Unload(hotReload);
|
||||
|
||||
@@ -125,7 +131,7 @@ namespace CounterStrikeSharp.API.Core
|
||||
_fileWatcher.Dispose();
|
||||
}
|
||||
|
||||
Console.WriteLine($"Finished unloading plugin {cachedName}");
|
||||
_logger.LogInformation("Finished unloading plugin {Name}", Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,13 +67,11 @@ namespace CounterStrikeSharp.API.Core
|
||||
|
||||
public unsafe ScriptContext()
|
||||
{
|
||||
//Console.WriteLine("Global context address: " + (IntPtr)m_extContext);
|
||||
}
|
||||
|
||||
public unsafe ScriptContext(fxScriptContext* context)
|
||||
{
|
||||
m_extContext = *context;
|
||||
//Console.WriteLine("Global context address: " + (IntPtr)m_extContext);
|
||||
}
|
||||
|
||||
private readonly ConcurrentQueue<Action> ms_finalizers = new ConcurrentQueue<Action>();
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<EnableDynamicLoading>true</EnableDynamicLoading>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<EnablePackageValidation>true</EnablePackageValidation>
|
||||
<NoWarn>$(NoWarn);CS1591</NoWarn>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<Authors>Roflmuffin</Authors>
|
||||
<Description>Official server side runtime assembly for CounterStrikeSharp</Description>
|
||||
<PackageProjectUrl>http://docs.cssharp.dev/</PackageProjectUrl>
|
||||
<RepositoryUrl>https://github.com/roflmuffin/CounterStrikeSharp</RepositoryUrl>
|
||||
<PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
|
||||
<PublishRepositoryUrl>true</PublishRepositoryUrl>
|
||||
<IncludeSymbols>true</IncludeSymbols>
|
||||
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<None Remove="Modules\Commands\CommandInfo" />
|
||||
@@ -11,6 +23,10 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="McMaster.NETCore.Plugins" Version="1.4.0" />
|
||||
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -20,11 +20,16 @@ public class ColorMarshaler : ICustomMarshal<Color>
|
||||
{
|
||||
public Color NativeToManaged(IntPtr pointer)
|
||||
{
|
||||
return Color.FromArgb(Marshal.ReadInt32(pointer));
|
||||
var color = Marshal.ReadInt32(pointer);
|
||||
var alpha = (byte)((color >> 24) & 0xFF);
|
||||
var blue = (byte)((color >> 16) & 0xFF);
|
||||
var green = (byte)((color >> 8) & 0xFF);
|
||||
var red = (byte)(color & 0xFF);
|
||||
return Color.FromArgb(alpha, red, green, blue);
|
||||
}
|
||||
|
||||
public void ManagedToNative(IntPtr pointer, Color managedObj)
|
||||
{
|
||||
Marshal.WriteInt32(pointer, managedObj.ToArgb());
|
||||
Marshal.WriteInt32(pointer, (managedObj.A << 24) | (managedObj.B << 16) | (managedObj.G << 8) | managedObj.R);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json;
|
||||
using System.Linq;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
|
||||
public partial class CommandData
|
||||
{
|
||||
[JsonPropertyName("flags")] public required HashSet<string> Flags { get; init; }
|
||||
[JsonPropertyName("enabled")] public bool Enabled { get; set; } = true;
|
||||
[JsonPropertyName("check_type")] public required string CheckType { get; init; }
|
||||
}
|
||||
|
||||
public static partial class AdminManager
|
||||
{
|
||||
private static Dictionary<string, CommandData> CommandOverrides = new();
|
||||
public static void LoadCommandOverrides(string overridePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(overridePath))
|
||||
{
|
||||
Console.WriteLine("Admin command overrides file not found. Skipping admin command overrides load.");
|
||||
return;
|
||||
}
|
||||
|
||||
var overridesFromFile = JsonSerializer.Deserialize<Dictionary<string, CommandData>>
|
||||
(File.ReadAllText(overridePath), new JsonSerializerOptions() { ReadCommentHandling = JsonCommentHandling.Skip });
|
||||
if (overridesFromFile == null) { throw new FileNotFoundException(); }
|
||||
foreach (var (command, overrideDef) in overridesFromFile)
|
||||
{
|
||||
if (CommandOverrides.ContainsKey(command))
|
||||
{
|
||||
CommandOverrides[command].Flags.UnionWith(overrideDef.Flags);
|
||||
}
|
||||
else
|
||||
{
|
||||
CommandOverrides.Add(command, overrideDef);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"Loaded {CommandOverrides.Count} admin command overrides.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Failed to load admin command overrides: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if a command has overriden permissions.
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
/// <returns>True if the command has overriden permissions, false if not.</returns>
|
||||
public static bool CommandIsOverriden(string commandName)
|
||||
{
|
||||
CommandOverrides.TryGetValue(commandName, out var overrideDef);
|
||||
if (overrideDef == null) return false;
|
||||
return overrideDef.Enabled && overrideDef?.Flags.Count() > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grabs the data for a command override that was loaded from "configs/admin_overrides.json".
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
/// <returns>CommandData class if found, null if not.</returns>
|
||||
public static CommandData? GetCommandOverrideData(string commandName)
|
||||
{
|
||||
return CommandOverrides.GetValueOrDefault(commandName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grabs the new, overriden flags for a command.
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
/// <returns>If the command is valid, a valid array of flags.</returns>
|
||||
public static string[] GetPermissionOverrides(string commandName)
|
||||
{
|
||||
CommandOverrides.TryGetValue(commandName, out var overrideDef);
|
||||
return overrideDef?.Flags.ToArray() ?? new string[] { };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new permission to a command override.
|
||||
/// This is not saved to "configs/admin_overrides.json".
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
/// <param name="permissions">Permissions to add to the command override.</param>
|
||||
public static void AddPermissionOverride(string commandName, params string[] permissions)
|
||||
{
|
||||
CommandOverrides.TryGetValue(commandName, out var overrideDef);
|
||||
if (overrideDef == null)
|
||||
{
|
||||
overrideDef = new CommandData()
|
||||
{
|
||||
Flags = new(permissions),
|
||||
Enabled = true,
|
||||
CheckType = "all"
|
||||
};
|
||||
|
||||
CommandOverrides[commandName] = overrideDef;
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var flag in permissions)
|
||||
{
|
||||
overrideDef.Flags.Add(flag);
|
||||
}
|
||||
CommandOverrides[commandName] = overrideDef;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a permission from a command override.
|
||||
/// This is not saved to "configs/admin_overrides.json".
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
/// <param name="permissions">Permissions to remove from the command override.</param>
|
||||
public static void RemovePermissionOverride(string commandName, params string[] permissions)
|
||||
{
|
||||
CommandOverrides.TryGetValue(commandName, out var overrideDef);
|
||||
if (overrideDef == null) return;
|
||||
|
||||
overrideDef.Flags.ExceptWith(permissions);
|
||||
CommandOverrides[commandName] = overrideDef;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all permissions from a command override.
|
||||
/// This is not saved to "configs/admin_overrides.json".
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
/// <param name="disable">Whether to disable the command override after clearing.</param>
|
||||
public static void ClearPermissionOverride(string commandName, bool disable = true)
|
||||
{
|
||||
CommandOverrides.TryGetValue(commandName, out var overrideDef);
|
||||
if (overrideDef == null) return;
|
||||
|
||||
overrideDef.Flags?.Clear();
|
||||
overrideDef.Enabled = !disable;
|
||||
CommandOverrides[commandName] = overrideDef;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a command override.
|
||||
/// This is not saved to "configs/admin_overrides.json".
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
public static void DeleteCommandOverride(string commandName)
|
||||
{
|
||||
if (!CommandOverrides.ContainsKey(commandName)) return;
|
||||
CommandOverrides.Remove(commandName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a command override to be enabled or disabled.
|
||||
/// This is not saved to "configs/admin_overrides.json".
|
||||
/// </summary>
|
||||
/// <param name="commandName">Name of the command.</param>
|
||||
/// <param name="state">New state of the command override.</param>
|
||||
public static void SetCommandOverideState(string commandName, bool state)
|
||||
{
|
||||
CommandOverrides.TryGetValue(commandName, out var overrideDef);
|
||||
if (overrideDef == null) return;
|
||||
|
||||
overrideDef.Flags?.Clear();
|
||||
overrideDef.Enabled = state;
|
||||
CommandOverrides[commandName] = overrideDef;
|
||||
}
|
||||
}
|
||||
}
|
||||
193
managed/CounterStrikeSharp.API/Modules/Admin/AdminGroup.cs
Normal file
193
managed/CounterStrikeSharp.API/Modules/Admin/AdminGroup.cs
Normal file
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Entities;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
public partial class AdminData
|
||||
{
|
||||
[JsonPropertyName("groups")] public HashSet<string> Groups { get; init; } = new();
|
||||
}
|
||||
public partial class AdminGroupData
|
||||
{
|
||||
[JsonPropertyName("flags")] public required HashSet<string> Flags { get; init; }
|
||||
[JsonPropertyName("immunity")] public uint Immunity { get; set; } = 0;
|
||||
[JsonPropertyName("command_overrides")] public Dictionary<string, bool> CommandOverrides { get; init; } = new();
|
||||
}
|
||||
|
||||
public static partial class AdminManager
|
||||
{
|
||||
private static Dictionary<string, AdminGroupData> Groups = new();
|
||||
|
||||
public static void LoadAdminGroups(string adminGroupsPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(adminGroupsPath))
|
||||
{
|
||||
Console.WriteLine("Admin groups file not found. Skipping admin groups load.");
|
||||
return;
|
||||
}
|
||||
|
||||
var groupsFromFile = JsonSerializer.Deserialize<Dictionary<string, AdminGroupData>>(File.ReadAllText(adminGroupsPath), new JsonSerializerOptions() { ReadCommentHandling = JsonCommentHandling.Skip });
|
||||
if (groupsFromFile == null) { throw new FileNotFoundException(); }
|
||||
foreach (var (key, groupDef) in groupsFromFile)
|
||||
{
|
||||
if (Groups.ContainsKey(key))
|
||||
{
|
||||
Groups[key].Flags.UnionWith(groupDef.Flags);
|
||||
if (groupDef.Immunity > Groups[key].Immunity)
|
||||
{
|
||||
Groups[key].Immunity = groupDef.Immunity;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Groups.Add(key, groupDef);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"Loaded {Groups.Count} admin groups.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Failed to load admin groups: {ex}");
|
||||
}
|
||||
|
||||
// Loop over each of the admins. If one of our admins is in a group,
|
||||
// add the flags from the group to their admin definition and change
|
||||
// the admin's immunity if it's higher.
|
||||
foreach (var adminData in Admins.Values)
|
||||
{
|
||||
var groups = adminData.Groups;
|
||||
foreach (var group in groups)
|
||||
{
|
||||
// roflmuffin is probably smart enough to condense this function down ;)
|
||||
if (Groups.TryGetValue(group, out var groupData))
|
||||
{
|
||||
adminData.Flags.UnionWith(groupData.Flags);
|
||||
if (groupData.Immunity > adminData.Immunity)
|
||||
{
|
||||
adminData.Immunity = groupData.Immunity;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if the player is part of an admin group.
|
||||
/// </summary>
|
||||
/// <param name="player">Player controller.</param>
|
||||
/// <param name="groups">Groups to check for.</param>
|
||||
/// <returns>True if a player is part of all of the groups provided, false if not.</returns>
|
||||
public static bool PlayerInGroup(CCSPlayerController? player, params string[] groups)
|
||||
{
|
||||
// This is here for cases where the server console is attempting to call commands.
|
||||
// The server console should have access to all commands, regardless of groups.
|
||||
if (player == null) return true;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) { return false; }
|
||||
var playerData = GetPlayerAdminData((SteamID)player.SteamID);
|
||||
return playerData?.Groups.IsSupersetOf(groups) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if the player is part of an admin group.
|
||||
/// </summary>
|
||||
/// <param name="steamId">SteamID of the player.</param>
|
||||
/// <param name="groups">Groups to check for.</param>
|
||||
/// <returns>True if a player is part of all of the groups provided, false if not.</returns>
|
||||
public static bool PlayerInGroup(SteamID steamId, params string[] groups)
|
||||
{
|
||||
var playerData = GetPlayerAdminData(steamId);
|
||||
return playerData?.Groups.IsSupersetOf(groups) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a player to a group.
|
||||
/// </summary>
|
||||
/// <param name="player">Player controller.</param>
|
||||
/// <param name="groups">Groups to add the player to.</param>
|
||||
public static void AddPlayerToGroup(CCSPlayerController? player, params string[] groups)
|
||||
{
|
||||
if (player == null) return;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) { return; }
|
||||
AddPlayerToGroup((SteamID)player.SteamID, groups);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a player to a group.
|
||||
/// </summary>
|
||||
/// <param name="steamId">SteamID of the player.</param>
|
||||
/// <param name="groups">Groups to add the player to.</param>
|
||||
public static void AddPlayerToGroup(SteamID steamId, params string[] groups)
|
||||
{
|
||||
var data = GetPlayerAdminData(steamId);
|
||||
if (data == null)
|
||||
{
|
||||
data = new AdminData()
|
||||
{
|
||||
Identity = steamId.SteamId64.ToString(),
|
||||
Flags = new(),
|
||||
Groups = new(groups)
|
||||
};
|
||||
}
|
||||
|
||||
foreach (var group in groups)
|
||||
{
|
||||
if (Groups.TryGetValue(group, out var groupDef))
|
||||
{
|
||||
data.Flags.UnionWith(groupDef.Flags);
|
||||
groupDef.CommandOverrides.ToList().ForEach(x => data.CommandOverrides[x.Key] = x.Value);
|
||||
}
|
||||
}
|
||||
Admins[steamId] = data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a player from a group.
|
||||
/// </summary>
|
||||
/// <param name="player">Player controller.</param>
|
||||
/// <param name="removeInheritedFlags">If true, all of the flags that the player inherited from being in the group will be removed.</param>
|
||||
/// <param name="groups"></param>
|
||||
public static void RemovePlayerFromGroup(CCSPlayerController? player, bool removeInheritedFlags = true, params string[] groups)
|
||||
{
|
||||
if (player == null) return;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) { return; }
|
||||
RemovePlayerFromGroup((SteamID)player.SteamID, true, groups);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a player from a group.
|
||||
/// </summary>
|
||||
/// <param name="steamId">SteamID of the player.</param>
|
||||
/// <param name="removeInheritedFlags">If true, all of the flags that the player inherited from being in the group will be removed.</param>
|
||||
/// <param name="groups"></param>
|
||||
public static void RemovePlayerFromGroup(SteamID steamId, bool removeInheritedFlags = true, params string[] groups)
|
||||
{
|
||||
var data = GetPlayerAdminData(steamId);
|
||||
if (data == null) return;
|
||||
|
||||
data.Groups.ExceptWith(groups);
|
||||
|
||||
if (removeInheritedFlags)
|
||||
{
|
||||
foreach (var group in groups)
|
||||
{
|
||||
if (Groups.TryGetValue(group, out var groupDef))
|
||||
{
|
||||
data.Flags.ExceptWith(groupDef.Flags);
|
||||
}
|
||||
}
|
||||
}
|
||||
Admins[steamId] = data;
|
||||
}
|
||||
}
|
||||
}
|
||||
90
managed/CounterStrikeSharp.API/Modules/Admin/AdminManager.cs
Normal file
90
managed/CounterStrikeSharp.API/Modules/Admin/AdminManager.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Commands;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using CounterStrikeSharp.API.Core.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
|
||||
public static partial class AdminManager
|
||||
{
|
||||
static AdminManager()
|
||||
{
|
||||
CommandUtils.AddStandaloneCommand("css_admins_reload", "Reloads the admin file.", ReloadAdminsCommand);
|
||||
CommandUtils.AddStandaloneCommand("css_admins_list", "List admins and their flags.", ListAdminsCommand);
|
||||
CommandUtils.AddStandaloneCommand("css_groups_reload", "Reloads the admin groups file.", ReloadAdminGroupsCommand);
|
||||
CommandUtils.AddStandaloneCommand("css_groups_list", "List admin groups and their flags.", ListAdminGroupsCommand);
|
||||
CommandUtils.AddStandaloneCommand("css_overrides_reload", "Reloads the admin command overrides file.", ReloadAdminOverridesCommand);
|
||||
CommandUtils.AddStandaloneCommand("css_overrides_list", "List admin command overrides and their flags.", ListAdminOverridesCommand);
|
||||
}
|
||||
|
||||
public static void MergeGroupPermsIntoAdmins()
|
||||
{
|
||||
foreach (var (steamID, adminDef) in Admins)
|
||||
{
|
||||
AddPlayerToGroup(steamID, adminDef.Groups.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
[RequiresPermissions(permissions:"@css/generic")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private static void ReloadAdminsCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
Admins.Clear();
|
||||
var rootDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.Parent;
|
||||
LoadAdminData(Path.Combine(rootDir.FullName, "configs", "admins.json"));
|
||||
}
|
||||
|
||||
[RequiresPermissions(permissions:"@css/generic")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private static void ListAdminsCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
foreach (var (steamId, data) in Admins)
|
||||
{
|
||||
command.ReplyToCommand($"{steamId.SteamId64}, {steamId.SteamId2} - {string.Join(", ", data.Flags)}");
|
||||
}
|
||||
}
|
||||
|
||||
[RequiresPermissions(permissions:"@css/generic")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private static void ReloadAdminGroupsCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
Groups.Clear();
|
||||
var rootDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.Parent;
|
||||
LoadAdminGroups(Path.Combine(rootDir.FullName, "configs", "admin_groups.json"));
|
||||
}
|
||||
|
||||
[RequiresPermissions(permissions: "@css/generic")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private static void ListAdminGroupsCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
foreach (var (groupName, groupDef) in Groups)
|
||||
{
|
||||
command.ReplyToCommand($"{groupName} - {string.Join(", ", groupDef.Flags)}");
|
||||
}
|
||||
}
|
||||
|
||||
[RequiresPermissions(permissions: "@css/generic")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private static void ReloadAdminOverridesCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
CommandOverrides.Clear();
|
||||
var rootDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.Parent;
|
||||
LoadCommandOverrides(Path.Combine(rootDir.FullName, "configs", "admin_overrides.json"));
|
||||
}
|
||||
|
||||
[RequiresPermissions(permissions: "@css/generic")]
|
||||
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
|
||||
private static void ListAdminOverridesCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
foreach (var (commandName, commandDef) in CommandOverrides)
|
||||
{
|
||||
command.ReplyToCommand($"{commandName} (enabled: {commandDef.Enabled.ToString()}) - {string.Join(", ", commandDef.Flags)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
396
managed/CounterStrikeSharp.API/Modules/Admin/AdminPermissions.cs
Normal file
396
managed/CounterStrikeSharp.API/Modules/Admin/AdminPermissions.cs
Normal file
@@ -0,0 +1,396 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json;
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using CounterStrikeSharp.API.Modules.Entities;
|
||||
using CounterStrikeSharp.API.Modules.Commands;
|
||||
using System.Reflection;
|
||||
using System.Numerics;
|
||||
using System.Linq;
|
||||
using CounterStrikeSharp.API.Core.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
public partial class AdminData
|
||||
{
|
||||
[JsonPropertyName("identity")] public required string Identity { get; init; }
|
||||
[JsonPropertyName("flags")] public HashSet<string> Flags { get; init; } = new();
|
||||
[JsonPropertyName("immunity")] public uint Immunity { get; set; } = 0;
|
||||
[JsonPropertyName("command_overrides")] public Dictionary<string, bool> CommandOverrides { get; init; } = new();
|
||||
}
|
||||
|
||||
public static partial class AdminManager
|
||||
{
|
||||
private static Dictionary<SteamID, AdminData> Admins = new();
|
||||
|
||||
// TODO: ServiceCollection
|
||||
private static ILogger _logger = CoreLogging.Factory.CreateLogger("AdminManager");
|
||||
|
||||
public static void LoadAdminData(string adminDataPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(adminDataPath))
|
||||
{
|
||||
_logger.LogWarning("Admin data file not found. Skipping admin data load.");
|
||||
return;
|
||||
}
|
||||
|
||||
var adminsFromFile = JsonSerializer.Deserialize<Dictionary<string, AdminData>>(File.ReadAllText(adminDataPath), new JsonSerializerOptions() { ReadCommentHandling = JsonCommentHandling.Skip });
|
||||
if (adminsFromFile == null) { throw new FileNotFoundException(); }
|
||||
foreach (var adminDef in adminsFromFile.Values)
|
||||
{
|
||||
if (SteamID.TryParse(adminDef.Identity, out var steamId))
|
||||
{
|
||||
if (Admins.ContainsKey(steamId!))
|
||||
{
|
||||
Admins[steamId!].Flags.UnionWith(adminDef.Flags);
|
||||
if (adminDef.Immunity > Admins[steamId!].Immunity)
|
||||
{
|
||||
Admins[steamId!].Immunity = adminDef.Immunity;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Admins.Add(steamId!, adminDef);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Loaded admin data with {Count} admins.", Admins.Count);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to load admin data");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grabs the admin data for a player that was loaded from "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="steamId">SteamID object of the player.</param>
|
||||
/// <returns>AdminData class if data found, null if not.</returns>
|
||||
public static AdminData? GetPlayerAdminData(SteamID steamId)
|
||||
{
|
||||
return Admins.GetValueOrDefault(steamId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a players admin data. This is not saved to "configs/admins.json"
|
||||
/// </summary>
|
||||
/// <param name="steamId">Steam ID remove admin data from.</param>
|
||||
public static void RemovePlayerAdminData(SteamID steamId)
|
||||
{
|
||||
Admins.Remove(steamId);
|
||||
}
|
||||
|
||||
#region Command Permission Checks
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if a player has access to a certain set of permission flags.
|
||||
/// </summary>
|
||||
/// <param name="player">Player or server console.</param>
|
||||
/// <param name="flags">Flags to look for in the players permission flags.</param>
|
||||
/// <returns>True if flags are present, false if not.</returns>
|
||||
public static bool PlayerHasPermissions(CCSPlayerController? player, params string[] flags)
|
||||
{
|
||||
// This is here for cases where the server console is attempting to call commands.
|
||||
// The server console should have access to all commands, regardless of permissions.
|
||||
if (player == null) return true;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) { return false; }
|
||||
var playerData = GetPlayerAdminData((SteamID)player.SteamID);
|
||||
return playerData?.Flags.IsSupersetOf(flags) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if a player has access to a certain set of permission flags.
|
||||
/// </summary>
|
||||
/// <param name="steamId">Steam ID object.</param>
|
||||
/// <param name="flags">Flags to look for in the players permission flags.</param>
|
||||
/// <returns>True if flags are present, false if not.</returns>
|
||||
public static bool PlayerHasPermissions(SteamID steamId, params string[] flags)
|
||||
{
|
||||
var playerData = GetPlayerAdminData(steamId);
|
||||
return playerData?.Flags.IsSupersetOf(flags) ?? false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
// This is placed here instead of in AdminCommandOverrides.cs as this all relates to admins that are
|
||||
// defined within the "configs/admins.json" file.
|
||||
#region Admin Specific Command Overrides
|
||||
/// <summary>
|
||||
/// Checks to see if a player has a command override. This does NOT return the actual
|
||||
/// state of the override.
|
||||
/// </summary>
|
||||
/// <param name="player">Player or server console.</param>
|
||||
/// <param name="command">Name of the command to check for.</param>
|
||||
/// <returns>True if override exists, false if not.</returns>
|
||||
public static bool PlayerHasCommandOverride(CCSPlayerController? player, string command)
|
||||
{
|
||||
// This is here for cases where the server console is attempting to call commands.
|
||||
// The server console should have access to all commands, regardless of permissions.
|
||||
if (player == null) return true;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) { return false; }
|
||||
var playerData = GetPlayerAdminData((SteamID)player.SteamID);
|
||||
return playerData?.CommandOverrides.ContainsKey(command) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if a player has a command override. This does NOT return the actual
|
||||
/// state of the override.
|
||||
/// </summary>
|
||||
/// <param name="steamId">Steam ID object.</param>
|
||||
/// <param name="command">Name of the command to check for.</param>
|
||||
/// <returns>True if override exists, false if not.</returns>
|
||||
public static bool PlayerHasCommandOverride(SteamID steamId, string command)
|
||||
{
|
||||
var playerData = GetPlayerAdminData(steamId);
|
||||
return playerData?.CommandOverrides.ContainsKey(command) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of a command override state.
|
||||
/// </summary>
|
||||
/// <param name="player">Player or server console.</param>
|
||||
/// <param name="command">Name of the command to check for.</param>
|
||||
/// <returns>True if override is active, false if not.</returns>
|
||||
public static bool GetPlayerCommandOverrideState(CCSPlayerController? player, string command)
|
||||
{
|
||||
// This is here for cases where the server console is attempting to call commands.
|
||||
// The server console should have access to all commands, regardless of permissions.
|
||||
if (player == null) return true;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) { return false; }
|
||||
var playerData = GetPlayerAdminData((SteamID)player.SteamID);
|
||||
return playerData?.CommandOverrides.GetValueOrDefault(command) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of a command override state.
|
||||
/// </summary>
|
||||
/// <param name="steamId">Steam ID object.</param>
|
||||
/// <param name="command">Name of the command to check for.</param>
|
||||
/// <returns>True if override is active, false if not.</returns>
|
||||
public static bool GetPlayerCommandOverrideState(SteamID steamId, string command)
|
||||
{
|
||||
var playerData = GetPlayerAdminData(steamId);
|
||||
return playerData?.CommandOverrides.GetValueOrDefault(command) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a player command override. This is not saved to "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="player">Player or server console.</param>
|
||||
/// <param name="command">Name of the command to check for.</param>
|
||||
/// <param name="state">New state of the command override.</param>
|
||||
public static void SetPlayerCommandOverride(CCSPlayerController? player, string command, bool state)
|
||||
{
|
||||
// This is here for cases where the server console is attempting to call commands.
|
||||
// The server console should have access to all commands, regardless of permissions.
|
||||
if (player == null) return;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) { return; }
|
||||
SetPlayerCommandOverride((SteamID)player.SteamID, command, state);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a player command override. This is not saved to "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="steamId">SteamID to add a flag to.</param>
|
||||
/// <param name="command">Name of the command to check for.</param>
|
||||
/// <param name="state">New state of the command override.</param>
|
||||
public static void SetPlayerCommandOverride(SteamID steamId, string command, bool state)
|
||||
{
|
||||
var data = GetPlayerAdminData(steamId);
|
||||
if (data == null)
|
||||
{
|
||||
data = new AdminData()
|
||||
{
|
||||
Identity = steamId.SteamId64.ToString(),
|
||||
Flags = new(),
|
||||
Groups = new(),
|
||||
CommandOverrides = new() { { command, state } }
|
||||
};
|
||||
|
||||
Admins[steamId] = data;
|
||||
return;
|
||||
}
|
||||
|
||||
data.CommandOverrides[command] = state;
|
||||
Admins[steamId] = data;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Manipulating Permissions
|
||||
/// <summary>
|
||||
/// Temporarily adds a permission flag to the player. These flags are not saved to
|
||||
/// "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="player">Player controller to add a flag to.</param>
|
||||
/// <param name="flags">Flags to add for the player.</param>
|
||||
public static void AddPlayerPermissions(CCSPlayerController? player, params string[] flags)
|
||||
{
|
||||
if (player == null) return;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) return;
|
||||
AddPlayerPermissions((SteamID)player.SteamID, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Temporarily adds a permission flag to the player. These flags are not saved to
|
||||
/// "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="steamId">SteamID to add a flag to.</param>
|
||||
/// <param name="flags">Flags to add for the player.</param>
|
||||
public static void AddPlayerPermissions(SteamID steamId, params string[] flags)
|
||||
{
|
||||
var data = GetPlayerAdminData(steamId);
|
||||
if (data == null)
|
||||
{
|
||||
data = new AdminData()
|
||||
{
|
||||
Identity = steamId.SteamId64.ToString(),
|
||||
Flags = new(flags),
|
||||
Groups = new()
|
||||
};
|
||||
|
||||
Admins[steamId] = data;
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var flag in flags)
|
||||
{
|
||||
data.Flags.Add(flag);
|
||||
}
|
||||
Admins[steamId] = data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Temporarily removes a permission flag to the player. These flags are not saved to
|
||||
/// "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="player">Player controller to remove flags from.</param>
|
||||
/// <param name="flags">Flags to remove from the player.</param>
|
||||
public static void RemovePlayerPermissions(CCSPlayerController? player, params string[] flags)
|
||||
{
|
||||
if (player == null) return;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) return;
|
||||
|
||||
RemovePlayerPermissions((SteamID)player.SteamID, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Temporarily removes a permission flag to the player. These flags are not saved to
|
||||
/// "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="steamId">Steam ID to remove flags from.</param>
|
||||
/// <param name="flags">Flags to remove from the player.</param>
|
||||
public static void RemovePlayerPermissions(SteamID steamId, params string[] flags)
|
||||
{
|
||||
var data = GetPlayerAdminData(steamId);
|
||||
if (data == null) return;
|
||||
|
||||
data.Flags.ExceptWith(flags);
|
||||
Admins[steamId] = data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Temporarily removes all permission flags from a player. These flags are not saved to
|
||||
/// "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="player">Player controller to remove flags from.</param>
|
||||
public static void ClearPlayerPermissions(CCSPlayerController? player)
|
||||
{
|
||||
if (player == null) return;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) return;
|
||||
|
||||
ClearPlayerPermissions((SteamID)player.SteamID);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Temporarily removes all permission flags from a player. These flags are not saved to
|
||||
/// "configs/admins.json".
|
||||
/// </summary>
|
||||
/// <param name="steamId">Steam ID to remove flags from.</param>
|
||||
public static void ClearPlayerPermissions(SteamID steamId)
|
||||
{
|
||||
var data = GetPlayerAdminData(steamId);
|
||||
if (data == null) return;
|
||||
|
||||
data.Flags.Clear();
|
||||
Admins[steamId] = data;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Player Immunity
|
||||
/// <summary>
|
||||
/// Sets the immunity value for a player.
|
||||
/// </summary>
|
||||
/// <param name="player">Player controller.</param>
|
||||
/// <param name="value">New immunity value.</param>
|
||||
public static void SetPlayerImmunity(CCSPlayerController? player, uint value)
|
||||
{
|
||||
if (player == null) return;
|
||||
if (!player.IsValid || player.Connected != PlayerConnectedState.PlayerConnected || player.IsBot) return;
|
||||
|
||||
SetPlayerImmunity((SteamID)player.SteamID, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the immunity value for a player.
|
||||
/// </summary>
|
||||
/// <param name="steamId">Steam ID of the player.</param>
|
||||
/// <param name="value">New immunity value.</param>
|
||||
public static void SetPlayerImmunity(SteamID steamId, uint value)
|
||||
{
|
||||
var data = GetPlayerAdminData(steamId);
|
||||
if (data == null) return;
|
||||
|
||||
data.Immunity = value;
|
||||
Admins[steamId] = data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if a player can target another player based on their immunity value.
|
||||
/// </summary>
|
||||
/// <param name="caller">Caller of the command.</param>
|
||||
/// <param name="target">Target of the command.</param>
|
||||
/// <returns></returns>
|
||||
public static bool CanPlayerTarget(CCSPlayerController? caller, CCSPlayerController? target)
|
||||
{
|
||||
// The server console should be able to target everyone.
|
||||
if (caller == null) return true;
|
||||
|
||||
if (target == null) return false;
|
||||
if (!target.IsValid || target.Connected != PlayerConnectedState.PlayerConnected) return false;
|
||||
|
||||
var callerData = GetPlayerAdminData((SteamID)caller.SteamID);
|
||||
if (callerData == null) return false;
|
||||
|
||||
var targetData = GetPlayerAdminData((SteamID)target.SteamID);
|
||||
if (targetData == null) return true;
|
||||
|
||||
return callerData.Immunity >= targetData.Immunity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks to see if a player can target another player based on their immunity value.
|
||||
/// </summary>
|
||||
/// <param name="caller">Caller of the command.</param>
|
||||
/// <param name="target">Target of the command.</param>
|
||||
/// <returns></returns>
|
||||
public static bool CanPlayerTarget(SteamID caller, SteamID target)
|
||||
{
|
||||
var callerData = GetPlayerAdminData(caller);
|
||||
if (callerData == null) return false;
|
||||
|
||||
var targetData = GetPlayerAdminData(caller);
|
||||
if (targetData == null) return true;
|
||||
|
||||
return callerData.Immunity >= targetData.Immunity;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CounterStrikeSharp.API.Modules.Entities;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
public class BaseRequiresPermissions : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// The permissions for the command.
|
||||
/// </summary>
|
||||
public string[] Permissions { get; }
|
||||
/// <summary>
|
||||
/// The name of the command that is attached to this attribute.
|
||||
/// </summary>
|
||||
public string Command { get; set; }
|
||||
/// <summary>
|
||||
/// Whether this attribute should be used for permission checks.
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
public BaseRequiresPermissions(params string[] permissions)
|
||||
{
|
||||
Permissions = permissions;
|
||||
Command = "";
|
||||
}
|
||||
|
||||
public virtual bool CanExecuteCommand(CCSPlayerController? caller)
|
||||
{
|
||||
// If we have a command in the "command_overrides" section in "configs/admins.json",
|
||||
// we skip the checks below and just return the defined value.
|
||||
var adminData = AdminManager.GetPlayerAdminData((SteamID)caller.SteamID);
|
||||
if (adminData == null) return false;
|
||||
if (adminData.CommandOverrides.ContainsKey(Command))
|
||||
{
|
||||
return adminData.CommandOverrides[Command];
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
public class PermissionCharacters
|
||||
{
|
||||
// Example: "#css/admin"
|
||||
public const char GroupPermissionChar = '#';
|
||||
// Example: "@css/manipulate_players"
|
||||
public const char UserPermissionChar = '@';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CounterStrikeSharp.API.Modules.Entities;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
|
||||
public class RequiresPermissions : BaseRequiresPermissions
|
||||
{
|
||||
public RequiresPermissions(params string[] permissions) : base(permissions) { }
|
||||
|
||||
public override bool CanExecuteCommand(CCSPlayerController? caller)
|
||||
{
|
||||
if (caller == null) return true;
|
||||
if (AdminManager.PlayerHasCommandOverride(caller, Command))
|
||||
{
|
||||
return AdminManager.GetPlayerCommandOverrideState(caller, Command);
|
||||
}
|
||||
if (!base.CanExecuteCommand(caller)) return false;
|
||||
|
||||
var groupPermissions = Permissions.Where(perm => perm.StartsWith(PermissionCharacters.GroupPermissionChar));
|
||||
var userPermissions = Permissions.Where(perm => perm.StartsWith(PermissionCharacters.UserPermissionChar));
|
||||
|
||||
if (!AdminManager.PlayerInGroup(caller, groupPermissions.ToArray())) return false;
|
||||
if (!AdminManager.PlayerHasPermissions(caller, userPermissions.ToArray())) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CounterStrikeSharp.API.Modules.Entities;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Admin
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
|
||||
public class RequiresPermissionsOr : BaseRequiresPermissions
|
||||
{
|
||||
public RequiresPermissionsOr(params string[] permissions) : base(permissions) { }
|
||||
|
||||
public override bool CanExecuteCommand(CCSPlayerController? caller)
|
||||
{
|
||||
if (caller == null) return true;
|
||||
if (AdminManager.PlayerHasCommandOverride(caller, Command))
|
||||
{
|
||||
return AdminManager.GetPlayerCommandOverrideState(caller, Command);
|
||||
}
|
||||
if (!base.CanExecuteCommand(caller)) return false;
|
||||
|
||||
var groupPermissions = Permissions.Where(perm => perm.StartsWith(PermissionCharacters.GroupPermissionChar));
|
||||
var userPermissions = Permissions.Where(perm => perm.StartsWith(PermissionCharacters.UserPermissionChar));
|
||||
|
||||
var adminData = AdminManager.GetPlayerAdminData((SteamID)caller.SteamID);
|
||||
if (adminData == null) return false;
|
||||
return (groupPermissions.Intersect(adminData.Groups).Count() + userPermissions.Intersect(adminData.Flags).Count()) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Commands
|
||||
{
|
||||
public enum CommandUsage
|
||||
{
|
||||
CLIENT_AND_SERVER = 0,
|
||||
CLIENT_ONLY,
|
||||
SERVER_ONLY
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
|
||||
public class CommandHelperAttribute : Attribute
|
||||
{
|
||||
public int MinArgs { get; }
|
||||
public string Usage { get; }
|
||||
public CommandUsage WhoCanExcecute { get; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="minArgs">The minimum amount of arguments required to execute this command.</param>
|
||||
/// <param name="usage">If the command fails, this string is printed to the caller to show the CommandUtils intended usage.</param>
|
||||
/// <param name="whoCanExecute">Restricts the command so it can only be executed by players, the server console, or both (see CommandUsage).</param>
|
||||
public CommandHelperAttribute(int minArgs = 0, string usage = "", CommandUsage whoCanExecute = CommandUsage.CLIENT_AND_SERVER)
|
||||
{
|
||||
MinArgs = minArgs;
|
||||
Usage = usage;
|
||||
WhoCanExcecute = whoCanExecute;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,10 +43,11 @@ namespace CounterStrikeSharp.API.Modules.Commands
|
||||
public string ArgByIndex(int index) => NativeAPI.CommandGetArgByIndex(Handle, index);
|
||||
public string GetArg(int index) => NativeAPI.CommandGetArgByIndex(Handle, index);
|
||||
|
||||
public void ReplyToCommand(string message) {
|
||||
public void ReplyToCommand(string message, bool console = false) {
|
||||
if (_player != null)
|
||||
{
|
||||
_player.PrintToChat(message);
|
||||
if (console) { _player.PrintToConsole(message); }
|
||||
else _player.PrintToChat(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Core.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Config
|
||||
{
|
||||
public static class ConfigManager
|
||||
{
|
||||
private static readonly DirectoryInfo? _rootDir;
|
||||
|
||||
private static readonly string _pluginConfigsFolderPath;
|
||||
private static ILogger _logger = CoreLogging.Factory.CreateLogger("ConfigManager");
|
||||
|
||||
static ConfigManager()
|
||||
{
|
||||
_rootDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.Parent;
|
||||
_pluginConfigsFolderPath = Path.Combine(_rootDir.FullName, "configs", "plugins");
|
||||
}
|
||||
|
||||
public static T Load<T>(string pluginName) where T : IBasePluginConfig, new()
|
||||
{
|
||||
string directoryPath = Path.Combine(_pluginConfigsFolderPath, pluginName);
|
||||
string configPath = Path.Combine(directoryPath, $"{pluginName}.json");
|
||||
|
||||
T config = (T)Activator.CreateInstance(typeof(T))!;
|
||||
|
||||
if (!File.Exists(configPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(directoryPath))
|
||||
{
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
}
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.Append($"// This configuration was automatically generated by CounterStrikeSharp for plugin '{pluginName}', at {DateTimeOffset.Now:yyyy/MM/dd hh:mm:ss}\n");
|
||||
builder.Append(JsonSerializer.Serialize<T>(config, new JsonSerializerOptions { WriteIndented = true }));
|
||||
File.WriteAllText(configPath, builder.ToString());
|
||||
return config;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to generate configuration file for {PluginName}", pluginName);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
config = JsonSerializer.Deserialize<T>(File.ReadAllText(configPath), new JsonSerializerOptions() { ReadCommentHandling = JsonCommentHandling.Skip })!;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to parse configuration file for {PluginName}", pluginName);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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/>. *
|
||||
*/
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Entities.Constants
|
||||
{
|
||||
public enum RoundEndReason : uint
|
||||
{
|
||||
Unknown = 0x0u,
|
||||
TargetBombed = 0x1u,
|
||||
TerroristsEscaped = 0x4u,
|
||||
CTsPreventEscape = 0x5u,
|
||||
EscapingTerroristsNeutralized = 0x6u,
|
||||
BombDefused = 0x7u,
|
||||
CTsWin = 0x8u,
|
||||
TerroristsWin = 0x9u,
|
||||
RoundDraw = 0xAu,
|
||||
AllHostageRescued = 0xBu,
|
||||
TargetSaved = 0xCu,
|
||||
HostagesNotRescued = 0xDu,
|
||||
TerroristsNotEscaped = 0xEu,
|
||||
GameCommencing = 0x10u,
|
||||
|
||||
TerroristsSurrender = 0x11u, // this also triggers match cancelled
|
||||
CTsSurrender = 0x12u, // this also triggers match cancelled
|
||||
|
||||
TerroristsPlanned = 0x13u,
|
||||
CTsReachedHostage = 0x14u,
|
||||
SurvivalWin = 0x15u,
|
||||
SurvivalDraw = 0x16u
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using System;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Entities
|
||||
{
|
||||
public class SteamID
|
||||
public class SteamID : IEquatable<SteamID>
|
||||
{
|
||||
const long Base = 76561197960265728;
|
||||
public ulong SteamId64 { get; set; }
|
||||
@@ -12,7 +12,6 @@ namespace CounterStrikeSharp.API.Modules.Entities
|
||||
|
||||
public static explicit operator SteamID(ulong u) => new(u);
|
||||
public static explicit operator SteamID(string s) => new(s);
|
||||
|
||||
ulong ParseId(string id)
|
||||
{
|
||||
var parts = id.Split(':');
|
||||
@@ -46,5 +45,55 @@ namespace CounterStrikeSharp.API.Modules.Entities
|
||||
}
|
||||
|
||||
public override string ToString() => $"[SteamID {SteamId64}, {SteamId2}, {SteamId3}]";
|
||||
|
||||
public bool Equals(SteamID? other)
|
||||
{
|
||||
if (ReferenceEquals(null, other)) return false;
|
||||
if (ReferenceEquals(this, other)) return true;
|
||||
return SteamId64 == other.SteamId64;
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
if (ReferenceEquals(null, obj)) return false;
|
||||
if (ReferenceEquals(this, obj)) return true;
|
||||
if (obj.GetType() != this.GetType()) return false;
|
||||
return Equals((SteamID)obj);
|
||||
}
|
||||
|
||||
public static bool TryParse(string s, out SteamID? steamId)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (ulong.TryParse(s, out var steamid64))
|
||||
{
|
||||
steamId = new SteamID(steamid64);
|
||||
return true;
|
||||
}
|
||||
|
||||
steamId = new SteamID(s);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
steamId = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return SteamId64.GetHashCode();
|
||||
}
|
||||
|
||||
public static bool operator ==(SteamID? left, SteamID? right)
|
||||
{
|
||||
return Equals(left, right);
|
||||
}
|
||||
|
||||
public static bool operator !=(SteamID? left, SteamID? right)
|
||||
{
|
||||
return !Equals(left, right);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,7 @@ namespace CounterStrikeSharp.API.Modules.Events
|
||||
protected void SetEntityIndex(string name, int value) => NativeAPI.SetEventEntityIndex(Handle, name, value);
|
||||
|
||||
public void FireEvent(bool dontBroadcast) => NativeAPI.FireEvent(Handle, dontBroadcast);
|
||||
// public void FireEventToClient(int clientId, bool dontBroadcast) => NativeAPI.FireEventToClient(Handle, clientId);
|
||||
|
||||
public void FireEventToClient(CCSPlayerController player) => NativeAPI.FireEventToClient(Handle, (int)player.EntityIndex.Value.Value);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using CounterStrikeSharp.API.Core;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Memory;
|
||||
|
||||
public class Addresses
|
||||
{
|
||||
public static string EnginePath = Path.Join(Server.GameDirectory, Constants.ROOT_BINARY_PATH, "libengine2.so");
|
||||
public static string Tier0Path = Path.Join(Server.GameDirectory, Constants.ROOT_BINARY_PATH, "libtier0.so");
|
||||
public static string ServerPath = Path.Join(Server.GameDirectory, Constants.GAME_BINARY_PATH, "libserver.so");
|
||||
public static string EnginePath => Path.Join(Server.GameDirectory, Constants.RootBinaryPath, $"{Constants.ModulePrefix}engine2{Constants.ModuleSuffix}");
|
||||
public static string Tier0Path => Path.Join(Server.GameDirectory, Constants.RootBinaryPath, $"{Constants.ModulePrefix}tier0{Constants.ModuleSuffix}");
|
||||
|
||||
public static string SchemaSystemPath =
|
||||
Path.Join(Server.GameDirectory, Constants.ROOT_BINARY_PATH, "libschemasystem.so");
|
||||
public static string ServerPath => Path.Join(Server.GameDirectory, Constants.GameBinaryPath, $"{Constants.ModulePrefix}server{Constants.ModuleSuffix}");
|
||||
|
||||
public static string SchemaSystemPath => Path.Join(Server.GameDirectory, Constants.RootBinaryPath, $"{Constants.ModulePrefix}schemasystem{Constants.ModuleSuffix}");
|
||||
public static string VScriptPath => Path.Join(Server.GameDirectory, Constants.RootBinaryPath, $"{Constants.ModulePrefix}vscript{Constants.ModuleSuffix}");
|
||||
|
||||
public static string VScriptPath = Path.Join(Server.GameDirectory, Constants.ROOT_BINARY_PATH, "libvscript.so");
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Memory
|
||||
{
|
||||
@@ -71,7 +73,7 @@ namespace CounterStrikeSharp.API.Modules.Memory
|
||||
return types[Enum.GetUnderlyingType(type)];
|
||||
}
|
||||
|
||||
Console.WriteLine("Error retrieving data type for type" + type.FullName);
|
||||
GlobalContext.Instance.Logger.LogWarning("Error retrieving data type for type {Type}", type.FullName);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -10,8 +10,53 @@ public class Schema
|
||||
{
|
||||
private static Dictionary<Tuple<string, string>, short> _schemaOffsets = new();
|
||||
|
||||
private static HashSet<string> _cs2BadList = new HashSet<string>()
|
||||
{
|
||||
"m_bIsValveDS",
|
||||
"m_bIsQuestEligible",
|
||||
// "m_iItemDefinitionIndex", // as of 2023.11.11 this is currently not blocked
|
||||
"m_iEntityLevel",
|
||||
"m_iItemIDHigh",
|
||||
"m_iItemIDLow",
|
||||
"m_iAccountID",
|
||||
"m_iEntityQuality",
|
||||
|
||||
"m_bInitialized",
|
||||
"m_szCustomName",
|
||||
"m_iAttributeDefinitionIndex",
|
||||
"m_iRawValue32",
|
||||
"m_iRawInitialValue32",
|
||||
"m_flValue", // MNetworkAlias "m_iRawValue32"
|
||||
"m_flInitialValue", // MNetworkAlias "m_iRawInitialValue32"
|
||||
"m_bSetBonus",
|
||||
"m_nRefundableCurrency",
|
||||
|
||||
"m_OriginalOwnerXuidLow",
|
||||
"m_OriginalOwnerXuidHigh",
|
||||
|
||||
"m_nFallbackPaintKit",
|
||||
"m_nFallbackSeed",
|
||||
"m_flFallbackWear",
|
||||
"m_nFallbackStatTrak",
|
||||
|
||||
"m_iCompetitiveWins",
|
||||
"m_iCompetitiveRanking",
|
||||
"m_iCompetitiveRankType",
|
||||
"m_iCompetitiveRankingPredicted_Win",
|
||||
"m_iCompetitiveRankingPredicted_Loss",
|
||||
"m_iCompetitiveRankingPredicted_Tie",
|
||||
|
||||
"m_nActiveCoinRank",
|
||||
"m_nMusicID",
|
||||
};
|
||||
|
||||
public static short GetSchemaOffset(string className, string propertyName)
|
||||
{
|
||||
if (CoreConfig.FollowCS2ServerGuidelines && _cs2BadList.Contains(propertyName))
|
||||
{
|
||||
throw new Exception($"Cannot set or get '{className}::{propertyName}' with \"FollowCS2ServerGuidelines\" option enabled.");
|
||||
}
|
||||
|
||||
var key = new Tuple<string, string>(className, propertyName);
|
||||
if (!_schemaOffsets.TryGetValue(key, out var offset))
|
||||
{
|
||||
@@ -29,6 +74,11 @@ public class Schema
|
||||
|
||||
public static void SetSchemaValue<T>(IntPtr handle, string className, string propertyName, T value)
|
||||
{
|
||||
if (CoreConfig.FollowCS2ServerGuidelines && _cs2BadList.Contains(propertyName))
|
||||
{
|
||||
throw new Exception($"Cannot set or get '{className}::{propertyName}' with \"FollowCS2ServerGuidelines\" option enabled.");
|
||||
}
|
||||
|
||||
NativeAPI.SetSchemaValueByName<T>(handle, (int)typeof(T).ToDataType(), className, propertyName, value);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,9 +31,15 @@ public partial class VirtualFunction
|
||||
{
|
||||
if (!_createdFunctions.TryGetValue(signature, out var function))
|
||||
{
|
||||
function = NativeAPI.CreateVirtualFunctionBySignature(IntPtr.Zero, Addresses.ServerPath, signature,
|
||||
argumentTypes.Count(), (int)returnType, arguments);
|
||||
_createdFunctions[signature] = function;
|
||||
try
|
||||
{
|
||||
function = NativeAPI.CreateVirtualFunctionBySignature(IntPtr.Zero, Addresses.ServerPath, signature,
|
||||
argumentTypes.Count(), (int)returnType, arguments);
|
||||
_createdFunctions[signature] = function;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return function;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Entities.Constants;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Memory;
|
||||
@@ -24,4 +25,13 @@ public static class VirtualFunctions
|
||||
|
||||
// void(*UTIL_Remove)(CEntityInstance*);
|
||||
public static Action<IntPtr> UTIL_Remove = VirtualFunction.CreateVoid<IntPtr>(GameData.GetSignature("UTIL_Remove"));
|
||||
|
||||
// void(*CBaseModelEntity_SetModel)(CBaseModelEntity*, const char*);
|
||||
public static Action<IntPtr, string> SetModel = VirtualFunction.CreateVoid<IntPtr, string>(GameData.GetSignature("CBaseModelEntity_SetModel"));
|
||||
|
||||
public static Action<IntPtr, RoundEndReason, float> TerminateRound = VirtualFunction.CreateVoid<nint, RoundEndReason, float>(GameData.GetSignature("CCSGameRules_TerminateRound"));
|
||||
|
||||
public static Func<string, int, IntPtr> UTIL_CreateEntityByName = VirtualFunction.Create<string, int, IntPtr>(GameData.GetSignature("UTIL_CreateEntityByName"));
|
||||
|
||||
public static Action<IntPtr, IntPtr> CBaseEntity_DispatchSpawn = VirtualFunction.CreateVoid<IntPtr, IntPtr>(GameData.GetSignature("CBaseEntity_DispatchSpawn"));
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Admin;
|
||||
using CounterStrikeSharp.API.Modules.Commands;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace CounterStrikeSharp.API.Modules.Utils;
|
||||
|
||||
public class CommandUtils
|
||||
{
|
||||
public static void AddStandaloneCommand(string name, string description, CommandInfo.CommandCallback handler)
|
||||
{
|
||||
var wrappedHandler = new Action<int, IntPtr>((i, ptr) =>
|
||||
{
|
||||
var caller = (i != -1) ? new CCSPlayerController(NativeAPI.GetEntityFromIndex(i + 1)) : null;
|
||||
var command = new CommandInfo(ptr, caller);
|
||||
|
||||
var methodInfo = handler?.GetMethodInfo();
|
||||
|
||||
if (!AdminManager.CommandIsOverriden(name))
|
||||
{
|
||||
// Do not execute command if we do not have the correct permissions.
|
||||
var permissions = methodInfo?.GetCustomAttributes<BaseRequiresPermissions>();
|
||||
if (permissions != null)
|
||||
{
|
||||
foreach (var attr in permissions)
|
||||
{
|
||||
attr.Command = name;
|
||||
if (!attr.CanExecuteCommand(caller))
|
||||
{
|
||||
command.ReplyToCommand("[CSS] You do not have the correct permissions to execute this command.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// If this command has it's permissions overriden, we will do an AND check for all permissions.
|
||||
else
|
||||
{
|
||||
// I don't know if this is the most sane implementation of this, can be edited in code review.
|
||||
var data = AdminManager.GetCommandOverrideData(name);
|
||||
if (data != null)
|
||||
{
|
||||
var attrType = (data.CheckType == "all") ? typeof(RequiresPermissions) : typeof(RequiresPermissionsOr);
|
||||
var attr = (BaseRequiresPermissions)Activator.CreateInstance(attrType, args: AdminManager.GetPermissionOverrides(name));
|
||||
attr.Command = name;
|
||||
if (!attr.CanExecuteCommand(caller))
|
||||
{
|
||||
command.ReplyToCommand("[CSS] You do not have the correct permissions to execute this command.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Do not execute if we shouldn't be calling this command.
|
||||
var helperAttribute = methodInfo?.GetCustomAttribute<CommandHelperAttribute>();
|
||||
if (helperAttribute != null)
|
||||
{
|
||||
switch (helperAttribute.WhoCanExcecute)
|
||||
{
|
||||
case CommandUsage.CLIENT_AND_SERVER: break; // Allow command through.
|
||||
case CommandUsage.CLIENT_ONLY:
|
||||
if (caller == null || !caller.IsValid) { command.ReplyToCommand("[CSS] This command can only be executed by clients."); return; }
|
||||
break;
|
||||
case CommandUsage.SERVER_ONLY:
|
||||
if (caller != null && caller.IsValid) { command.ReplyToCommand("[CSS] This command can only be executed by the server."); return; }
|
||||
break;
|
||||
default: throw new ArgumentException("Unrecognised CommandUsage value passed in CommandHelperAttribute.");
|
||||
}
|
||||
|
||||
// Technically the command itself counts as the first argument,
|
||||
// but we'll just ignore that for this check.
|
||||
if (helperAttribute.MinArgs != 0 && command.ArgCount - 1 < helperAttribute.MinArgs)
|
||||
{
|
||||
command.ReplyToCommand($"[CSS] Expected usage: \"!{command.ArgByIndex(0)} {helperAttribute.Usage}\".");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
handler?.Invoke(caller, command);
|
||||
});
|
||||
|
||||
var methodInfo = handler?.GetMethodInfo();
|
||||
var helperAttribute = methodInfo?.GetCustomAttribute<CommandHelperAttribute>();
|
||||
|
||||
var subscriber = new BasePlugin.CallbackSubscriber(handler, wrappedHandler, () => { });
|
||||
NativeAPI.AddCommand(name, description, (helperAttribute?.WhoCanExcecute == CommandUsage.SERVER_ONLY),
|
||||
(int)ConCommandFlags.FCVAR_LINKED_CONCOMMAND, subscriber.GetInputArgument());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"profiles": {
|
||||
"CounterStrikeSharp.API": {
|
||||
"commandName": "Project",
|
||||
"nativeDebugging": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Memory;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -43,6 +44,11 @@ namespace CounterStrikeSharp.API
|
||||
return (T)Activator.CreateInstance(typeof(T), NativeAPI.GetEntityFromIndex(index))!;
|
||||
}
|
||||
|
||||
public static T? CreateEntityByName<T>(string name) where T : CBaseEntity
|
||||
{
|
||||
return (T?)Activator.CreateInstance(typeof(T), VirtualFunctions.UTIL_CreateEntityByName(name, -1));
|
||||
}
|
||||
|
||||
public static CCSPlayerController GetPlayerFromIndex(int index)
|
||||
{
|
||||
return Utilities.GetEntityFromIndex<CCSPlayerController>(index);
|
||||
@@ -79,7 +85,7 @@ namespace CounterStrikeSharp.API
|
||||
{
|
||||
var controller = GetPlayerFromIndex(i);
|
||||
|
||||
if (!controller.IsValid || controller.UserId < 0)
|
||||
if (!controller.IsValid || controller.UserId == -1)
|
||||
continue;
|
||||
|
||||
players.Add(controller);
|
||||
@@ -88,6 +94,7 @@ namespace CounterStrikeSharp.API
|
||||
return players;
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
public static void ReplyToCommand(CCSPlayerController? player, string msg, bool console = false)
|
||||
{
|
||||
if (player != null)
|
||||
|
||||
@@ -4855,6 +4855,14 @@
|
||||
},
|
||||
"CBaseCSGrenadeProjectile": {
|
||||
"fields": [
|
||||
{
|
||||
"name": "m_vInitialPosition",
|
||||
"type": {
|
||||
"atomic": 0,
|
||||
"category": 4,
|
||||
"name": "Vector"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_vInitialVelocity",
|
||||
"type": {
|
||||
@@ -4970,6 +4978,20 @@
|
||||
"category": 0,
|
||||
"name": "int32"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bHasEverHitPlayer",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "bool"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bClearFromPlayers",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "bool"
|
||||
}
|
||||
}
|
||||
],
|
||||
"parent": "CBaseGrenade"
|
||||
@@ -13245,10 +13267,10 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bMatchAbortedDueToPlayerBan",
|
||||
"name": "m_nMatchAbortedEarlyReason",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "bool"
|
||||
"name": "int32"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -13828,6 +13850,13 @@
|
||||
"name": "uint32"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bCannotBeKicked",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "bool"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bEverFullyConnected",
|
||||
"type": {
|
||||
@@ -14125,12 +14154,26 @@
|
||||
"name": "bool"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_dblLastReceivedPacketPlatFloatTime",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "float64"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_LastTeamDamageWarningTime",
|
||||
"type": {
|
||||
"category": 5,
|
||||
"name": "GameTime_t"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_LastTimePlayerWasDisconnectedForPawnsRemove",
|
||||
"type": {
|
||||
"category": 5,
|
||||
"name": "GameTime_t"
|
||||
}
|
||||
}
|
||||
],
|
||||
"parent": "CBasePlayerController"
|
||||
@@ -14439,6 +14482,13 @@
|
||||
"name": "char[18]"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bInHostageResetZone",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "bool"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bInBuyZone",
|
||||
"type": {
|
||||
@@ -16244,6 +16294,20 @@
|
||||
"category": 0,
|
||||
"name": "float32"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_flHeightAtJumpStart",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "float32"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_flMaxJumpHeightThisJump",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "float32"
|
||||
}
|
||||
}
|
||||
],
|
||||
"parent": "CPlayer_MovementServices_Humanoid"
|
||||
@@ -30081,6 +30145,14 @@
|
||||
"category": 4,
|
||||
"name": "Vector"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_vecHostageResetPosition",
|
||||
"type": {
|
||||
"atomic": 0,
|
||||
"category": 4,
|
||||
"name": "Vector"
|
||||
}
|
||||
}
|
||||
],
|
||||
"parent": "CHostageExpresserShim"
|
||||
@@ -32719,6 +32791,40 @@
|
||||
],
|
||||
"parent": "CLogicalEntity"
|
||||
},
|
||||
"CLogicEventListener": {
|
||||
"fields": [
|
||||
{
|
||||
"name": "m_strEventName",
|
||||
"type": {
|
||||
"atomic": 0,
|
||||
"category": 4,
|
||||
"name": "CUtlString"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_bIsEnabled",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "bool"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_nTeam",
|
||||
"type": {
|
||||
"category": 0,
|
||||
"name": "int32"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "m_OnEventFired",
|
||||
"type": {
|
||||
"category": 5,
|
||||
"name": "CEntityIOOutput"
|
||||
}
|
||||
}
|
||||
],
|
||||
"parent": "CLogicalEntity"
|
||||
},
|
||||
"CLogicGameEvent": {
|
||||
"fields": [
|
||||
{
|
||||
@@ -54460,6 +54566,10 @@
|
||||
"fields": [],
|
||||
"parent": "CBaseTrigger"
|
||||
},
|
||||
"CTriggerHostageReset": {
|
||||
"fields": [],
|
||||
"parent": "CBaseTrigger"
|
||||
},
|
||||
"CTriggerHurt": {
|
||||
"fields": [
|
||||
{
|
||||
@@ -90276,6 +90386,23 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"C4LightEffect_t": {
|
||||
"align": 4,
|
||||
"items": [
|
||||
{
|
||||
"name": "eLightEffectNone",
|
||||
"value": 0
|
||||
},
|
||||
{
|
||||
"name": "eLightEffectDropped",
|
||||
"value": 1
|
||||
},
|
||||
{
|
||||
"name": "eLightEffectThirdPersonHeld",
|
||||
"value": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
"CAnimationGraphVisualizerPrimitiveType": {
|
||||
"align": 4,
|
||||
"items": [
|
||||
@@ -96794,6 +96921,10 @@
|
||||
{
|
||||
"name": "DFLAG_IGNORE_ARMOR",
|
||||
"value": 2048
|
||||
},
|
||||
{
|
||||
"name": "DFLAG_SUPPRESS_UTILREMOVE",
|
||||
"value": 4096
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
using CounterStrikeSharp.API;
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Core.Attributes;
|
||||
@@ -27,12 +29,21 @@ using CounterStrikeSharp.API.Modules.Entities;
|
||||
using CounterStrikeSharp.API.Modules.Events;
|
||||
using CounterStrikeSharp.API.Modules.Memory;
|
||||
using CounterStrikeSharp.API.Modules.Menu;
|
||||
using CounterStrikeSharp.API.Modules.Timers;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace TestPlugin
|
||||
{
|
||||
[MinimumApiVersion(1)]
|
||||
public class SamplePlugin : BasePlugin
|
||||
public class SampleConfig : BasePluginConfig
|
||||
{
|
||||
[JsonPropertyName("IsPluginEnabled")] public bool IsPluginEnabled { get; set; } = true;
|
||||
|
||||
[JsonPropertyName("LogPrefix")] public string LogPrefix { get; set; } = "CSSharp";
|
||||
}
|
||||
|
||||
[MinimumApiVersion(33)]
|
||||
public class SamplePlugin : BasePlugin, IPluginConfig<SampleConfig>
|
||||
{
|
||||
public override string ModuleName => "Sample Plugin";
|
||||
public override string ModuleVersion => "v1.0.0";
|
||||
@@ -41,12 +52,28 @@ namespace TestPlugin
|
||||
|
||||
public override string ModuleDescription => "A playground of features used for testing";
|
||||
|
||||
public SampleConfig Config { get; set; }
|
||||
|
||||
// This method is called right before `Load` is called
|
||||
public void OnConfigParsed(SampleConfig config)
|
||||
{
|
||||
// Save config instance
|
||||
Config = config;
|
||||
}
|
||||
|
||||
public override void Load(bool hotReload)
|
||||
{
|
||||
Console.WriteLine(
|
||||
// Basic usage of the configuration system
|
||||
if (!Config.IsPluginEnabled)
|
||||
{
|
||||
Logger.LogWarning($"{Config.LogPrefix} {ModuleName} is disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation(
|
||||
$"Test Plugin has been loaded, and the hot reload flag was {hotReload}, path is {ModulePath}");
|
||||
|
||||
Console.WriteLine($"Max Players: {Server.MaxPlayers}");
|
||||
Logger.LogWarning($"Max Players: {Server.MaxPlayers}");
|
||||
|
||||
SetupConvars();
|
||||
SetupGameEvents();
|
||||
@@ -56,7 +83,7 @@ namespace TestPlugin
|
||||
|
||||
// ValveInterface provides pointers to loaded modules via Interface Name exposed from the engine (e.g. Source2Server001)
|
||||
var server = ValveInterface.Server;
|
||||
Log($"Server pointer found @ {server.Pointer:X}");
|
||||
Logger.LogInformation("Server pointer found @ {Pointer:X}", server.Pointer);
|
||||
|
||||
// You can use `ModuleDirectory` to get the directory of the plugin (for storing config files, saving database files etc.)
|
||||
File.WriteAllText(Path.Join(ModuleDirectory, "example.txt"),
|
||||
@@ -70,7 +97,7 @@ namespace TestPlugin
|
||||
// This value is asserted against the native code that points to the same function.
|
||||
var virtualFunc = VirtualFunction.Create<IntPtr>(server.Pointer, 91);
|
||||
var result = virtualFunc() - 8;
|
||||
Log($"Result of virtual func call is {result:X}");
|
||||
Logger.LogInformation("Result of virtual func call is {Pointer:X}", result);
|
||||
}
|
||||
|
||||
private void SetupConvars()
|
||||
@@ -81,13 +108,13 @@ namespace TestPlugin
|
||||
cheatsCvar.SetValue(true);
|
||||
|
||||
var numericCvar = ConVar.Find("mp_warmuptime");
|
||||
Console.WriteLine($"mp_warmuptime = {numericCvar?.GetPrimitiveValue<float>()}");
|
||||
Logger.LogInformation("mp_warmuptime = {Value}", numericCvar?.GetPrimitiveValue<float>());
|
||||
|
||||
var stringCvar = ConVar.Find("sv_skyname");
|
||||
Console.WriteLine($"sv_skyname = {stringCvar?.StringValue}");
|
||||
Logger.LogInformation("sv_skyname = {Value}", stringCvar?.StringValue);
|
||||
|
||||
var fogCvar = ConVar.Find("fog_color");
|
||||
Console.WriteLine($"fog_color = {fogCvar?.GetNativeValue<Vector>()}");
|
||||
Logger.LogInformation("fog_color = {Value}", fogCvar?.GetNativeValue<Vector>());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -100,7 +127,7 @@ namespace TestPlugin
|
||||
var entity = new CCSPlayerController(NativeAPI.GetEntityFromIndex(@event.Userid));
|
||||
if (!entity.IsValid)
|
||||
{
|
||||
Log("invalid entity");
|
||||
Logger.LogInformation("invalid entity");
|
||||
return HookResult.Continue;
|
||||
}
|
||||
|
||||
@@ -123,7 +150,8 @@ namespace TestPlugin
|
||||
if (!@event.Userid.IsValid) return 0;
|
||||
if (!@event.Userid.PlayerPawn.IsValid) return 0;
|
||||
|
||||
Log($"Player spawned with entity index: {@event.Userid.EntityIndex} & User ID: {@event.Userid.UserId}");
|
||||
Logger.LogInformation("Player spawned with entity index: {EntityIndex} & User ID: {UserId}",
|
||||
@event.Userid.EntityIndex, @event.Userid.UserId);
|
||||
|
||||
return HookResult.Continue;
|
||||
});
|
||||
@@ -138,7 +166,7 @@ namespace TestPlugin
|
||||
// Set player to random colour
|
||||
player.PlayerPawn.Value.Render = Color.FromArgb(Random.Shared.Next(0, 255),
|
||||
Random.Shared.Next(0, 255), Random.Shared.Next(0, 255));
|
||||
|
||||
|
||||
Server.NextFrame(() =>
|
||||
{
|
||||
player.PrintToCenter(string.Join("\n", weapons.Select(x => x.Value.DesignerName)));
|
||||
@@ -147,17 +175,14 @@ namespace TestPlugin
|
||||
activeWeapon.ReserveAmmo[0] = 250;
|
||||
activeWeapon.Clip1 = 250;
|
||||
|
||||
Log(
|
||||
$"Pawn Position: {pawn.CBodyComponent?.SceneNode?.AbsOrigin} @{pawn.CBodyComponent?.SceneNode.Rotation}");
|
||||
Logger.LogInformation("Pawn Position: {AbsOrigin}-{Rotation}", pawn.AbsOrigin, pawn.AbsRotation);
|
||||
|
||||
char randomColourChar = (char)new Random().Next(0, 16);
|
||||
Server.PrintToChatAll($"Random String with Random Colour: {randomColourChar}{new Random().Next()}");
|
||||
|
||||
pawn.Health += 5;
|
||||
|
||||
Log(
|
||||
$"Found steamID {new SteamID(player.SteamID)} for player {player.PlayerName}:{pawn.Health}|{pawn.InBuyZone}");
|
||||
Log($"{@event.Userid}, {@event.X},{@event.Y},{@event.Z}");
|
||||
Logger.LogInformation("Bullet Impact: {X},{Y},{Z}", @event.X, @event.Y, @event.Z);
|
||||
|
||||
return HookResult.Continue;
|
||||
});
|
||||
@@ -165,7 +190,7 @@ namespace TestPlugin
|
||||
{
|
||||
// Grab all cs_player_controller entities and set their cash value to $1337.
|
||||
var playerEntities = Utilities.GetPlayers();
|
||||
Log($"cs_player_controller count: {playerEntities.Count()}");
|
||||
Logger.LogInformation($"cs_player_controller count: {playerEntities.Count()}");
|
||||
|
||||
foreach (var player in playerEntities)
|
||||
{
|
||||
@@ -176,7 +201,7 @@ namespace TestPlugin
|
||||
// Grab everything starting with cs_, but we'll only mainpulate cs_gamerules.
|
||||
// Note: this iterates through all entities, so is an expensive operation.
|
||||
var csEntities = Utilities.FindAllEntitiesByDesignerName<CBaseEntity>("cs_");
|
||||
Log($"Amount of cs_* entities: {csEntities.Count()}");
|
||||
Logger.LogInformation("Amount of cs_* entities: {Count}", csEntities.Count());
|
||||
|
||||
foreach (var entity in csEntities)
|
||||
{
|
||||
@@ -192,15 +217,18 @@ namespace TestPlugin
|
||||
private void SetupListeners()
|
||||
{
|
||||
// Hook global listeners defined by CounterStrikeSharp
|
||||
RegisterListener<Listeners.OnMapStart>(mapName => { Log($"Map {mapName} has started!"); });
|
||||
RegisterListener<Listeners.OnMapEnd>(() => { Log($"Map has ended."); });
|
||||
RegisterListener<Listeners.OnMapStart>(mapName =>
|
||||
{
|
||||
Logger.LogInformation("Map {Map} has started!", mapName);
|
||||
});
|
||||
RegisterListener<Listeners.OnMapEnd>(() => { Logger.LogInformation($"Map has ended."); });
|
||||
RegisterListener<Listeners.OnClientConnect>((index, name, ip) =>
|
||||
{
|
||||
Log($"Client {name} from {ip} has connected!");
|
||||
Logger.LogInformation("Client {Name} from {Ip} has connected!", name, ip);
|
||||
});
|
||||
RegisterListener<Listeners.OnClientAuthorized>((index, id) =>
|
||||
{
|
||||
Log($"Client {index} with address {id}");
|
||||
Logger.LogInformation("Client {Index} with address {Id}", index, id);
|
||||
});
|
||||
|
||||
RegisterListener<Listeners.OnEntitySpawned>(entity =>
|
||||
@@ -217,7 +245,8 @@ namespace TestPlugin
|
||||
projectile.SmokeColor.X = Random.Shared.NextSingle() * 255.0f;
|
||||
projectile.SmokeColor.X = Random.Shared.NextSingle() * 255.0f;
|
||||
projectile.SmokeColor.X = Random.Shared.NextSingle() * 255.0f;
|
||||
Log($"Smoke grenade spawned with color {projectile.SmokeColor}");
|
||||
Logger.LogInformation("Smoke grenade spawned with color {SmokeColor}",
|
||||
projectile.SmokeColor);
|
||||
});
|
||||
return;
|
||||
case "flashbang_projectile":
|
||||
@@ -270,8 +299,9 @@ namespace TestPlugin
|
||||
(player, info) =>
|
||||
{
|
||||
if (player == null) return;
|
||||
Log(
|
||||
$"CounterStrikeSharp - a test command was called by {new SteamID(player.SteamID).SteamId2} with {info.ArgString}");
|
||||
Logger.LogInformation(
|
||||
"CounterStrikeSharp - a test command was called by {SteamID2} with {Arguments}",
|
||||
((SteamID)player.SteamID).SteamId2, info.ArgString);
|
||||
});
|
||||
|
||||
AddCommand("css_changeteam", "change team", (player, info) =>
|
||||
@@ -291,7 +321,8 @@ namespace TestPlugin
|
||||
// Listens for any client use of the command `jointeam`.
|
||||
AddCommandListener("jointeam", (player, info) =>
|
||||
{
|
||||
Log($"{player.PlayerName} just did a jointeam (pre) [{info.ArgString}]");
|
||||
Logger.LogInformation("{PlayerName} just did a jointeam (pre) [{ArgString}]", player.PlayerName,
|
||||
info.ArgString);
|
||||
|
||||
return HookResult.Continue;
|
||||
});
|
||||
@@ -300,7 +331,7 @@ namespace TestPlugin
|
||||
[GameEventHandler]
|
||||
public HookResult OnPlayerConnect(EventPlayerConnect @event, GameEventInfo info)
|
||||
{
|
||||
Log($"Player {@event.Name} has connected! (post)");
|
||||
Logger.LogInformation("Player {Name} has connected! (post)", @event.Name);
|
||||
|
||||
return HookResult.Continue;
|
||||
}
|
||||
@@ -308,7 +339,7 @@ namespace TestPlugin
|
||||
[GameEventHandler(HookMode.Pre)]
|
||||
public HookResult OnPlayerConnectPre(EventPlayerConnect @event, GameEventInfo info)
|
||||
{
|
||||
Log($"Player {@event.Name} has connected! (pre)");
|
||||
Logger.LogInformation("Player {Name} has connected! (pre)", @event.Name);
|
||||
|
||||
return HookResult.Continue;
|
||||
}
|
||||
@@ -326,7 +357,7 @@ namespace TestPlugin
|
||||
[ConsoleCommand("cssharp_attribute", "This is a custom attribute event")]
|
||||
public void OnCommand(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
Log("cssharp_attribute called!");
|
||||
command.ReplyToCommand("cssharp_attribute called", true);
|
||||
}
|
||||
|
||||
[ConsoleCommand("css_changelevel", "Changes map")]
|
||||
@@ -359,7 +390,7 @@ namespace TestPlugin
|
||||
[ConsoleCommand("css_pause", "Pause Game")]
|
||||
public void OnCommandPause(CCSPlayerController? player, CommandInfo command)
|
||||
{
|
||||
Log("Pause");
|
||||
Logger.LogInformation("Pause");
|
||||
}
|
||||
|
||||
[ConsoleCommand("css_give", "Give named item")]
|
||||
@@ -372,17 +403,10 @@ namespace TestPlugin
|
||||
|
||||
private HookResult GenericEventHandler<T>(T @event, GameEventInfo info) where T : GameEvent
|
||||
{
|
||||
Log($"Event found {@event.Handle:X}, event name: {@event.EventName} dont broadcast: {info.DontBroadcast}");
|
||||
Logger.LogInformation("Event found {Pointer:X}, event name: {EventName}, dont broadcast: {DontBroadcast}",
|
||||
@event.Handle, @event.EventName, info.DontBroadcast);
|
||||
|
||||
return HookResult.Continue;
|
||||
}
|
||||
|
||||
private void Log(string message)
|
||||
{
|
||||
Console.BackgroundColor = ConsoleColor.DarkGray;
|
||||
Console.ForegroundColor = ConsoleColor.DarkMagenta;
|
||||
Console.WriteLine(message);
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,12 @@
|
||||
<Platforms>AnyCPU;x86</Platforms>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj" />
|
||||
<ProjectReference Include="..\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj">
|
||||
<Private>false</Private>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
79
src/core/coreconfig.cpp
Normal file
79
src/core/coreconfig.cpp
Normal file
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* 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 <fstream>
|
||||
#include "core/log.h"
|
||||
#include "core/coreconfig.h"
|
||||
|
||||
namespace counterstrikesharp {
|
||||
|
||||
CCoreConfig::CCoreConfig(const std::string& path) { m_sPath = path; }
|
||||
|
||||
CCoreConfig::~CCoreConfig() = default;
|
||||
|
||||
bool CCoreConfig::Init(char* conf_error, int conf_error_size)
|
||||
{
|
||||
std::ifstream ifs(m_sPath);
|
||||
|
||||
if (!ifs) {
|
||||
V_snprintf(conf_error, conf_error_size, "CoreConfig file not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
m_json = json::parse(ifs);
|
||||
|
||||
try {
|
||||
PublicChatTrigger = m_json["PublicChatTrigger"];
|
||||
SilentChatTrigger = m_json["SilentChatTrigger"];
|
||||
FollowCS2ServerGuidelines = m_json["FollowCS2ServerGuidelines"];
|
||||
} catch (const std::exception& ex) {
|
||||
V_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;
|
||||
}
|
||||
|
||||
bool CCoreConfig::IsTriggerInternal(std::vector<std::string> triggers, const std::string& message, std::string& prefix) const
|
||||
{
|
||||
for (std::string& trigger : triggers)
|
||||
{
|
||||
if (message.rfind(trigger, 0) == 0)
|
||||
{
|
||||
prefix = trigger;
|
||||
CSSHARP_CORE_TRACE("Trigger found, prefix is {}", prefix);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CCoreConfig::IsSilentChatTrigger(const std::string& message, std::string& prefix) const
|
||||
{
|
||||
return IsTriggerInternal(SilentChatTrigger, message, prefix);
|
||||
}
|
||||
|
||||
bool CCoreConfig::IsPublicChatTrigger(const std::string& message, std::string& prefix) const
|
||||
{
|
||||
return IsTriggerInternal(PublicChatTrigger, message, prefix);
|
||||
}
|
||||
} // namespace counterstrikesharp
|
||||
50
src/core/coreconfig.h
Normal file
50
src/core/coreconfig.h
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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>
|
||||
|
||||
namespace counterstrikesharp {
|
||||
|
||||
class CCoreConfig
|
||||
{
|
||||
public:
|
||||
std::vector<std::string> PublicChatTrigger = { std::string("!") };
|
||||
std::vector<std::string> SilentChatTrigger = { std::string("/") };
|
||||
bool FollowCS2ServerGuidelines = true;
|
||||
|
||||
using json = nlohmann::json;
|
||||
CCoreConfig(const std::string& path);
|
||||
~CCoreConfig();
|
||||
|
||||
bool Init(char* conf_error, int conf_error_size);
|
||||
const std::string GetPath() const;
|
||||
|
||||
bool IsSilentChatTrigger(const std::string& message, std::string& prefix) const;
|
||||
bool IsPublicChatTrigger(const std::string& message, std::string& prefix) const;
|
||||
|
||||
private:
|
||||
bool IsTriggerInternal(std::vector<std::string> triggers, const std::string& message, std::string& prefix) const;
|
||||
|
||||
private:
|
||||
std::string m_sPath;
|
||||
json m_json;
|
||||
};
|
||||
|
||||
} // namespace counterstrikesharp
|
||||
@@ -18,17 +18,18 @@
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <platform.h>
|
||||
#include "interfaces/interfaces.h"
|
||||
#include <cstdint>
|
||||
#include "core/gameconfig.h"
|
||||
|
||||
class CGameEntitySystem;
|
||||
|
||||
class CGameResourceService
|
||||
{
|
||||
public:
|
||||
CGameEntitySystem *GetGameEntitySystem()
|
||||
{
|
||||
return *reinterpret_cast<CGameEntitySystem **>((uintptr_t)(this) + 0x50);
|
||||
}
|
||||
public:
|
||||
CGameEntitySystem* GetGameEntitySystem()
|
||||
{
|
||||
return *reinterpret_cast<CGameEntitySystem**>(
|
||||
(uintptr_t)(this) +
|
||||
counterstrikesharp::globals::gameConfig->GetOffset("GameEntitySystem"));
|
||||
}
|
||||
};
|
||||
@@ -18,11 +18,12 @@
|
||||
*/
|
||||
|
||||
#include "cs2_interfaces.h"
|
||||
#include "interfaces/interfaces.h"
|
||||
|
||||
#include "tier0/memdbgon.h"
|
||||
#include "core/memory_module.h"
|
||||
#include "core/globals.h"
|
||||
#include "interfaces/interfaces.h"
|
||||
|
||||
// memdbgon must be the last include file in a .cpp file!!!
|
||||
#include "tier0/memdbgon.h"
|
||||
|
||||
namespace counterstrikesharp {
|
||||
void interfaces::Initialize() {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <string_view>
|
||||
#include <array>
|
||||
#include "core/cs2_sdk/interfaces/CUtlTSHash.h"
|
||||
#define CSGO2
|
||||
#define CS2
|
||||
|
||||
#define CSCHEMATYPE_GETSIZES_INDEX 3
|
||||
#define SCHEMASYSTEM_TYPE_SCOPES_OFFSET 0x190
|
||||
@@ -181,7 +181,8 @@ class CSchemaType
|
||||
CSchemaType* element_type_;
|
||||
};
|
||||
|
||||
struct generic_type_t {
|
||||
struct generic_type_t
|
||||
{
|
||||
uint64_t unknown;
|
||||
const char* m_name_; // 0x0008
|
||||
};
|
||||
@@ -316,12 +317,24 @@ class CSchemaSystemTypeScope
|
||||
public:
|
||||
CSchemaClassInfo* FindDeclaredClass(const char* class_name)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
CSchemaClassInfo* rv = nullptr;
|
||||
CALL_VIRTUAL(void, 2, this, &rv, class_name);
|
||||
return rv;
|
||||
#else
|
||||
return CALL_VIRTUAL(CSchemaClassInfo*, 2, this, class_name);
|
||||
#endif
|
||||
}
|
||||
|
||||
CSchemaEnumBinding* FindDeclaredEnum(const char* name)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
CSchemaEnumBinding* rv = nullptr;
|
||||
CALL_VIRTUAL(void, 3, this, &rv, name);
|
||||
return rv;
|
||||
#else
|
||||
return CALL_VIRTUAL(CSchemaEnumBinding*, 3, this, name);
|
||||
#endif
|
||||
}
|
||||
|
||||
CSchemaType* FindSchemaTypeByName(const char* name, std::uintptr_t* pSchema)
|
||||
@@ -349,24 +362,19 @@ class CSchemaSystemTypeScope
|
||||
return CALL_VIRTUAL(CSchemaEnumBinding*, 8, this, name);
|
||||
}
|
||||
|
||||
std::string_view GetScopeName() {
|
||||
return {m_name_.data()};
|
||||
}
|
||||
std::string_view GetScopeName() { return {m_name_.data()}; }
|
||||
|
||||
[[nodiscard]] CUtlTSHash<CSchemaClassBinding*> GetClasses() const {
|
||||
return m_classes_;
|
||||
}
|
||||
[[nodiscard]] CUtlTSHash<CSchemaClassBinding*> GetClasses() const { return m_classes_; }
|
||||
|
||||
[[nodiscard]] CUtlTSHash<CSchemaEnumBinding*> GetEnums() const { return m_enumes_; }
|
||||
|
||||
[[nodiscard]] CUtlTSHash<CSchemaEnumBinding*> GetEnums() const {
|
||||
return m_enumes_;
|
||||
}
|
||||
private:
|
||||
char pad_0x0000[0x8]; // 0x0000
|
||||
std::array<char, 256> m_name_ = {};
|
||||
char pad_0x0108[SCHEMASYSTEMTYPESCOPE_OFF1]; // 0x0108
|
||||
CUtlTSHash<CSchemaClassBinding*> m_classes_; // 0x0588
|
||||
char pad_0x0594[SCHEMASYSTEMTYPESCOPE_OFF2]; // 0x05C8
|
||||
CUtlTSHash<CSchemaEnumBinding*> m_enumes_; // 0x2DD0
|
||||
CUtlTSHash<CSchemaEnumBinding*> m_enumes_; // 0x2DD0
|
||||
private:
|
||||
static constexpr unsigned int s_class_list = 0x580;
|
||||
};
|
||||
|
||||
@@ -20,13 +20,15 @@
|
||||
#include "schema.h"
|
||||
|
||||
#include "interfaces/cs2_interfaces.h"
|
||||
#include "../globals.h"
|
||||
// #include <unordered_map>
|
||||
#include "tier1/utlmap.h"
|
||||
#include "tier0/memdbgon.h"
|
||||
#include "../memory.h"
|
||||
#include "core/globals.h"
|
||||
#include "core/memory.h"
|
||||
#include "core/log.h"
|
||||
|
||||
#include "tier1/utlmap.h"
|
||||
|
||||
// memdbgon must be the last include file in a .cpp file!!!
|
||||
#include "tier0/memdbgon.h"
|
||||
|
||||
using SchemaKeyValueMap_t = CUtlMap<uint32_t, SchemaKey>;
|
||||
using SchemaTableMap_t = CUtlMap<uint32_t, SchemaKeyValueMap_t*>;
|
||||
|
||||
|
||||
@@ -19,23 +19,15 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "stdint.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4005)
|
||||
#endif
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
#ifdef _WIN32
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
#include "tier0/dbg.h"
|
||||
#include "const.h"
|
||||
#include "../../utils/virtual.h"
|
||||
#include "stdint.h"
|
||||
#include "utils/virtual.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <stdint.h>
|
||||
#include <type_traits>
|
||||
|
||||
#undef schema
|
||||
|
||||
struct SchemaKey {
|
||||
@@ -64,6 +56,45 @@ inline uint64_t hash_64_fnv1a_const(const char *str, const uint64_t value = val_
|
||||
}
|
||||
|
||||
namespace schema {
|
||||
static std::vector<std::string> CS2BadList = {
|
||||
"m_bIsValveDS",
|
||||
"m_bIsQuestEligible",
|
||||
"m_iItemDefinitionIndex", // in unmanaged this cannot be set.
|
||||
"m_iEntityLevel",
|
||||
"m_iItemIDHigh",
|
||||
"m_iItemIDLow",
|
||||
"m_iAccountID",
|
||||
"m_iEntityQuality",
|
||||
|
||||
"m_bInitialized",
|
||||
"m_szCustomName",
|
||||
"m_iAttributeDefinitionIndex",
|
||||
"m_iRawValue32",
|
||||
"m_iRawInitialValue32",
|
||||
"m_flValue", // MNetworkAlias "m_iRawValue32"
|
||||
"m_flInitialValue", // MNetworkAlias "m_iRawInitialValue32"
|
||||
"m_bSetBonus",
|
||||
"m_nRefundableCurrency",
|
||||
|
||||
"m_OriginalOwnerXuidLow",
|
||||
"m_OriginalOwnerXuidHigh",
|
||||
|
||||
"m_nFallbackPaintKit",
|
||||
"m_nFallbackSeed",
|
||||
"m_flFallbackWear",
|
||||
"m_nFallbackStatTrak",
|
||||
|
||||
"m_iCompetitiveWins",
|
||||
"m_iCompetitiveRanking",
|
||||
"m_iCompetitiveRankType",
|
||||
"m_iCompetitiveRankingPredicted_Win",
|
||||
"m_iCompetitiveRankingPredicted_Loss",
|
||||
"m_iCompetitiveRankingPredicted_Tie",
|
||||
|
||||
"m_nActiveCoinRank",
|
||||
"m_nMusicID",
|
||||
};
|
||||
|
||||
int16_t FindChainOffset(const char *className);
|
||||
SchemaKey GetOffset(const char *className, uint32_t classKey, const char *memberName, uint32_t memberKey);
|
||||
} // namespace schema
|
||||
|
||||
236
src/core/gameconfig.cpp
Normal file
236
src/core/gameconfig.cpp
Normal file
@@ -0,0 +1,236 @@
|
||||
#include "core/gameconfig.h"
|
||||
#include <fstream>
|
||||
|
||||
#include "log.h"
|
||||
#include "metamod_oslink.h"
|
||||
|
||||
namespace counterstrikesharp {
|
||||
|
||||
CGameConfig::CGameConfig(const std::string& path) { m_sPath = path; }
|
||||
|
||||
CGameConfig::~CGameConfig() = default;
|
||||
|
||||
bool CGameConfig::Init(char* conf_error, int conf_error_size)
|
||||
{
|
||||
std::ifstream ifs(m_sPath);
|
||||
if (!ifs) {
|
||||
V_snprintf(conf_error, conf_error_size, "Gamedata file not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
m_json = json::parse(ifs);
|
||||
|
||||
#if _WIN32
|
||||
constexpr auto platform = "windows";
|
||||
#else
|
||||
constexpr auto platform = "linux";
|
||||
#endif
|
||||
|
||||
try {
|
||||
for (auto& [k, v] : m_json.items()) {
|
||||
if (v.contains("signatures")) {
|
||||
if (auto library = v["signatures"]["library"]; library.is_string()) {
|
||||
m_umLibraries[k] = library.get<std::string>();
|
||||
}
|
||||
if (auto signature = v["signatures"][platform]; signature.is_string()) {
|
||||
m_umSignatures[k] = signature.get<std::string>();
|
||||
}
|
||||
}
|
||||
if (v.contains("offsets")) {
|
||||
if (auto offset = v["offsets"][platform]; offset.is_number_integer()) {
|
||||
m_umOffsets[k] = offset.get<std::int64_t>();
|
||||
}
|
||||
}
|
||||
if (v.contains("patches")) {
|
||||
if (auto patch = v["patches"][platform]; patch.is_string()) {
|
||||
m_umPatches[k] = patch.get<std::string>();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& ex) {
|
||||
V_snprintf(conf_error, conf_error_size, "Failed to parse gamedata file: %s", ex.what());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::string CGameConfig::GetPath()
|
||||
{
|
||||
return m_sPath;
|
||||
}
|
||||
|
||||
const char* CGameConfig::GetLibrary(const std::string& name)
|
||||
{
|
||||
// My recommendation is switch to C++20.
|
||||
auto it = m_umLibraries.find(name);
|
||||
if (it == m_umLibraries.end()) {
|
||||
return nullptr;
|
||||
}
|
||||
return it->second.c_str();
|
||||
}
|
||||
|
||||
const char* CGameConfig::GetSignature(const std::string& name)
|
||||
{
|
||||
auto it = m_umSignatures.find(name);
|
||||
if (it == m_umSignatures.end()) {
|
||||
return nullptr;
|
||||
}
|
||||
return it->second.c_str();
|
||||
}
|
||||
|
||||
const char* CGameConfig::GetSymbol(const char* name)
|
||||
{
|
||||
const char* symbol = this->GetSignature(name);
|
||||
|
||||
if (!symbol || strlen(symbol) <= 1) {
|
||||
CSSHARP_CORE_ERROR("Missing symbol: {}\n", name);
|
||||
return nullptr;
|
||||
}
|
||||
return symbol + 1;
|
||||
}
|
||||
|
||||
const char* CGameConfig::GetPatch(const std::string& name)
|
||||
{
|
||||
auto it = m_umPatches.find(name);
|
||||
if (it == m_umPatches.end()) {
|
||||
return nullptr;
|
||||
}
|
||||
return it->second.c_str();
|
||||
}
|
||||
|
||||
int CGameConfig::GetOffset(const std::string& name)
|
||||
{
|
||||
auto it = m_umOffsets.find(name);
|
||||
if (it == m_umOffsets.end()) {
|
||||
return -1;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
void* CGameConfig::GetAddress(const std::string& name, void* engine, void* server, char* error,
|
||||
int maxlen)
|
||||
{
|
||||
CSSHARP_CORE_ERROR("Not implemented.");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
modules::CModule** CGameConfig::GetModule(const char* name)
|
||||
{
|
||||
const char* library = this->GetLibrary(name);
|
||||
if (!library)
|
||||
return nullptr;
|
||||
|
||||
if (strcmp(library, "engine") == 0)
|
||||
return &modules::engine;
|
||||
else if (strcmp(library, "server") == 0)
|
||||
return &modules::server;
|
||||
else if (strcmp(library, "vscript") == 0)
|
||||
return &modules::vscript;
|
||||
else if (strcmp(library, "tier0") == 0)
|
||||
return &modules::tier0;
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool CGameConfig::IsSymbol(const char* name)
|
||||
{
|
||||
const char* sigOrSymbol = this->GetSignature(name);
|
||||
if (!sigOrSymbol || strlen(sigOrSymbol) <= 0) {
|
||||
CSSHARP_CORE_ERROR("Missing signature or symbol: {}\n", name);
|
||||
return false;
|
||||
}
|
||||
return sigOrSymbol[0] == '@';
|
||||
}
|
||||
|
||||
void* CGameConfig::ResolveSignature(const char* name)
|
||||
{
|
||||
modules::CModule** module = this->GetModule(name);
|
||||
if (!module || !(*module)) {
|
||||
CSSHARP_CORE_ERROR("Invalid Module {}\n", name);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void* address = nullptr;
|
||||
if (this->IsSymbol(name)) {
|
||||
const char* symbol = this->GetSymbol(name);
|
||||
if (!symbol) {
|
||||
CSSHARP_CORE_ERROR("Invalid symbol for {}\n", name);
|
||||
return nullptr;
|
||||
}
|
||||
address = dlsym((*module)->m_hModule, symbol);
|
||||
} else {
|
||||
const char* signature = this->GetSignature(name);
|
||||
if (!signature) {
|
||||
CSSHARP_CORE_ERROR("Failed to find signature for {}\n", name);
|
||||
return nullptr;
|
||||
}
|
||||
size_t iLength = 0;
|
||||
byte* pSignature = HexToByte(signature, iLength);
|
||||
if (!pSignature) {
|
||||
return nullptr;
|
||||
}
|
||||
address = (*module)->FindSignature(pSignature, iLength);
|
||||
}
|
||||
|
||||
if (!address) {
|
||||
CSSHARP_CORE_ERROR("Failed to find address for {}\n", name);
|
||||
return nullptr;
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
std::string CGameConfig::GetDirectoryName(const std::string& directoryPathInput)
|
||||
{
|
||||
std::string directoryPath = std::string(directoryPathInput);
|
||||
|
||||
size_t found = std::string(directoryPath).find_last_of("/\\");
|
||||
if (found != std::string::npos) {
|
||||
return std::string(directoryPath, found + 1);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
int CGameConfig::HexStringToUint8Array(const char* hexString, uint8_t* byteArray, size_t maxBytes)
|
||||
{
|
||||
if (!hexString) {
|
||||
printf("Invalid hex string.\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
size_t hexStringLength = strlen(hexString);
|
||||
size_t byteCount = hexStringLength / 4; // Each "\\x" represents one byte.
|
||||
|
||||
if (hexStringLength % 4 != 0 || byteCount == 0 || byteCount > maxBytes) {
|
||||
printf("Invalid hex string format or byte count.\n");
|
||||
return -1; // Return an error code.
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < hexStringLength; i += 4) {
|
||||
if (sscanf(hexString + i, "\\x%2hhX", &byteArray[i / 4]) != 1) {
|
||||
printf("Failed to parse hex string at position %zu.\n", i);
|
||||
return -1; // Return an error code.
|
||||
}
|
||||
}
|
||||
|
||||
byteArray[byteCount] = '\0'; // Add a null-terminating character.
|
||||
|
||||
return byteCount; // Return the number of bytes successfully converted.
|
||||
}
|
||||
|
||||
byte* CGameConfig::HexToByte(const char* src, size_t& length)
|
||||
{
|
||||
if (!src || strlen(src) <= 0) {
|
||||
CSSHARP_CORE_INFO("Invalid hex string\n");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
length = strlen(src) / 4;
|
||||
uint8_t* dest = new uint8_t[length];
|
||||
int byteCount = HexStringToUint8Array(src, dest, length);
|
||||
if (byteCount <= 0) {
|
||||
CSSHARP_CORE_INFO("Invalid hex format %s\n", src);
|
||||
return nullptr;
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
} // namespace counterstrikesharp
|
||||
51
src/core/gameconfig.h
Normal file
51
src/core/gameconfig.h
Normal file
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
|
||||
#include "core/globals.h"
|
||||
#include "core/memory_module.h"
|
||||
#include <KeyValues.h>
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#undef snprintf
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace counterstrikesharp {
|
||||
|
||||
class CGameConfig
|
||||
{
|
||||
public:
|
||||
using json = nlohmann::json;
|
||||
CGameConfig(const std::string& path);
|
||||
~CGameConfig();
|
||||
|
||||
bool Init(char* conf_error, int conf_error_size);
|
||||
const std::string GetPath();
|
||||
const char* GetLibrary(const std::string& name);
|
||||
const char* GetSignature(const std::string& name);
|
||||
const char* GetSymbol(const char* name);
|
||||
const char* GetPatch(const std::string& name);
|
||||
int GetOffset(const std::string& name);
|
||||
void* GetAddress(const std::string& name, void* engine, void* server, char* error, int maxlen);
|
||||
modules::CModule** GetModule(const char* name);
|
||||
bool IsSymbol(const char* name);
|
||||
void* ResolveSignature(const char* name);
|
||||
|
||||
static std::string GetDirectoryName(const std::string& directoryPathInput);
|
||||
static int HexStringToUint8Array(const char* hexString, uint8_t* byteArray, size_t maxBytes);
|
||||
static byte* HexToByte(const char* src, size_t& length);
|
||||
|
||||
private:
|
||||
std::string m_sPath;
|
||||
// use Valve KeyValues in the future.
|
||||
// since we'd better make '\' easier.
|
||||
json m_json;
|
||||
std::unordered_map<std::string, int> m_umOffsets;
|
||||
std::unordered_map<std::string, std::string> m_umSignatures;
|
||||
std::unordered_map<std::string, void*> m_umAddresses;
|
||||
std::unordered_map<std::string, std::string> m_umLibraries;
|
||||
std::unordered_map<std::string, std::string> m_umPatches;
|
||||
};
|
||||
|
||||
} // namespace counterstrikesharp
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "mm_plugin.h"
|
||||
#include "core/globals.h"
|
||||
#include "core/managers/player_manager.h"
|
||||
#include "iserver.h"
|
||||
@@ -12,12 +13,12 @@
|
||||
|
||||
#include "log.h"
|
||||
#include "utils/virtual.h"
|
||||
#include "core/memory.h"
|
||||
#include "core/managers/con_command_manager.h"
|
||||
#include "core/managers/chat_manager.h"
|
||||
#include "memory_module.h"
|
||||
#include "interfaces/cs2_interfaces.h"
|
||||
#include "core/managers/entity_manager.h"
|
||||
#include "core/managers/client_command_manager.h"
|
||||
#include "core/managers/server_manager.h"
|
||||
#include <public/game/server/iplayerinfo.h>
|
||||
#include <public/entity2/entitysystem.h>
|
||||
@@ -25,44 +26,46 @@
|
||||
namespace counterstrikesharp {
|
||||
|
||||
namespace modules {
|
||||
CModule *engine = nullptr;
|
||||
CModule *tier0 = nullptr;
|
||||
CModule *server = nullptr;
|
||||
CModule *schemasystem = nullptr;
|
||||
CModule *vscript = nullptr;
|
||||
} // namespace modules
|
||||
CModule* engine = nullptr;
|
||||
CModule* tier0 = nullptr;
|
||||
CModule* server = nullptr;
|
||||
CModule* schemasystem = nullptr;
|
||||
CModule* vscript = nullptr;
|
||||
} // namespace modules
|
||||
|
||||
namespace globals {
|
||||
IVEngineServer *engine = nullptr;
|
||||
IGameEventManager2 *gameEventManager = nullptr;
|
||||
IGameEventSystem *gameEventSystem = nullptr;
|
||||
IPlayerInfoManager *playerinfoManager = nullptr;
|
||||
IBotManager *botManager = nullptr;
|
||||
IServerPluginHelpers *helpers = nullptr;
|
||||
IUniformRandomStream *randomStream = nullptr;
|
||||
IEngineTrace *engineTrace = nullptr;
|
||||
IEngineSound *engineSound = nullptr;
|
||||
INetworkStringTableContainer *netStringTables = nullptr;
|
||||
CGlobalVars *globalVars = nullptr;
|
||||
IFileSystem *fileSystem = nullptr;
|
||||
IServerGameDLL *serverGameDll = nullptr;
|
||||
IServerGameClients *serverGameClients = nullptr;
|
||||
INetworkServerService *networkServerService = nullptr;
|
||||
IServerTools *serverTools = nullptr;
|
||||
IPhysics *physics = nullptr;
|
||||
IPhysicsCollision *physicsCollision = nullptr;
|
||||
IPhysicsSurfaceProps *physicsSurfaceProps = nullptr;
|
||||
IMDLCache *modelCache = nullptr;
|
||||
IVoiceServer *voiceServer = nullptr;
|
||||
IVEngineServer* engine = nullptr;
|
||||
IGameEventManager2* gameEventManager = nullptr;
|
||||
IGameEventSystem* gameEventSystem = nullptr;
|
||||
IPlayerInfoManager* playerinfoManager = nullptr;
|
||||
IBotManager* botManager = nullptr;
|
||||
IServerPluginHelpers* helpers = nullptr;
|
||||
IUniformRandomStream* randomStream = nullptr;
|
||||
IEngineTrace* engineTrace = nullptr;
|
||||
IEngineSound* engineSound = nullptr;
|
||||
INetworkStringTableContainer* netStringTables = nullptr;
|
||||
CGlobalVars* globalVars = nullptr;
|
||||
IFileSystem* fileSystem = nullptr;
|
||||
IServerGameDLL* serverGameDll = nullptr;
|
||||
IServerGameClients* serverGameClients = nullptr;
|
||||
INetworkServerService* networkServerService = nullptr;
|
||||
IServerTools* serverTools = nullptr;
|
||||
IPhysics* physics = nullptr;
|
||||
IPhysicsCollision* physicsCollision = nullptr;
|
||||
IPhysicsSurfaceProps* physicsSurfaceProps = nullptr;
|
||||
IMDLCache* modelCache = nullptr;
|
||||
IVoiceServer* voiceServer = nullptr;
|
||||
CDotNetManager dotnetManager;
|
||||
ICvar *cvars = nullptr;
|
||||
ISource2Server *server = nullptr;
|
||||
CGlobalEntityList *globalEntityList = nullptr;
|
||||
CounterStrikeSharpMMPlugin *mmPlugin = nullptr;
|
||||
ICvar* cvars = nullptr;
|
||||
ISource2Server* server = nullptr;
|
||||
CGlobalEntityList* globalEntityList = nullptr;
|
||||
CounterStrikeSharpMMPlugin* mmPlugin = nullptr;
|
||||
SourceHook::Impl::CSourceHookImpl source_hook_impl;
|
||||
SourceHook::ISourceHook *source_hook = &source_hook_impl;
|
||||
ISmmAPI *ismm = nullptr;
|
||||
SourceHook::ISourceHook* source_hook = &source_hook_impl;
|
||||
ISmmAPI* ismm = nullptr;
|
||||
CGameEntitySystem* entitySystem = nullptr;
|
||||
CCoreConfig* coreConfig = nullptr;
|
||||
CGameConfig* gameConfig = nullptr;
|
||||
|
||||
// Custom Managers
|
||||
CallbackManager callbackManager;
|
||||
@@ -72,10 +75,12 @@ TimerSystem timerSystem;
|
||||
ConCommandManager conCommandManager;
|
||||
EntityManager entityManager;
|
||||
ChatManager chatManager;
|
||||
ClientCommandManager clientCommandManager;
|
||||
ServerManager serverManager;
|
||||
|
||||
void Initialize() {
|
||||
GetLegacyGameEventListener_t* GetLegacyGameEventListener = nullptr;
|
||||
|
||||
void Initialize()
|
||||
{
|
||||
modules::engine = new modules::CModule(ROOTBIN, "engine2");
|
||||
modules::tier0 = new modules::CModule(ROOTBIN, "tier0");
|
||||
modules::server = new modules::CModule(GAMEBIN, "server");
|
||||
@@ -84,19 +89,27 @@ void Initialize() {
|
||||
|
||||
interfaces::Initialize();
|
||||
|
||||
globals::entitySystem = interfaces::pGameResourceServiceServer->GetGameEntitySystem();
|
||||
entitySystem = interfaces::pGameResourceServiceServer->GetGameEntitySystem();
|
||||
|
||||
gameEventManager = (IGameEventManager2 *)(CALL_VIRTUAL(uintptr_t, 91, server) - 8);
|
||||
GetLegacyGameEventListener = reinterpret_cast<GetLegacyGameEventListener_t*>(modules::server->FindSignature(
|
||||
globals::gameConfig->GetSignature("LegacyGameEventListener")));
|
||||
|
||||
if (int offset = -1; (offset = gameConfig->GetOffset("GameEventManager")) != -1) {
|
||||
gameEventManager = (IGameEventManager2*)(CALL_VIRTUAL(uintptr_t, offset, server) - 8);
|
||||
}
|
||||
}
|
||||
|
||||
int source_hook_pluginid = 0;
|
||||
CGlobalVars *getGlobalVars() {
|
||||
INetworkGameServer *server = networkServerService->GetIGameServer();
|
||||
CGlobalVars* getGlobalVars()
|
||||
{
|
||||
INetworkGameServer* server = networkServerService->GetIGameServer();
|
||||
|
||||
if (!server) return nullptr;
|
||||
if (!server) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return networkServerService->GetIGameServer()->GetGlobals();
|
||||
}
|
||||
|
||||
} // namespace globals
|
||||
} // namespace counterstrikesharp
|
||||
} // namespace globals
|
||||
} // namespace counterstrikesharp
|
||||
|
||||
@@ -33,6 +33,7 @@ class ICvar;
|
||||
class IGameEventSystem;
|
||||
class CounterStrikeSharpMMPlugin;
|
||||
class CGameEntitySystem;
|
||||
class IGameEventListener2;
|
||||
|
||||
namespace counterstrikesharp {
|
||||
class EntityListener;
|
||||
@@ -48,8 +49,9 @@ class ChatCommands;
|
||||
class HookManager;
|
||||
class EntityManager;
|
||||
class ChatManager;
|
||||
class ClientCommandManager;
|
||||
class ServerManager;
|
||||
class CCoreConfig;
|
||||
class CGameConfig;
|
||||
|
||||
namespace globals {
|
||||
|
||||
@@ -91,7 +93,6 @@ extern EntityManager entityManager;
|
||||
extern TimerSystem timerSystem;
|
||||
extern ChatCommands chatCommands;
|
||||
extern ChatManager chatManager;
|
||||
extern ClientCommandManager clientCommandManager;
|
||||
extern ServerManager serverManager;
|
||||
|
||||
extern HookManager hookManager;
|
||||
@@ -100,6 +101,12 @@ extern int source_hook_pluginid;
|
||||
extern IGameEventSystem *gameEventSystem;
|
||||
extern CounterStrikeSharpMMPlugin *mmPlugin;
|
||||
extern ISmmAPI *ismm;
|
||||
extern CCoreConfig* coreConfig;
|
||||
extern CGameConfig* gameConfig;
|
||||
|
||||
typedef IGameEventListener2 *GetLegacyGameEventListener_t(CPlayerSlot slot);
|
||||
|
||||
extern GetLegacyGameEventListener_t* GetLegacyGameEventListener;
|
||||
|
||||
void Initialize();
|
||||
// Should only be called within the active game loop (i e map should be loaded
|
||||
|
||||
@@ -8,17 +8,22 @@ namespace counterstrikesharp {
|
||||
std::shared_ptr<spdlog::logger> Log::m_core_logger;
|
||||
|
||||
void Log::Init() {
|
||||
std::vector<spdlog::sink_ptr> logSinks;
|
||||
auto ansiColorSink = std::make_shared<spdlog::sinks::ansicolor_stderr_sink_mt>();
|
||||
ansiColorSink->set_color(spdlog::level::trace, ansiColorSink->yellow);
|
||||
logSinks.emplace_back(ansiColorSink);
|
||||
logSinks.emplace_back(
|
||||
std::vector<spdlog::sink_ptr> log_sinks;
|
||||
auto color_sink = std::make_shared<spdlog::sinks::stderr_color_sink_mt>();
|
||||
#if _WIN32
|
||||
color_sink->set_color(spdlog::level::trace, 6);
|
||||
#else
|
||||
color_sink->set_color(spdlog::level::trace, color_sink->yellow);
|
||||
#endif
|
||||
|
||||
log_sinks.emplace_back(color_sink);
|
||||
log_sinks.emplace_back(
|
||||
std::make_shared<spdlog::sinks::basic_file_sink_mt>("counterstrikesharp.log", true));
|
||||
|
||||
logSinks[0]->set_pattern("%^[%T.%e] %n: %v%$");
|
||||
logSinks[1]->set_pattern("[%T.%e] [%l] %n: %v");
|
||||
log_sinks[0]->set_pattern("%^[%T.%e] %n: %v%$");
|
||||
log_sinks[1]->set_pattern("[%T.%e] [%l] %n: %v");
|
||||
|
||||
m_core_logger = std::make_shared<spdlog::logger>("CSSharp", begin(logSinks), end(logSinks));
|
||||
m_core_logger = std::make_shared<spdlog::logger>("CSSharp", begin(log_sinks), end(log_sinks));
|
||||
spdlog::register_logger(m_core_logger);
|
||||
m_core_logger->set_level(spdlog::level::info);
|
||||
m_core_logger->flush_on(spdlog::level::info);
|
||||
|
||||
@@ -24,9 +24,13 @@
|
||||
#include <public/eiface.h>
|
||||
#include "core/memory.h"
|
||||
#include "core/log.h"
|
||||
#include "core/coreconfig.h"
|
||||
#include "core/gameconfig.h"
|
||||
|
||||
#include <funchook.h>
|
||||
|
||||
#include "core/memory_module.h"
|
||||
|
||||
namespace counterstrikesharp {
|
||||
|
||||
ChatManager::ChatManager() {}
|
||||
@@ -35,11 +39,13 @@ ChatManager::~ChatManager() {}
|
||||
|
||||
void ChatManager::OnAllInitialized()
|
||||
{
|
||||
// TODO: Allow reading of the shared game data json from the C++ side too so this isn't
|
||||
// being hardcoded.
|
||||
m_pHostSay = (HostSay)FindSignature(
|
||||
MODULE_PREFIX "server" MODULE_EXT,
|
||||
R"(\x55\x48\x89\xE5\x41\x57\x49\x89\xFF\x41\x56\x41\x55\x41\x54\x4D\x89\xC4)");
|
||||
m_pHostSay = reinterpret_cast<HostSay>(
|
||||
modules::server->FindSignature(globals::gameConfig->GetSignature("Host_Say")));
|
||||
|
||||
if (m_pHostSay == nullptr) {
|
||||
CSSHARP_CORE_ERROR("Failed to find signature for \'Host_Say\'");
|
||||
return;
|
||||
}
|
||||
|
||||
auto m_hook = funchook_create();
|
||||
funchook_prepare(m_hook, (void**)&m_pHostSay, (void*)&DetourHostSay);
|
||||
@@ -51,71 +57,72 @@ void ChatManager::OnShutdown() {}
|
||||
void DetourHostSay(CBaseEntity* pController, CCommand& args, bool teamonly, int unk1,
|
||||
const char* unk2)
|
||||
{
|
||||
CCommand newArgs;
|
||||
newArgs.Tokenize(args.Arg(1));
|
||||
|
||||
if (*args[1] == '/' || *args[1] == '!') {
|
||||
globals::chatManager.OnSayCommandPost(pController, newArgs);
|
||||
return;
|
||||
}
|
||||
|
||||
m_pHostSay(pController, args, teamonly, unk1, unk2);
|
||||
|
||||
if (pController) {
|
||||
auto pEvent = globals::gameEventManager->CreateEvent("player_chat", true);
|
||||
if (pEvent) {
|
||||
pEvent->SetBool("teamonly", teamonly);
|
||||
pEvent->SetInt("userid", pController->GetEntityIndex().Get());
|
||||
pEvent->SetInt("userid", pController->GetEntityIndex().Get() - 1);
|
||||
pEvent->SetString("text", args[1]);
|
||||
|
||||
globals::gameEventManager->FireEvent(pEvent, true);
|
||||
}
|
||||
}
|
||||
|
||||
std::string prefix;
|
||||
bool bSilent = globals::coreConfig->IsSilentChatTrigger(args[1], prefix);
|
||||
bool bCommand = globals::coreConfig->IsPublicChatTrigger(args[1], prefix) || bSilent;
|
||||
|
||||
if (!bSilent) {
|
||||
m_pHostSay(pController, args, teamonly, unk1, unk2);
|
||||
}
|
||||
|
||||
if (bCommand)
|
||||
{
|
||||
char *pszMessage = (char *)(args.ArgS() + prefix.length() + 1);
|
||||
|
||||
// Trailing slashes are only removed if Host_Say has been called.
|
||||
if (bSilent)
|
||||
pszMessage[V_strlen(pszMessage) - 1] = 0;
|
||||
|
||||
CCommand args;
|
||||
args.Tokenize(pszMessage);
|
||||
|
||||
auto prefixedPhrase = std::string("css_") + args.Arg(0);
|
||||
auto bValidWithPrefix = globals::conCommandManager.IsValidValveCommand(prefixedPhrase.c_str());
|
||||
|
||||
if (bValidWithPrefix) {
|
||||
// Re-tokenize with a `css_` prefix if we have found that its a valid command.
|
||||
args.Tokenize(("css_" + std::string(pszMessage)).c_str());
|
||||
}
|
||||
|
||||
globals::chatManager.OnSayCommandPost(pController, args);
|
||||
}
|
||||
}
|
||||
|
||||
bool ChatManager::OnSayCommandPre(CBaseEntity* pController, CCommand& command) {
|
||||
return false;
|
||||
}
|
||||
bool ChatManager::OnSayCommandPre(CBaseEntity* pController, CCommand& command) { return false; }
|
||||
|
||||
bool ChatManager::OnSayCommandPost(CBaseEntity* pController, CCommand& command)
|
||||
void ChatManager::OnSayCommandPost(CBaseEntity* pController, CCommand& command)
|
||||
{
|
||||
const char* args = command.ArgS();
|
||||
auto commandStr = command.Arg(0);
|
||||
|
||||
return InternalDispatch(pController, commandStr + 1, command);
|
||||
return InternalDispatch(pController, commandStr, command);
|
||||
}
|
||||
|
||||
bool ChatManager::InternalDispatch(CBaseEntity* pPlayerController, const char* szTriggerPhase,
|
||||
void ChatManager::InternalDispatch(CBaseEntity* pPlayerController, const char* szTriggerPhase,
|
||||
CCommand& fullCommand)
|
||||
{
|
||||
auto ppArgV = new const char*[fullCommand.ArgC()];
|
||||
ppArgV[0] = strdup(szTriggerPhase);
|
||||
for (int i = 1; i < fullCommand.ArgC(); i++) {
|
||||
ppArgV[i] = fullCommand.Arg(i);
|
||||
}
|
||||
|
||||
auto prefixedPhrase = std::string("css_") + szTriggerPhase;
|
||||
|
||||
auto command = globals::conCommandManager.FindCommand(prefixedPhrase.c_str());
|
||||
|
||||
if (command) {
|
||||
ppArgV[0] = prefixedPhrase.c_str();
|
||||
}
|
||||
|
||||
CCommand commandCopy(fullCommand.ArgC(), ppArgV);
|
||||
|
||||
if (pPlayerController == nullptr) {
|
||||
auto result = globals::conCommandManager.InternalDispatch(CPlayerSlot(-1), &commandCopy);
|
||||
delete[] ppArgV;
|
||||
return result;
|
||||
globals::conCommandManager.ExecuteCommandCallbacks(
|
||||
fullCommand.Arg(0), CCommandContext(CommandTarget_t::CT_NO_TARGET, CPlayerSlot(-1)),
|
||||
fullCommand, HookMode::Pre);
|
||||
return;
|
||||
}
|
||||
|
||||
auto index = pPlayerController->GetEntityIndex().Get();
|
||||
|
||||
auto slot = CPlayerSlot(index - 1);
|
||||
|
||||
auto result = globals::conCommandManager.InternalDispatch(slot, &commandCopy);
|
||||
delete[] ppArgV;
|
||||
return result;
|
||||
globals::conCommandManager.ExecuteCommandCallbacks(
|
||||
fullCommand.Arg(0), CCommandContext(CommandTarget_t::CT_NO_TARGET, slot), fullCommand,
|
||||
HookMode::Pre);
|
||||
}
|
||||
} // namespace counterstrikesharp
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user