1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2008 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 "vsp_listener.h"
22 #include "iplayerinfo.h"
23 #include <filesystem.h>
25 using namespace SourceMM;
28 * @brief Implementation of main SourceMM GameDLL functionality
33 DLL_IMPORT ICommandLine *CommandLine();
35 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
36 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
37 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
38 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
40 void LevelShutdown_handler();
41 bool LevelInit_handler(char const *pMapName,
42 char const *pMapEntities,
43 char const *pOldLevel,
44 char const *pLandmarkName,
47 bool GameInit_handler();
48 int LoadPlugins(const char *filepath, const char *vdfpath);
49 int LoadVDFPluginsFromDir(const char *dir, int &skipped);
50 bool KVLoadFromFile(KeyValues *kv,
51 IBaseFileSystem *filesystem,
52 const char *resourceName,
53 const char *pathID = NULL);
55 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
57 SourceHook::CSourceHookImpl g_SourceHook;
58 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
59 SourceHook::String g_ModPath;
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 = &g_VspListener;
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);
129 CreateInterface(const char *iface, int *ret)
133 if (!g_bIsBridgedAsVsp && strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
135 if (g_VspListener.IsLoaded())
142 assert(&g_VspListener == g_pRealVspCallbacks);
144 int vsp_version = atoi(&iface[22]);
145 if (vsp_version < 1 || vsp_version > 2)
152 g_vsp_version = vsp_version;
154 return g_pRealVspCallbacks;
158 *ret = (ptr != NULL) ? IFACE_OK : IFACE_FAILED;
163 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
165 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
167 if (!g_Engine.engine)
169 Error("Could not find IVEngineServer! Metamod cannot load.");
172 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
175 Error("Could not find ICvar! Metamod cannot load.");
179 g_Engine.loaded = true;
181 /* The Ship is the only game known at this time that uses the pre-Episode One engine */
182 g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
184 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
186 if (g_GameDll.pGameClients)
188 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
192 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
193 LogMessage("[META] Warning: Could not find IServerGameClients!");
194 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
197 if (!g_SmmAPI.CacheCmds())
199 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
200 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
203 if (!g_SmmAPI.CacheUserMessages())
205 /* Don't know of a mod that has stripped out user messages completely,
206 * but perhaps should do something different here?
208 LogMessage("[META] Warning: Failed to get list of user messages.");
209 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
212 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
215 LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
218 if (!g_SMConVarAccessor.InitConCommandBaseList())
220 /* This is very unlikely considering it's old engine */
221 LogMessage("[META] Warning: Failed to find ConCommandBase list!");
222 LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
225 if (!bWaitForGameInit)
227 DoInitialPluginLoads();
228 bInFirstLevel = true;
234 void LoadAsGameDLL(const gamedll_bridge_info *info)
236 g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
237 g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
238 g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
239 g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
240 g_GameDll.loaded = true;
241 g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
242 g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
243 g_GameDllVersion = info->dllVersion;
247 StartupMetamod(g_Engine.engineFactory, false);
250 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
252 g_Engine.engineFactory = ifaceFactory;
253 g_Engine.fileSystemFactory = ifaceFactory;
254 g_Engine.physicsFactory = ifaceFactory;
256 IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
257 if (playerInfoManager == NULL)
259 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
263 g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
265 /* Now find the server */
266 g_GameDll.factory = serverFactory;
268 char gamedll_iface[] = "ServerGameDLL000";
269 for (unsigned int i = 3; i <= 50; i++)
271 gamedll_iface[15] = '0' + i;
272 g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
273 if (g_GameDll.pGameDLL != NULL)
275 g_GameDllVersion = i;
280 if (g_GameDll.pGameDLL == NULL)
282 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
286 char gameclients_iface[] = "ServerGameClients000";
287 for (unsigned int i = 3; i <= 4; i++)
289 gameclients_iface[19] = '0' + i;
290 g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
291 if (g_GameDll.pGameClients != NULL)
299 if (!StartupMetamod(ifaceFactory, true))
307 bool GameInit_handler()
310 RETURN_META_VALUE(MRES_IGNORED, true);
312 if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
313 g_SmmAPI.LoadAsVSP();
315 if (g_bIsBridgedAsVsp)
317 DoInitialPluginLoads();
318 g_PluginMngr.SetAllLoaded();
323 RETURN_META_VALUE(MRES_IGNORED, true);
326 void UnloadMetamod(bool shutting_down)
329 g_PluginMngr.UnloadAll();
333 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
334 g_SMConVarAccessor.MarkCommandsAsGameDLL();
335 g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
338 g_SourceHook.CompleteShutdown();
341 bool LoadFromVDF(const char *file, bool &skipped)
344 bool already, kvfileLoaded;
346 const char *plugin_file, *alias;
347 char full_path[256], error[256];
349 pValues = new KeyValues("Metamod Plugin");
351 if (g_Engine.original)
353 /* The Ship must use a special version of this function */
354 kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
358 kvfileLoaded = pValues->LoadFromFile(baseFs, file);
363 pValues->deleteThis();
368 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
370 pValues->deleteThis();
375 if ((alias = pValues->GetString("alias", NULL)) != NULL)
377 g_PluginMngr.SetAlias(alias, plugin_file);
380 /* Attempt to find a file extension */
381 if (UTIL_GetExtension(plugin_file) == NULL)
383 g_SmmAPI.PathFormat(full_path,
388 #if defined WIN32 || defined _WIN32
397 g_SmmAPI.PathFormat(full_path,
404 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
406 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
408 LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
412 pValues->deleteThis();
416 int LoadVDFPluginsFromDir(const char *dir, int &skipped)
429 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
430 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
432 DWORD dw = GetLastError();
433 if (dw == ERROR_FILE_NOT_FOUND)
436 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
439 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
443 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
449 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
450 success = LoadFromVDF(path, skip);
455 } while (FindNextFile(hFind, &fd));
463 if ((pDir = opendir(dir)) == NULL)
465 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
469 while ((pEnt = readdir(pDir)) != NULL)
471 if (strcmp(pEnt->d_name, ".") == 0
472 || strcmp(pEnt->d_name, "..") == 0)
476 extidx = strlen(pEnt->d_name) - 4;
477 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
481 g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
482 success = LoadFromVDF(path, skip);
495 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
499 Assert(_heapchk() == _HEAPOK);
502 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
506 // load file into a null-terminated buffer
507 int fileSize = filesystem->Size(f);
508 char *buffer = (char *)MemAllocScratch(fileSize + 1);
512 filesystem->Read(buffer, fileSize, f); // read into local buffer
514 buffer[fileSize] = 0; // null terminate file as EOF
516 filesystem->Close( f ); // close file after reading
518 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
525 int LoadPluginsFromFile(const char *filepath, int &skipped)
534 fp = fopen(filepath, "rt");
540 char buffer[255], error[255], full_path[PATH_SIZE];
541 const char *ptr, *ext, *file;
543 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
545 UTIL_TrimLeft(buffer);
546 UTIL_TrimRight(buffer);
548 length = strlen(buffer);
554 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
560 if (buffer[0] == '"')
583 while (*cptr && isspace(*cptr))
588 UTIL_TrimRight(cptr);
589 if (*cptr && isalpha(*cptr))
591 g_PluginMngr.SetAlias(buffer, cptr);
603 /* First find if it's an absolute path or not... */
604 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
606 /* If we're in an absolute path, ignore our normal heuristics */
607 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
608 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
610 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
626 /* Attempt to find a file extension */
627 ptr = UTIL_GetExtension(file);
628 /* Add an extension if there's none there */
631 #if defined WIN32 || defined _WIN32
641 /* Format the new path */
642 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
643 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
644 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
646 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
666 int LoadPlugins(const char *filepath, const char *vdfpath)
668 int total, skipped, fskipped, vskipped;
671 total = LoadPluginsFromFile(filepath, fskipped);
672 total += LoadVDFPluginsFromDir(vdfpath, vskipped);
673 skipped = fskipped + vskipped;
675 if (total == 0 || total > 1)
679 LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
681 LogMessage("[META] Loaded %d plugin%s.", total, s);
686 void LogMessage(const char *msg, ...)
689 static char buffer[2048];
692 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
695 buffer[len++] = '\n';
698 if (!g_Engine.engine)
700 fprintf(stdout, "%s", buffer);
702 g_Engine.engine->LogPrint(buffer);
706 void LevelShutdown_handler(void)
710 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
712 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
713 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
714 LoadPlugins(filepath, vdfpath);
718 bInFirstLevel = false;
721 g_bLevelChanged = true;
723 ITER_EVENT(OnLevelShutdown, ());
725 RETURN_META(MRES_IGNORED);
728 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
730 if (!g_SmmAPI.CmdCacheSuccessful())
732 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
733 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
736 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
738 RETURN_META_VALUE(MRES_IGNORED, false);
741 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
742 void * operator new(size_t size) {
743 return(calloc(1, size));
746 void * operator new[](size_t size) {
747 return(calloc(1, size));
750 void operator delete(void * ptr) {
755 void operator delete[](void * ptr) {