1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2009 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): David "BAILOPAN" Anderson
8 * Contributor(s): Scott "Damaged Soul" Ehlert
9 * : Pavol "PM OnoTo" Marko
10 * ============================
13 #include <interface.h>
15 #include <tier0/icommandline.h>
17 #include "concommands.h"
21 #include "iplayerinfo.h"
22 #include <filesystem.h>
24 using namespace SourceMM;
27 * @brief Implementation of main SourceMM GameDLL functionality
32 DLL_IMPORT ICommandLine *CommandLine();
34 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
35 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
36 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
37 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
39 void LevelShutdown_handler();
40 bool LevelInit_handler(char const *pMapName,
41 char const *pMapEntities,
42 char const *pOldLevel,
43 char const *pLandmarkName,
46 bool GameInit_handler();
47 int LoadPlugins(const char *filepath, const char *vdfpath);
48 int LoadVDFPluginsFromDir(const char *dir, int &skipped);
49 bool KVLoadFromFile(KeyValues *kv,
50 IBaseFileSystem *filesystem,
51 const char *resourceName,
52 const char *pathID = NULL);
54 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
56 SourceHook::CSourceHookImpl g_SourceHook;
57 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
58 SourceHook::String g_ModPath;
59 SourceHook::String g_MetamodPath;
60 PluginId g_PLID = Pl_Console; /* Technically, SourceMM is the "Console" plugin... :p */
61 static bool bInFirstLevel = true;
62 bool g_bGameInit = false;
63 int g_GameDllVersion = 0;
64 static const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
65 static const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
66 static const char GAMEINFO_PATH[] = "|gameinfo_path|";
67 IFileSystem *baseFs = NULL;
68 bool g_bLevelChanged = false;
69 IServerPluginCallbacks *g_pRealVspCallbacks = NULL;
70 unsigned int g_vsp_version = 0;
72 #define ITER_EVENT(evn, args) \
73 CPluginManager::CPlugin *pl; \
74 SourceHook::List<CPluginEventHandler>::iterator event; \
75 IMetamodListener *api; \
76 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
78 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
79 api = (*event).event; \
84 ///////////////////////////////////
85 // Main code for HL2 Interaction //
86 ///////////////////////////////////
88 /* Initialize everything here */
91 /* Like Metamod, reload plugins at the end of the map.
92 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
93 * if the server is shut down (silly, but rare case).
97 char smm_path[PATH_SIZE];
98 const char *game_dir = CommandLine()->ParmValue("-game", "hl2");
99 abspath(smm_path, game_dir);
100 g_ModPath.assign(smm_path);
102 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
103 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
104 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
107 void DoInitialPluginLoads()
109 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
110 const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
114 pluginFile = GetPluginsFile();
118 mmBaseDir = GetMetamodBaseDir();
121 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
123 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), pluginFile);
124 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), mmBaseDir);
125 LoadPlugins(filepath, vdfpath);
128 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
130 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
132 if (!g_Engine.engine)
134 Error("Could not find IVEngineServer! Metamod cannot load.");
137 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
140 Error("Could not find ICvar! Metamod cannot load.");
144 g_Engine.loaded = true;
146 /* The Ship is the only game known at this time that uses the pre-Episode One engine */
147 g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
149 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
151 if (g_GameDll.pGameClients)
153 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
157 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
158 LogMessage("[META] Warning: Could not find IServerGameClients!");
159 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
162 if (!g_SmmAPI.CacheCmds())
164 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
165 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
168 g_SmmAPI.CacheUserMessages();
170 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
173 LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
176 if (!g_SMConVarAccessor.InitConCommandBaseList())
178 /* This is very unlikely considering it's old engine */
179 LogMessage("[META] Warning: Failed to find ConCommandBase list!");
180 LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
183 if (!bWaitForGameInit)
185 DoInitialPluginLoads();
186 bInFirstLevel = true;
192 void LoadAsGameDLL(const gamedll_bridge_info *info)
194 g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
195 g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
196 g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
197 g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
198 g_GameDll.loaded = true;
199 g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
200 g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
201 g_GameDllVersion = info->dllVersion;
202 g_MetamodPath.assign(info->vsp_listener_path);
206 StartupMetamod(g_Engine.engineFactory, false);
209 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
211 g_Engine.engineFactory = ifaceFactory;
212 g_Engine.fileSystemFactory = ifaceFactory;
213 g_Engine.physicsFactory = ifaceFactory;
215 IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
216 if (playerInfoManager == NULL)
218 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
222 g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
224 /* Now find the server */
225 g_GameDll.factory = serverFactory;
227 char gamedll_iface[] = "ServerGameDLL000";
228 for (unsigned int i = 3; i <= 50; i++)
230 gamedll_iface[15] = '0' + i;
231 g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
232 if (g_GameDll.pGameDLL != NULL)
234 g_GameDllVersion = i;
239 if (g_GameDll.pGameDLL == NULL)
241 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
245 char gameclients_iface[] = "ServerGameClients000";
246 for (unsigned int i = 3; i <= 4; i++)
248 gameclients_iface[19] = '0' + i;
249 g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
250 if (g_GameDll.pGameClients != NULL)
258 if (!StartupMetamod(ifaceFactory, true))
266 bool GameInit_handler()
269 RETURN_META_VALUE(MRES_IGNORED, true);
271 if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
272 g_SmmAPI.LoadAsVSP();
274 if (g_bIsBridgedAsVsp)
276 DoInitialPluginLoads();
277 g_PluginMngr.SetAllLoaded();
282 RETURN_META_VALUE(MRES_IGNORED, true);
285 void UnloadMetamod(bool shutting_down)
288 g_PluginMngr.UnloadAll();
292 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
293 g_SMConVarAccessor.MarkCommandsAsGameDLL();
294 g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
297 g_SourceHook.CompleteShutdown();
300 bool LoadFromVDF(const char *file, bool &skipped)
303 bool already, kvfileLoaded;
305 const char *plugin_file, *alias;
306 char full_path[256], error[256];
308 pValues = new KeyValues("Metamod Plugin");
310 if (g_Engine.original)
312 /* The Ship must use a special version of this function */
313 kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
317 kvfileLoaded = pValues->LoadFromFile(baseFs, file);
322 pValues->deleteThis();
327 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
329 pValues->deleteThis();
334 if ((alias = pValues->GetString("alias", NULL)) != NULL)
336 g_PluginMngr.SetAlias(alias, plugin_file);
339 /* Attempt to find a file extension */
340 if (UTIL_GetExtension(plugin_file) == NULL)
342 g_SmmAPI.PathFormat(full_path,
347 #if defined WIN32 || defined _WIN32
356 g_SmmAPI.PathFormat(full_path,
363 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
365 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
367 LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
371 pValues->deleteThis();
375 int LoadVDFPluginsFromDir(const char *dir, int &skipped)
388 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
389 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
391 DWORD dw = GetLastError();
392 if (dw == ERROR_FILE_NOT_FOUND)
395 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
398 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
402 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
408 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
409 success = LoadFromVDF(path, skip);
414 } while (FindNextFile(hFind, &fd));
422 if ((pDir = opendir(dir)) == NULL)
424 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
428 while ((pEnt = readdir(pDir)) != NULL)
430 if (strcmp(pEnt->d_name, ".") == 0
431 || strcmp(pEnt->d_name, "..") == 0)
435 extidx = strlen(pEnt->d_name) - 4;
436 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
440 g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
441 success = LoadFromVDF(path, skip);
454 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
458 Assert(_heapchk() == _HEAPOK);
461 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
465 // load file into a null-terminated buffer
466 int fileSize = filesystem->Size(f);
467 char *buffer = (char *)MemAllocScratch(fileSize + 1);
471 filesystem->Read(buffer, fileSize, f); // read into local buffer
473 buffer[fileSize] = 0; // null terminate file as EOF
475 filesystem->Close( f ); // close file after reading
477 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
484 int LoadPluginsFromFile(const char *filepath, int &skipped)
493 fp = fopen(filepath, "rt");
499 char buffer[255], error[255], full_path[PATH_SIZE];
500 const char *ptr, *ext, *file;
502 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
504 UTIL_TrimLeft(buffer);
505 UTIL_TrimRight(buffer);
507 length = strlen(buffer);
513 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
519 if (buffer[0] == '"')
542 while (*cptr && isspace(*cptr))
547 UTIL_TrimRight(cptr);
548 if (*cptr && isalpha(*cptr))
550 g_PluginMngr.SetAlias(buffer, cptr);
562 /* First find if it's an absolute path or not... */
563 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
565 /* If we're in an absolute path, ignore our normal heuristics */
566 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
567 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
569 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
585 /* Attempt to find a file extension */
586 ptr = UTIL_GetExtension(file);
587 /* Add an extension if there's none there */
590 #if defined WIN32 || defined _WIN32
600 /* Format the new path */
601 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
602 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
603 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
605 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
625 int LoadPlugins(const char *filepath, const char *vdfpath)
627 int total, skipped, fskipped, vskipped;
630 total = LoadPluginsFromFile(filepath, fskipped);
631 total += LoadVDFPluginsFromDir(vdfpath, vskipped);
632 skipped = fskipped + vskipped;
634 if (total == 0 || total > 1)
638 LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
640 LogMessage("[META] Loaded %d plugin%s.", total, s);
645 void LogMessage(const char *msg, ...)
648 static char buffer[2048];
651 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
654 buffer[len++] = '\n';
657 if (!g_Engine.engine)
659 fprintf(stdout, "%s", buffer);
661 g_Engine.engine->LogPrint(buffer);
665 void LevelShutdown_handler(void)
669 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
671 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
672 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
673 LoadPlugins(filepath, vdfpath);
677 bInFirstLevel = false;
680 g_bLevelChanged = true;
682 ITER_EVENT(OnLevelShutdown, ());
684 RETURN_META(MRES_IGNORED);
687 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
689 if (!g_SmmAPI.CmdCacheSuccessful())
691 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
692 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
695 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
697 RETURN_META_VALUE(MRES_IGNORED, false);
700 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
701 void * operator new(size_t size) {
702 return(calloc(1, size));
705 void * operator new[](size_t size) {
706 return(calloc(1, size));
709 void operator delete(void * ptr) {
714 void operator delete[](void * ptr) {