VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
EngineHooks.cpp
Go to the documentation of this file.
2
5
9#include <engine2/gamesessionconfiguration.h>
10#include <engine2/inetworkserverservice.h>
11#include <engine2/isource2server.h>
12#include <engine2/ivengineserver2.h>
13#include <entity2/entitysystem.h>
14#include <icvar.h>
15#include <igamesystem.h>
16#include <inetchannelinfo.h>
17#include <interfaces/interfaces.h>
18#include <string>
19#include <string_view>
20#include <tier0/buffer_string.h>
21#include <tier0/convar.h>
22#include <utility>
23
24namespace VoltMod
25{
26
27/** The engine passes null for an absent string. */
28static std::string_view Text(const char* text)
29{
30 return text != nullptr ? text : "";
31}
32
33/** Offer a command to the plugins, and keep it from the engine when one consumes it. */
34static HookResult<void> RunCommand(PluginRegistry& registry, std::string_view name, const CCommand& arguments, int slot)
35{
36 // ArgS is the whole line after the command name.
37 const bool consumed = registry.RaiseConsoleCommand(name, Text(arguments.ArgS()), slot);
38 return consumed ? HookResult<void>::Block() : HookResult<void>{};
39}
40
41/** Ask the plugins about a joining client, and refuse it with the first reason one gives. */
42static HookResult<bool> AdmitClient(PluginRegistry& registry, int slot, uint64_t xuid, std::string_view name,
43 CBufferString* rejectReason)
44{
45 const std::string reason = registry.RaiseClientConnecting(slot, static_cast<int64_t>(xuid), name);
46 if (reason.empty())
47 {
48 return {};
49 }
50 if (rejectReason != nullptr)
51 {
52 rejectReason->Insert(0, reason.c_str());
53 }
54 return HookResult<bool>::Block(false);
55}
56
57/** A client's address, or empty for a bot, which has no net channel. */
58static std::string_view ClientAddress(IVEngineServer2* server, CPlayerSlot slot)
59{
60 auto* channel = server->GetPlayerNetInfo(slot);
61 return channel != nullptr ? Text(channel->GetAddress()) : std::string_view{};
62}
63
64/** Hand every map's resource manifest to the plugins. The game rules system is in every session. */
66{
67 const VirtualFn<void(IGameSystem*, const EventBuildGameSessionManifest_t*)> build(
68 KHook::GetVtableIndex(&IGameSystem::OnBuildGameSessionManifest),
69 FindVirtualTable("server", "CGameRulesGameSystem"));
70 const auto onBuildManifest = [&registry](IGameSystem&, const EventBuildGameSessionManifest_t* event) {
71 if (event && event->m_pResourceManifest)
72 {
73 registry.RaiseBuildGameSessionManifest(event->m_pResourceManifest);
74 }
75 };
76 return HookVirtual("CGameRulesGameSystem::BuildGameSessionManifest", build, nullptr, onBuildManifest);
77}
78
79EngineHooks::EngineHooks(PluginRegistry& registry, const EngineInterfaces& engine, std::function<void()> beforeFrame,
80 std::function<void()> beforeServerStartup, std::function<void(int64_t)> beforeClientConnected,
81 std::function<void(int64_t)> afterClientDisconnected)
82 : _registry(registry),
83 _beforeFrame(std::move(beforeFrame)),
84 _beforeServerStartup(std::move(beforeServerStartup)),
85 _beforeClientConnected(std::move(beforeClientConnected)),
86 _afterClientDisconnected(std::move(afterClientDisconnected))
87{
88 // Registers the host's own ConCommands, `volt` among them.
89 g_pCVar = engine.Cvar;
90 ConVar_Register(FCVAR_RELEASE | FCVAR_CLIENT_CAN_EXECUTE | FCVAR_SERVER_CAN_EXECUTE | FCVAR_GAMEDLL);
91
92 auto add = [this](Subscription hook) { _hooks.Add(std::move(hook)); };
93
94 const auto onFrame = [this](IServerGameDLL&, bool, bool, bool) {
95 _beforeFrame();
96 _registry.RaiseFrame();
97 };
98 const auto onStartupServer = [this](INetworkServerService&, const GameSessionConfiguration_t&,
99 ISource2WorldSession*, const char* mapName) {
100 const std::string_view map = Text(mapName);
101 Log::Info("Server startup: map '{}'.", map.empty() ? "<none>" : map);
102 _beforeServerStartup();
103 _registry.RaiseServerStartup(map);
104 DisconnectEveryone();
105 };
106 const auto onClientConnect = [this](IServerGameClients&, CPlayerSlot slot, const char* name, uint64 xuid,
107 const char*, bool, CBufferString* rejectReason) {
108 return AdmitClient(_registry, slot.Get(), xuid, Text(name), rejectReason);
109 };
110 const auto onClientConnected = [this](IServerGameClients&, CPlayerSlot slot, const char* name, uint64 xuid,
111 const char*, const char* address, bool) {
112 // Before the call: the address is gone after it.
113 ConnectClient(slot.Get(), xuid, Text(name), Text(address));
114 };
115 const auto onClientPutInServer = [this, server = engine.Engine](IServerGameClients&, CPlayerSlot slot,
116 const char* name, ClientPutInServerType_t,
117 uint64 xuid) {
118 if (IsValidSlot(slot.Get()) && !_registry.IsConnected(slot.Get()))
119 {
120 ConnectClient(slot.Get(), xuid, Text(name), ClientAddress(server, slot));
121 }
122 };
123 const auto onClientDisconnect = [this](IServerGameClients&, CPlayerSlot slot, ENetworkDisconnectionReason,
124 const char*, uint64 xuid, const char*) {
125 _registry.RaiseClientDisconnected(slot.Get());
126 _afterClientDisconnected(static_cast<int64_t>(xuid));
127 };
128 const auto onClientFullyConnect = [this](IServerGameClients&, CPlayerSlot slot) {
129 _registry.RaiseClientFullyConnected(slot.Get());
130 };
131 const auto onClientSettingsChanged = [this](IServerGameClients&, CPlayerSlot slot) {
132 _registry.RaiseClientSettingsChanged(slot.Get());
133 };
134 const auto onConCommand = [this](ICvar&, ConCommandRef command, const CCommandContext& context,
135 const CCommand& arguments) {
136 return RunCommand(_registry, Text(command.GetName()), arguments, context.GetPlayerSlot().Get());
137 };
138 const auto onClientCommand = [this](IServerGameClients&, CPlayerSlot slot, const CCommand& arguments) {
139 return RunCommand(_registry, Text(arguments.Arg(0)), arguments, slot.Get());
140 };
141 const auto onCheckTransmit = [this](ISource2GameEntities&, CCheckTransmitInfo** infoList, int infoCount,
142 CBitVec<MAX_EDICTS>&, CBitVec<MAX_EDICTS>&, const Entity2Networkable_t**,
143 const uint16*, int) { _registry.RaiseCheckTransmit(infoList, infoCount); };
144
145 add(HookInterface(&IServerGameDLL::GameFrame, engine.ServerGameDll, nullptr, onFrame));
146 add(HookInterface(&INetworkServerService::StartupServer, engine.NetworkServerService, nullptr, onStartupServer));
147 // Before the engine admits the player, so a refusal keeps them out with a reason they see.
148 add(HookInterface(&IServerGameClients::ClientConnect, engine.ServerGameClients, onClientConnect));
149 add(HookInterface(&IServerGameClients::OnClientConnected, engine.ServerGameClients, onClientConnected));
150 // Clients returning from a map change skip OnClientConnected.
151 add(HookInterface(&IServerGameClients::ClientPutInServer, engine.ServerGameClients, nullptr, onClientPutInServer));
152 // After the call, before the slot is reused.
153 add(HookInterface(&IServerGameClients::ClientDisconnect, engine.ServerGameClients, nullptr, onClientDisconnect));
154 add(HookInterface(&IServerGameClients::ClientFullyConnect, engine.ServerGameClients, nullptr,
155 onClientFullyConnect));
156 add(HookInterface(&IServerGameClients::ClientSettingsChanged, engine.ServerGameClients, nullptr,
157 onClientSettingsChanged));
158 add(HookInterface(&ICvar::DispatchConCommand, engine.Cvar, onConCommand));
159 // Client commands that are not ConCommands, `vote` among them.
160 add(HookInterface(&IServerGameClients::ClientCommand, engine.ServerGameClients, onClientCommand));
161 // Filter the bit vectors after the game fills them.
162 add(HookInterface(&ISource2GameEntities::CheckTransmit, engine.GameEntities, nullptr, onCheckTransmit));
163
164 if (auto manifest = HookSessionManifest(_registry))
165 {
166 add(std::move(*manifest));
167 }
168 else
169 {
170 Log::Error("Precache is off: {}", manifest.error().Detail);
171 }
172
173 Log::Info("Engine hooks installed.");
174}
175
176void EngineHooks::ConnectClient(int slot, uint64_t xuid, std::string_view name, std::string_view address)
177{
178 _beforeClientConnected(static_cast<int64_t>(xuid));
179 _registry.RaiseClientConnected(slot, static_cast<int64_t>(xuid), name, address);
180}
181
182void EngineHooks::DisconnectEveryone()
183{
184 for (int slot = 0; slot < MaxPlayers; ++slot)
185 {
186 if (_registry.IsConnected(slot))
187 {
188 _registry.RaiseClientDisconnected(slot);
189 }
190 }
191}
192
193} // namespace VoltMod
EngineHooks(PluginRegistry &registry, const EngineInterfaces &engine, std::function< void()> beforeFrame, std::function< void()> beforeServerStartup, std::function< void(int64_t)> beforeClientConnected, std::function< void(int64_t)> afterClientDisconnected)
A hook before-handler's verdict.
static HookResult Block(Ret value)
The loaded plugins and the engine events raised on them, one per process.
std::string RaiseClientConnecting(int slot, int64_t steamId, std::string_view name)
void RaiseClientConnected(int slot, int64_t steamId, std::string_view name, std::string_view address)
void RaiseBuildGameSessionManifest(IEntityResourceManifest *manifest)
bool RaiseConsoleCommand(std::string_view name, std::string_view arguments, int slot)
void RaiseClientDisconnected(int slot)
bool IsConnected(int slot) const
Owns one registration and releases it on destruction.
void Error(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:97
void Info(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:79
Result< Subscription > HookVirtual(std::string_view name, const VirtualFn< Ret(Object *, Args...)> &function, Before &&before, After &&after=nullptr)
Hook a gamedata-bound virtual function on objects sharing its class vtable.
Definition Hook.hpp:168
static HookResult< bool > AdmitClient(PluginRegistry &registry, int slot, uint64_t xuid, std::string_view name, CBufferString *rejectReason)
static HookResult< void > RunCommand(PluginRegistry &registry, std::string_view name, const CCommand &arguments, int slot)
std::expected< T, Error > Result
Definition Result.hpp:64
constexpr bool IsValidSlot(int slot)
Definition Slot.hpp:13
static std::string_view ClientAddress(IVEngineServer2 *server, CPlayerSlot slot)
static std::string_view Text(const char *text)
Subscription HookInterface(Ret(Iface::*method)(Args...), Iface *instance, Before &&before, After &&after=nullptr)
Hook one virtual method of an engine interface for a subscription's lifetime.
Definition Hook.hpp:142
static Result< Subscription > HookSessionManifest(PluginRegistry &registry)
constexpr int MaxPlayers
Definition Slot.hpp:7
void * FindVirtualTable(std::string_view moduleName, std::string_view className)
ISource2GameClients * ServerGameClients
ISource2GameEntities * GameEntities
INetworkServerService * NetworkServerService