Initial import of core-legacy as a gameinfo provider.
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, DLLShutdown, SH_NOATTRIB, false);
36 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
37 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
38 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
39 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
41 void DLLShutdown_handler();
42 void LevelShutdown_handler();
43 bool LevelInit_handler(char const *pMapName,
44 char const *pMapEntities,
45 char const *pOldLevel,
46 char const *pLandmarkName,
49 bool GameInit_handler();
50 void LookForVDFs(const char *dir);
51 bool KVLoadFromFile(KeyValues *kv,
52 IBaseFileSystem *filesystem,
53 const char *resourceName,
54 const char *pathID = NULL);
56 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
58 SourceHook::CSourceHookImpl g_SourceHook;
59 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
60 SourceHook::String g_ModPath;
61 PluginId g_PLID = Pl_Console; /* Technically, SourceMM is the "Console" plugin... :p */
62 static bool bInFirstLevel = true;
63 bool g_bGameInit = false;
64 SourceHook::CallClass<IServerGameDLL> *g_GameDllPatch;
65 SourceHook::CallClass<ICvar> *g_CvarPatch;
66 int g_GameDllVersion = 0;
67 static const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
68 static const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
69 static const char GAMEINFO_PATH[] = "|gameinfo_path|";
70 IFileSystem *baseFs = NULL;
71 bool g_bLevelChanged = false;
72 IServerPluginCallbacks *g_pRealVspCallbacks = &g_VspListener;
74 #define ITER_EVENT(evn, args) \
75 CPluginManager::CPlugin *pl; \
76 SourceHook::List<CPluginEventHandler>::iterator event; \
77 IMetamodListener *api; \
78 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
80 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
81 api = (*event).event; \
86 ///////////////////////////////////
87 // Main code for HL2 Interaction //
88 ///////////////////////////////////
90 /* Initialize everything here */
93 /* Like Metamod, reload plugins at the end of the map.
94 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
95 * if the server is shut down (silly, but rare case).
99 char smm_path[PATH_SIZE];
100 const char *game_dir = CommandLine()->ParmValue("-game", "hl2");
101 abspath(smm_path, game_dir);
102 g_ModPath.assign(smm_path);
104 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
105 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
106 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
107 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
110 void DoInitialPluginLoads()
112 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
113 const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
117 pluginFile = GetPluginsFile();
121 mmBaseDir = GetMetamodBaseDir();
126 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), pluginFile);
127 LoadPluginsFromFile(full_path);
128 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), mmBaseDir);
129 LookForVDFs(full_path);
132 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
134 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
136 if (!g_Engine.engine)
138 Error("Could not find IVEngineServer! Metamod cannot load.");
141 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
144 Error("Could not find ICvar! Metamod cannot load.");
148 g_Engine.loaded = true;
150 /* The Ship is the only game known at this time that uses the pre-Episode One engine */
151 g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
153 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
155 g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
156 g_CvarPatch = SH_GET_CALLCLASS(g_Engine.icvar);
158 if (g_GameDll.pGameClients)
160 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
164 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
165 LogMessage("[META] Warning: Could not find IServerGameClients!");
166 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
169 if (!g_SmmAPI.CacheCmds())
171 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
172 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
175 if (!g_SmmAPI.CacheUserMessages())
177 /* Don't know of a mod that has stripped out user messages completely,
178 * but perhaps should do something different here?
180 LogMessage("[META] Warning: Failed to get list of user messages.");
181 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
184 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
187 LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
190 if (!g_SMConVarAccessor.InitConCommandBaseList())
192 /* This is very unlikely considering it's old engine */
193 LogMessage("[META] Warning: Failed to find ConCommandBase list!");
194 LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
197 if (!bWaitForGameInit)
199 DoInitialPluginLoads();
200 bInFirstLevel = true;
206 void LoadAsGameDLL(const gamedll_bridge_info *info)
208 g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
209 g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
210 g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
211 g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
212 g_GameDll.loaded = true;
213 g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
214 g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
215 g_GameDllVersion = info->dllVersion;
219 StartupMetamod(g_Engine.engineFactory, false);
222 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
224 g_Engine.engineFactory = ifaceFactory;
225 g_Engine.fileSystemFactory = ifaceFactory;
226 g_Engine.physicsFactory = ifaceFactory;
228 IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
229 if (playerInfoManager == NULL)
231 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
235 g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
237 /* Now find the server */
238 g_GameDll.factory = serverFactory;
240 char gamedll_iface[] = "ServerGameDLL000";
241 for (unsigned int i = 3; i <= 50; i++)
243 gamedll_iface[15] = '0' + i;
244 g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
245 if (g_GameDll.pGameDLL != NULL)
247 g_GameDllVersion = i;
252 if (g_GameDll.pGameDLL == NULL)
254 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
258 char gameclients_iface[] = "ServerGameClients000";
259 for (unsigned int i = 3; i <= 4; i++)
261 gameclients_iface[19] = '0' + i;
262 g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
263 if (g_GameDll.pGameClients != NULL)
271 if (!StartupMetamod(ifaceFactory, true))
276 g_PluginMngr.SetAllLoaded();
281 bool GameInit_handler()
284 RETURN_META_VALUE(MRES_IGNORED, true);
286 if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
287 g_SmmAPI.LoadAsVSP();
289 if (g_bIsBridgedAsVsp)
290 DoInitialPluginLoads();
294 RETURN_META_VALUE(MRES_IGNORED, true);
297 void UnloadMetamod(bool shutting_down)
300 g_PluginMngr.UnloadAll();
304 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
305 g_SMConVarAccessor.MarkCommandsAsGameDLL();
306 g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
308 SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
311 SH_RELEASE_CALLCLASS(g_GameDllPatch);
312 SH_RELEASE_CALLCLASS(g_CvarPatch);
313 g_GameDllPatch = NULL;
316 g_SourceHook.CompleteShutdown();
319 void DLLShutdown_handler()
322 RETURN_META(MRES_SUPERCEDE);
325 void LoadFromVDF(const char *file)
328 bool already, kvfileLoaded;
330 const char *plugin_file, *alias;
331 char full_path[256], error[256];
333 pValues = new KeyValues("Metamod Plugin");
335 if (g_Engine.original)
337 /* The Ship must use a special version of this function */
338 kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
342 kvfileLoaded = pValues->LoadFromFile(baseFs, file);
347 pValues->deleteThis();
351 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
353 pValues->deleteThis();
357 if ((alias = pValues->GetString("alias", NULL)) != NULL)
359 g_PluginMngr.SetAlias(alias, plugin_file);
362 /* Attempt to find a file extension */
363 if (UTIL_GetExtension(plugin_file) == NULL)
365 g_SmmAPI.PathFormat(full_path,
370 #if defined WIN32 || defined _WIN32
379 g_SmmAPI.PathFormat(full_path,
386 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
387 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
389 LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
392 pValues->deleteThis();
395 void LookForVDFs(const char *dir)
404 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
405 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
407 DWORD dw = GetLastError();
408 if (dw == ERROR_FILE_NOT_FOUND)
411 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
414 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
418 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
424 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
426 } while (FindNextFile(hFind, &fd));
434 if ((pDir = opendir(dir)) == NULL)
436 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
440 while ((pEnt = readdir(pDir)) != NULL)
442 if (strcmp(pEnt->d_name, ".") == 0
443 || strcmp(pEnt->d_name, "..") == 0)
447 extidx = strlen(pEnt->d_name) - 4;
448 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
452 g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
460 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
464 Assert(_heapchk() == _HEAPOK);
467 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
471 // load file into a null-terminated buffer
472 int fileSize = filesystem->Size(f);
473 char *buffer = (char *)MemAllocScratch(fileSize + 1);
477 filesystem->Read(buffer, fileSize, f); // read into local buffer
479 buffer[fileSize] = 0; // null terminate file as EOF
481 filesystem->Close( f ); // close file after reading
483 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
490 int LoadPluginsFromFile(const char *_file)
493 int total = 0, skipped=0;
497 fp = fopen(_file, "rt");
500 LogMessage("[META] Could not open plugins file %s\n", _file);
504 char buffer[255], error[255], full_path[255];
505 const char *ptr, *ext, *file;
507 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
509 UTIL_TrimLeft(buffer);
510 UTIL_TrimRight(buffer);
512 length = strlen(buffer);
518 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
524 if (buffer[0] == '"')
547 while (*cptr && isspace(*cptr))
552 UTIL_TrimRight(cptr);
553 if (*cptr && isalpha(*cptr))
555 g_PluginMngr.SetAlias(buffer, cptr);
567 /* First find if it's an absolute path or not... */
568 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
570 /* If we're in an absolute path, ignore our normal heuristics */
571 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
572 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
574 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
590 /* Attempt to find a file extension */
591 ptr = UTIL_GetExtension(file);
592 /* Add an extension if there's none there */
595 #if defined WIN32 || defined _WIN32
605 /* Format the new path */
606 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
607 id = g_PluginMngr.Load(full_path, 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);
629 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
633 LogMessage("[META] Loaded %d plugins from file.", total);
639 void LogMessage(const char *msg, ...)
642 static char buffer[2048];
645 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
648 buffer[len++] = '\n';
651 if (!g_Engine.engine)
653 fprintf(stdout, "%s", buffer);
655 g_Engine.engine->LogPrint(buffer);
659 void LevelShutdown_handler(void)
665 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
666 LoadPluginsFromFile(full_path);
668 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
669 LookForVDFs(full_path);
673 bInFirstLevel = false;
676 g_bLevelChanged = true;
678 ITER_EVENT(OnLevelShutdown, ());
680 RETURN_META(MRES_IGNORED);
683 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
685 if (!g_SmmAPI.CmdCacheSuccessful())
687 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
688 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
691 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
693 RETURN_META_VALUE(MRES_IGNORED, false);
696 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
697 void * operator new(size_t size) {
698 return(calloc(1, size));
701 void * operator new[](size_t size) {
702 return(calloc(1, size));
705 void operator delete(void * ptr) {
710 void operator delete[](void * ptr) {