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;
71 #define ITER_EVENT(evn, args) \
72 CPluginManager::CPlugin *pl; \
73 SourceHook::List<CPluginEventHandler>::iterator event; \
74 IMetamodListener *api; \
75 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
77 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
78 api = (*event).event; \
83 ///////////////////////////////////
84 // Main code for HL2 Interaction //
85 ///////////////////////////////////
87 /* Initialize everything here */
90 /* Like Metamod, reload plugins at the end of the map.
91 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
92 * if the server is shut down (silly, but rare case).
96 char smm_path[PATH_SIZE];
97 const char *game_dir = CommandLine()->ParmValue("-game", "hl2");
98 abspath(smm_path, game_dir);
99 g_ModPath.assign(smm_path);
101 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
102 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
103 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
106 void DoInitialPluginLoads()
108 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
109 const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
113 pluginFile = GetPluginsFile();
117 mmBaseDir = GetMetamodBaseDir();
120 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
122 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), pluginFile);
123 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), mmBaseDir);
124 LoadPlugins(filepath, vdfpath);
128 CreateInterface(const char *iface, int *ret)
132 if (!g_bIsBridgedAsVsp && strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
134 if (g_VspListener.IsLoaded())
141 assert(&g_VspListener == g_pRealVspCallbacks);
143 int vsp_version = atoi(&iface[22]);
144 if (vsp_version < 1 || vsp_version > 2)
151 return g_pRealVspCallbacks;
155 *ret = (ptr != NULL) ? IFACE_OK : IFACE_FAILED;
160 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
162 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
164 if (!g_Engine.engine)
166 Error("Could not find IVEngineServer! Metamod cannot load.");
169 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
172 Error("Could not find ICvar! Metamod cannot load.");
176 g_Engine.loaded = true;
178 /* The Ship is the only game known at this time that uses the pre-Episode One engine */
179 g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
181 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
183 if (g_GameDll.pGameClients)
185 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
189 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
190 LogMessage("[META] Warning: Could not find IServerGameClients!");
191 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
194 if (!g_SmmAPI.CacheCmds())
196 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
197 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
200 if (!g_SmmAPI.CacheUserMessages())
202 /* Don't know of a mod that has stripped out user messages completely,
203 * but perhaps should do something different here?
205 LogMessage("[META] Warning: Failed to get list of user messages.");
206 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
209 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
212 LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
215 if (!g_SMConVarAccessor.InitConCommandBaseList())
217 /* This is very unlikely considering it's old engine */
218 LogMessage("[META] Warning: Failed to find ConCommandBase list!");
219 LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
222 if (!bWaitForGameInit)
224 DoInitialPluginLoads();
225 bInFirstLevel = true;
231 void LoadAsGameDLL(const gamedll_bridge_info *info)
233 g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
234 g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
235 g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
236 g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
237 g_GameDll.loaded = true;
238 g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
239 g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
240 g_GameDllVersion = info->dllVersion;
244 StartupMetamod(g_Engine.engineFactory, false);
247 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
249 g_Engine.engineFactory = ifaceFactory;
250 g_Engine.fileSystemFactory = ifaceFactory;
251 g_Engine.physicsFactory = ifaceFactory;
253 IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
254 if (playerInfoManager == NULL)
256 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
260 g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
262 /* Now find the server */
263 g_GameDll.factory = serverFactory;
265 char gamedll_iface[] = "ServerGameDLL000";
266 for (unsigned int i = 3; i <= 50; i++)
268 gamedll_iface[15] = '0' + i;
269 g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
270 if (g_GameDll.pGameDLL != NULL)
272 g_GameDllVersion = i;
277 if (g_GameDll.pGameDLL == NULL)
279 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
283 char gameclients_iface[] = "ServerGameClients000";
284 for (unsigned int i = 3; i <= 4; i++)
286 gameclients_iface[19] = '0' + i;
287 g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
288 if (g_GameDll.pGameClients != NULL)
296 if (!StartupMetamod(ifaceFactory, true))
304 bool GameInit_handler()
307 RETURN_META_VALUE(MRES_IGNORED, true);
309 if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
310 g_SmmAPI.LoadAsVSP();
312 if (g_bIsBridgedAsVsp)
314 DoInitialPluginLoads();
315 g_PluginMngr.SetAllLoaded();
320 RETURN_META_VALUE(MRES_IGNORED, true);
323 void UnloadMetamod(bool shutting_down)
326 g_PluginMngr.UnloadAll();
330 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
331 g_SMConVarAccessor.MarkCommandsAsGameDLL();
332 g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
335 g_SourceHook.CompleteShutdown();
338 bool LoadFromVDF(const char *file, bool &skipped)
341 bool already, kvfileLoaded;
343 const char *plugin_file, *alias;
344 char full_path[256], error[256];
346 pValues = new KeyValues("Metamod Plugin");
348 if (g_Engine.original)
350 /* The Ship must use a special version of this function */
351 kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
355 kvfileLoaded = pValues->LoadFromFile(baseFs, file);
360 pValues->deleteThis();
365 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
367 pValues->deleteThis();
372 if ((alias = pValues->GetString("alias", NULL)) != NULL)
374 g_PluginMngr.SetAlias(alias, plugin_file);
377 /* Attempt to find a file extension */
378 if (UTIL_GetExtension(plugin_file) == NULL)
380 g_SmmAPI.PathFormat(full_path,
385 #if defined WIN32 || defined _WIN32
394 g_SmmAPI.PathFormat(full_path,
401 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
403 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
405 LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
409 pValues->deleteThis();
413 int LoadVDFPluginsFromDir(const char *dir, int &skipped)
426 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
427 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
429 DWORD dw = GetLastError();
430 if (dw == ERROR_FILE_NOT_FOUND)
433 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
436 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
440 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
446 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
447 success = LoadFromVDF(path, skip);
452 } while (FindNextFile(hFind, &fd));
460 if ((pDir = opendir(dir)) == NULL)
462 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
466 while ((pEnt = readdir(pDir)) != NULL)
468 if (strcmp(pEnt->d_name, ".") == 0
469 || strcmp(pEnt->d_name, "..") == 0)
473 extidx = strlen(pEnt->d_name) - 4;
474 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
478 g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
479 success = LoadFromVDF(path, skip);
492 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
496 Assert(_heapchk() == _HEAPOK);
499 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
503 // load file into a null-terminated buffer
504 int fileSize = filesystem->Size(f);
505 char *buffer = (char *)MemAllocScratch(fileSize + 1);
509 filesystem->Read(buffer, fileSize, f); // read into local buffer
511 buffer[fileSize] = 0; // null terminate file as EOF
513 filesystem->Close( f ); // close file after reading
515 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
522 int LoadPluginsFromFile(const char *filepath, int &skipped)
531 fp = fopen(filepath, "rt");
537 char buffer[255], error[255], full_path[PATH_SIZE];
538 const char *ptr, *ext, *file;
540 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
542 UTIL_TrimLeft(buffer);
543 UTIL_TrimRight(buffer);
545 length = strlen(buffer);
551 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
557 if (buffer[0] == '"')
580 while (*cptr && isspace(*cptr))
585 UTIL_TrimRight(cptr);
586 if (*cptr && isalpha(*cptr))
588 g_PluginMngr.SetAlias(buffer, cptr);
600 /* First find if it's an absolute path or not... */
601 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
603 /* If we're in an absolute path, ignore our normal heuristics */
604 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
605 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
607 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
623 /* Attempt to find a file extension */
624 ptr = UTIL_GetExtension(file);
625 /* Add an extension if there's none there */
628 #if defined WIN32 || defined _WIN32
638 /* Format the new path */
639 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
640 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
641 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
643 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
663 int LoadPlugins(const char *filepath, const char *vdfpath)
665 int total, skipped, fskipped, vskipped;
668 total = LoadPluginsFromFile(filepath, fskipped);
669 total += LoadVDFPluginsFromDir(vdfpath, vskipped);
670 skipped = fskipped + vskipped;
672 if (total == 0 || total > 1)
676 LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
678 LogMessage("[META] Loaded %d plugin%s.", total, s);
683 void LogMessage(const char *msg, ...)
686 static char buffer[2048];
689 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
692 buffer[len++] = '\n';
695 if (!g_Engine.engine)
697 fprintf(stdout, "%s", buffer);
699 g_Engine.engine->LogPrint(buffer);
703 void LevelShutdown_handler(void)
707 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
709 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
710 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
711 LoadPlugins(filepath, vdfpath);
715 bInFirstLevel = false;
718 g_bLevelChanged = true;
720 ITER_EVENT(OnLevelShutdown, ());
722 RETURN_META(MRES_IGNORED);
725 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
727 if (!g_SmmAPI.CmdCacheSuccessful())
729 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
730 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
733 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
735 RETURN_META_VALUE(MRES_IGNORED, false);
738 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
739 void * operator new(size_t size) {
740 return(calloc(1, size));
743 void * operator new[](size_t size) {
744 return(calloc(1, size));
747 void operator delete(void * ptr) {
752 void operator delete[](void * ptr) {