-
-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathmm_plugin.cpp
More file actions
326 lines (255 loc) · 12.8 KB
/
Copy pathmm_plugin.cpp
File metadata and controls
326 lines (255 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/**
* vim: set ts=4 sw=4 tw=99 noet :
* ======================================================
* Metamod:Source Sample Plugin
* Written by AlliedModders LLC.
* ======================================================
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* This sample plugin is public domain.
*/
#include "mm_plugin.h"
#include <cstdio>
#include "core/detours.h"
#include "core/coreconfig.h"
#include "core/game_system.h"
#include "core/gameconfig.h"
#include "core/gameconfig_updater.h"
#include "core/global_listener.h"
#include "core/log.h"
#include "core/managers/entity_manager.h"
#include "core/tick_scheduler.h"
#include "core/timer_system.h"
#include "core/utils.h"
#include "entity2/entitysystem.h"
#include "igameeventsystem.h"
#include "interfaces/cs2_interfaces.h"
#include "iserver.h"
#include "scripting/callback_manager.h"
#include "scripting/dotnet_host.h"
#include "scripting/script_engine.h"
#include "tier0/vprof.h"
#include "tier0/icommandline.h"
#include "tier1/utlstringtoken.h"
DLL_IMPORT ICommandLine* CommandLine();
#define VERSION_STRING "v" SEMVER " @ " GITHUB_SHA
#define BUILD_TIMESTAMP __DATE__ " " __TIME__
int g_iLoadEventsFromFileId = -1;
counterstrikesharp::GlobalClass* counterstrikesharp::GlobalClass::head = nullptr;
CGameEntitySystem* GameEntitySystem() { return counterstrikesharp::globals::entitySystem; }
// TODO: Workaround for windows, we __MUST__ have COUNTERSTRIKESHARP_API to handle it.
// like on windows it should be `extern "C" __declspec(dllexport)`, on linux it should be anything else.
DLL_EXPORT void InvokeNative(counterstrikesharp::fxNativeContext& context)
{
if (context.nativeIdentifier == 0) return;
if (context.nativeIdentifier != counterstrikesharp::hash_string_const("QUEUE_TASK_FOR_FRAME") &&
context.nativeIdentifier != counterstrikesharp::hash_string_const("GET_SCHEMA_OFFSET") &&
counterstrikesharp::globals::gameThreadId != std::this_thread::get_id())
{
counterstrikesharp::ScriptContextRaw scriptContext(context);
scriptContext.ThrowNativeError("Invoked on a non-main thread");
CSSHARP_CORE_CRITICAL("Native {:x} was invoked on a non-main thread", context.nativeIdentifier);
return;
}
counterstrikesharp::ScriptEngine::InvokeNative(context);
}
class GameSessionConfiguration_t
{
};
PLUGIN_EXPOSE(CounterStrikeSharpMMPlugin, counterstrikesharp::gPlugin);
namespace counterstrikesharp {
SH_DECL_HOOK3_void(IServerGameDLL, GameFrame, SH_NOATTRIB, 0, bool, bool, bool);
SH_DECL_HOOK3_void(
INetworkServerService, StartupServer, SH_NOATTRIB, 0, const GameSessionConfiguration_t&, ISource2WorldSession*, const char*);
SH_DECL_HOOK3_void(IEngineServiceMgr, RegisterLoopMode, SH_NOATTRIB, 0, const char*, ILoopModeFactory*, void**);
SH_DECL_HOOK1(IEngineServiceMgr, FindService, SH_NOATTRIB, 0, IEngineService*, const char*);
SH_DECL_HOOK2(IGameEventManager2, LoadEventsFromFile, SH_NOATTRIB, 0, int, const char*, bool);
CounterStrikeSharpMMPlugin gPlugin;
#if 0
// Currently unavailable, requires hl2sdk work!
ConVar sample_cvar("sample_cvar", "42", 0);
#endif
bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI* ismm, char* error, size_t maxlen, bool late)
{
PLUGIN_SAVEVARS();
globals::ismm = ismm;
globals::gameThreadId = std::this_thread::get_id();
Log::Init();
CSSHARP_CORE_INFO("Initializing with command line: {}", CommandLine()->GetCmdLine());
const char* basePath = CommandLine()->ParmValue(MakeStringToken("+css_basepath"), "/addons/counterstrikesharp");
GET_V_IFACE_CURRENT(GetEngineFactory, globals::engineServer2, IVEngineServer2, SOURCE2ENGINETOSERVER_INTERFACE_VERSION);
GET_V_IFACE_CURRENT(GetEngineFactory, globals::engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
GET_V_IFACE_CURRENT(GetEngineFactory, globals::cvars, ICvar, CVAR_INTERFACE_VERSION);
GET_V_IFACE_CURRENT(GetEngineFactory, g_pGameResourceServiceServer, IGameResourceService, GAMERESOURCESERVICESERVER_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetServerFactory, globals::server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
GET_V_IFACE_ANY(GetServerFactory, globals::serverGameClients, IServerGameClients, INTERFACEVERSION_SERVERGAMECLIENTS);
GET_V_IFACE_ANY(GetEngineFactory, globals::networkServerService, INetworkServerService, NETWORKSERVERSERVICE_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::schemaSystem, CSchemaSystem, SCHEMASYSTEM_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::gameEventSystem, IGameEventSystem, GAMEEVENTSYSTEM_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::engineServiceManager, IEngineServiceMgr, ENGINESERVICEMGR_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetEngineFactory, globals::networkMessages, INetworkMessages, NETWORKMESSAGES_INTERFACE_VERSION);
GET_V_IFACE_ANY(GetServerFactory, globals::gameEntities, ISource2GameEntities, SOURCE2GAMEENTITIES_INTERFACE_VERSION);
g_pCVar = globals::cvars;
g_pSource2GameEntities = globals::gameEntities;
interfaces::pGameResourceServiceServer = (CGameResourceService*)g_pGameResourceServiceServer;
if (utils::RelativeDirectory(std::string(basePath)) == "NotFound")
{
CSSHARP_CORE_ERROR("Invalid base path: {}", basePath);
return false;
}
CSSHARP_CORE_INFO("Current root directory: {}", utils::GetRootDirectory());
auto coreconfig_path = std::string(utils::ConfigsDirectory() + "/core");
globals::coreConfig = new CCoreConfig(coreconfig_path);
char coreconfig_error[255] = "";
if (!globals::coreConfig->Init(coreconfig_error, sizeof(coreconfig_error)))
{
CSSHARP_CORE_ERROR("Could not read \'{}\'. Error: {}", coreconfig_path, coreconfig_error);
return false;
}
Log::Close();
Log::Init(globals::coreConfig->LogFilePath);
CSSHARP_CORE_INFO("CoreConfig loaded.");
if (globals::coreConfig->AutoUpdateEnabled)
{
#ifdef _WIN32
if (!update::TryUpdateGameConfig())
{
CSSHARP_CORE_ERROR("Failed to update game config.");
}
#else
CSSHARP_CORE_WARN("Auto-update is not currently supported on this platform.");
#endif
}
auto gamedata_path = std::string(utils::GamedataDirectory() + "/gamedata.json");
globals::gameConfig = new CGameConfig(gamedata_path);
char conf_error[255] = "";
if (!globals::gameConfig->Init(conf_error, sizeof(conf_error)))
{
CSSHARP_CORE_ERROR("Could not read \'{}\'. Error: {}", gamedata_path, conf_error);
return false;
}
globals::Initialize();
CSSHARP_CORE_INFO("Globals loaded.");
globals::mmPlugin = &gPlugin;
CALL_GLOBAL_LISTENER(OnAllInitialized());
on_activate_callback = globals::callbackManager.CreateCallback("OnMapStart");
on_metamod_all_plugins_loaded_callback = globals::callbackManager.CreateCallback("OnMetamodAllPluginsLoaded");
SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this, &CounterStrikeSharpMMPlugin::Hook_GameFrame, true);
SH_ADD_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService, this,
&CounterStrikeSharpMMPlugin::Hook_StartupServer, true);
SH_ADD_HOOK_MEMFUNC(IEngineServiceMgr, RegisterLoopMode, globals::engineServiceManager, this,
&CounterStrikeSharpMMPlugin::Hook_RegisterLoopMode, false);
SH_ADD_HOOK_MEMFUNC(IEngineServiceMgr, FindService, globals::engineServiceManager, this, &CounterStrikeSharpMMPlugin::Hook_FindService,
true);
auto pCGameEventManagerVTable = (IGameEventManager2*)modules::server->FindVirtualTable("CGameEventManager");
g_iLoadEventsFromFileId = SH_ADD_DVPHOOK(IGameEventManager2, LoadEventsFromFile, pCGameEventManagerVTable,
SH_MEMBER(this, &CounterStrikeSharpMMPlugin::Hook_LoadEventsFromFile), false);
if (!InitGameSystems())
{
CSSHARP_CORE_ERROR("Failed to initialize GameSystem!");
return false;
}
CSSHARP_CORE_INFO("Initialized GameSystem.");
if (!globals::dotnetManager.Initialize())
{
CSSHARP_CORE_ERROR("Failed to initialize .NET runtime");
}
CSSHARP_CORE_INFO("Hooks added.");
// Used by Metamod Console Commands
g_pCVar = globals::cvars;
ConVar_Register(FCVAR_RELEASE | FCVAR_CLIENT_CAN_EXECUTE | FCVAR_GAMEDLL);
return true;
}
void CounterStrikeSharpMMPlugin::Hook_StartupServer(const GameSessionConfiguration_t& config, ISource2WorldSession*, const char*)
{
globals::entitySystem = interfaces::pGameResourceServiceServer->GetGameEntitySystem();
globals::entitySystem->AddListenerEntity(&globals::entityManager.entityListener);
globals::timerSystem.OnStartupServer();
on_activate_callback->ScriptContext().Reset();
on_activate_callback->ScriptContext().Push(globals::getGlobalVars()->mapname.ToCStr());
on_activate_callback->Execute();
}
bool CounterStrikeSharpMMPlugin::Unload(char* error, size_t maxlen)
{
SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this, &CounterStrikeSharpMMPlugin::Hook_GameFrame, true);
SH_REMOVE_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService, this,
&CounterStrikeSharpMMPlugin::Hook_StartupServer, true);
SH_REMOVE_HOOK_ID(g_iLoadEventsFromFileId);
globals::callbackManager.ReleaseCallback(on_activate_callback);
globals::callbackManager.ReleaseCallback(on_metamod_all_plugins_loaded_callback);
return true;
}
void CounterStrikeSharpMMPlugin::AllPluginsLoaded()
{
/* This is where we'd do stuff that relies on the mod or other plugins
* being initialized (for example, cvars added and events registered).
*/
on_metamod_all_plugins_loaded_callback->ScriptContext().Reset();
on_metamod_all_plugins_loaded_callback->Execute();
if (globals::entityManager.Func_OnTakeDamage)
{
globals::entityManager.Func_OnTakeDamage->AddHook(&OnTakeDamageProxy);
}
}
void CounterStrikeSharpMMPlugin::Hook_GameFrame(bool simulating, bool bFirstTick, bool bLastTick)
{
/**
* simulating:
* ***********
* true | game is ticking
* false | game is not ticking
*/
// VPROF_BUDGET("CS#::Hook_GameFrame", "CS# On Frame");
globals::timerSystem.OnGameFrame(simulating);
auto callbacks = globals::tickScheduler.getCallbacks(globals::getGlobalVars()->tickcount);
if (callbacks.size() > 0)
{
CSSHARP_CORE_TRACE("Executing frame specific tasks of size: {0} on tick number {1}", callbacks.size(),
globals::getGlobalVars()->tickcount);
for (auto& callback : callbacks)
{
callback();
}
}
}
// Potentially might not work
void CounterStrikeSharpMMPlugin::OnLevelInit(
char const* pMapName, char const* pMapEntities, char const* pOldLevel, char const* pLandmarkName, bool loadGame, bool background)
{
CSSHARP_CORE_TRACE("name={0},mapname={1}", "LevelInit", pMapName);
}
void CounterStrikeSharpMMPlugin::Hook_RegisterLoopMode(const char* pszLoopModeName,
ILoopModeFactory* pLoopModeFactory,
void** ppGlobalPointer)
{
if (strcmp(pszLoopModeName, "game") == 0)
{
if (!globals::gameLoopInitialized) globals::gameLoopInitialized = true;
CALL_GLOBAL_LISTENER(OnGameLoopInitialized());
}
}
IEngineService* CounterStrikeSharpMMPlugin::Hook_FindService(const char* serviceName)
{
IEngineService* pService = META_RESULT_ORIG_RET(IEngineService*);
return pService;
}
int CounterStrikeSharpMMPlugin::Hook_LoadEventsFromFile(const char* filename, bool bSearchAll)
{
ExecuteOnce(globals::gameEventManager = META_IFACEPTR(IGameEventManager2));
RETURN_META_VALUE(MRES_IGNORED, 0);
}
void CounterStrikeSharpMMPlugin::OnLevelShutdown() {}
bool CounterStrikeSharpMMPlugin::Pause(char* error, size_t maxlen) { return true; }
bool CounterStrikeSharpMMPlugin::Unpause(char* error, size_t maxlen) { return true; }
const char* CounterStrikeSharpMMPlugin::GetLicense() { return "GNU GPLv3"; }
const char* CounterStrikeSharpMMPlugin::GetVersion() { return VERSION_STRING; }
const char* CounterStrikeSharpMMPlugin::GetDate() { return BUILD_TIMESTAMP; }
const char* CounterStrikeSharpMMPlugin::GetLogTag() { return "CSSHARP"; }
const char* CounterStrikeSharpMMPlugin::GetAuthor() { return "Roflmuffin"; }
const char* CounterStrikeSharpMMPlugin::GetDescription() { return "Counter Strike .NET Scripting Runtime"; }
const char* CounterStrikeSharpMMPlugin::GetName() { return "CounterStrikeSharp"; }
const char* CounterStrikeSharpMMPlugin::GetURL() { return "https://github.com/roflmuffin/CounterStrikeSharp"; }
} // namespace counterstrikesharp