3 * ======================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC and authors.
7 * ======================================================
9 * This software is provided 'as-is', without any express or implied warranty.
10 * In no event will the authors be held liable for any damages arising from
11 * the use of this software.
13 * Permission is granted to anyone to use this software for any purpose,
14 * including commercial applications, and to alter it and redistribute it
15 * freely, subject to the following restrictions:
17 * 1. The origin of this software must not be misrepresented; you must not
18 * claim that you wrote the original software. If you use this software in a
19 * product, an acknowledgment in the product documentation would be
20 * appreciated but is not required.
21 * 2. Altered source versions must be plainly marked as such, and must not be
22 * misrepresented as being the original software.
23 * 3. This notice may not be removed or altered from any source distribution.
28 #include "metamod_oslink.h"
30 #include <interface.h>
32 #include "metamod_provider.h"
33 #include "metamod_plugins.h"
34 #include "metamod_util.h"
35 #include "metamod_console.h"
37 using namespace SourceMM;
38 using namespace SourceHook;
39 using namespace SourceHook::Impl;
42 * @brief Implementation of main SourceMM GameDLL functionality
46 SH_DECL_MANUALHOOK4(SGD_DLLInit, 0, 0, 0, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
47 SH_DECL_MANUALHOOK0(SGD_GameInit, 0, 0, 0, bool);
48 SH_DECL_MANUALHOOK6(SGD_LevelInit, 0, 0, 0, bool, const char *, const char *, const char *, const char *, bool, bool);
49 SH_DECL_MANUALHOOK0_void(SGD_LevelShutdown, 0, 0, 0);
50 SH_DECL_MANUALHOOK0_void(SGD_DLLShutdown, 0, 0, 0);
52 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
53 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
54 void Handler_DLLShutdown();
55 void Handler_LevelShutdown();
56 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
57 bool Handler_GameInit();
59 void LookForVDFs(const char *dir);
64 CreateInterfaceFn factory;
70 bool parsed_game_info = false;
72 int gamedll_version = 0;
73 int engine_build = SOURCE_ENGINE_UNKNOWN;
74 List<game_dll_t *> gamedll_list;
75 bool is_gamedll_loaded = false;
76 bool in_first_level = true;
77 bool is_game_init = false;
78 bool vsp_load_attempted = false;
79 bool vsp_load_requested = false;
80 bool vsp_loaded = false;
81 game_dll_t gamedll_info;
82 ConVar *metamod_version = NULL;
83 ConVar *mm_pluginsfile = NULL;
84 ConVar *mm_basedir = NULL;
85 IServerGameDLL *server = NULL;
86 CreateInterfaceFn engine_factory = NULL;
87 CreateInterfaceFn physics_factory = NULL;
88 CreateInterfaceFn filesystem_factory = NULL;
89 CGlobalVars *gpGlobals = NULL;
90 CSourceHookImpl g_SourceHook;
91 CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
92 ISourceHook *g_SHPtr = &g_SourceHook;
93 PluginId g_PLID = Pl_Console;
94 META_RES last_meta_res;
95 IServerPluginCallbacks *vsp_callbacks = NULL;
96 bool were_plugins_loaded = false;
98 MetamodSource g_Metamod;
99 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
101 void ClearGamedllList();
104 #define IFACE_MACRO(orig,nam) \
105 CPluginManager::CPlugin *pl; \
106 SourceHook::List<IMetamodListener *>::iterator event; \
107 IMetamodListener *api; \
110 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
112 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
114 mret = IFACE_FAILED; \
115 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
116 if (ret) *ret = mret; \
121 return (orig)(iface, ret);
123 #define ITER_EVENT(evn, args) \
124 CPluginManager::CPlugin *pl; \
125 SourceHook::List<IMetamodListener *>::iterator event; \
126 IMetamodListener *api; \
127 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
129 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
135 /* Initialize everything here */
136 void InitializeForLoad()
138 char full_path[PATH_SIZE] = {0};
139 GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
140 full_bin_path.assign(full_path);
142 /* Like Metamod, reload plugins at the end of the map.
143 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
144 * if the server is shut down (silly, but rare case).
146 in_first_level = true;
148 SourceHook::MemFuncInfo info;
150 if (!provider->GetHookInfo(ProvidedHook_DLLInit, &info))
152 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLInit");
154 SH_MANUALHOOK_RECONFIGURE(SGD_DLLInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
155 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit, false);
156 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit_Post, true);
158 if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
160 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
162 SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
163 SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
165 if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
167 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
169 SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
170 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
172 if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
174 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
176 SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
177 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
179 if (!provider->GetHookInfo(ProvidedHook_DLLShutdown, &info))
181 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLShutdown");
183 SH_MANUALHOOK_RECONFIGURE(SGD_DLLShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
184 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLShutdown, server, Handler_DLLShutdown, false);
187 bool DetectGameInformation()
189 char mm_path[PATH_SIZE];
190 char game_path[PATH_SIZE];
192 /* Get path to SourceMM DLL */
193 if (!GetFileOfAddress((void *)InitializeForLoad, mm_path, sizeof(mm_path)))
198 metamod_path.assign(mm_path);
200 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
201 const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
203 /* Get absolute path */
204 abspath(game_path, game_dir);
205 mod_path.assign(game_path);
207 engine_build = provider->DetermineSourceEngine(game_dir);;
212 /* This is where the magic happens */
213 SMM_API void *CreateInterface(const char *iface, int *ret)
215 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
216 if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
218 provider->DisplayWarning("Do not try loading Metamod:Source as a plugin.\n");
228 if (strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
230 if (vsp_callbacks != NULL && atoi(&iface[22]) != vsp_version)
239 vsp_version = atoi(&iface[22]);
240 vsp_callbacks = provider->GetVSPCallbacks(vsp_version);
244 *ret = (vsp_callbacks != NULL) ? IFACE_OK : IFACE_FAILED;
247 if (vsp_callbacks == NULL)
252 return vsp_callbacks;
255 if (provider->IsAlternatelyLoaded())
257 IFACE_MACRO(gamedll_info.factory, GameDLL);
260 if (!parsed_game_info)
262 parsed_game_info = true;
264 if (!DetectGameInformation())
266 provider->DisplayError("GetFileOfAddress() failed! Metamod cannot load.\n");
270 char temp_path[PATH_SIZE];
272 /* Path to gameinfo.txt */
273 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s", mod_path.c_str(), "gameinfo.txt");
275 FILE *fp = fopen(temp_path, "rt");
279 provider->DisplayError("Unable to open gameinfo.txt! Metamod cannot load.\n");
284 char key[128], val[128];
286 bool gamebin = false;
289 char cur_path[PATH_SIZE];
291 getcwd(cur_path, PATH_SIZE);
293 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
295 UTIL_TrimComments(buffer);
296 UTIL_TrimLeft(buffer);
297 UTIL_TrimRight(buffer);
299 if (stricmp(buffer, "SearchPaths") == 0)
309 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
310 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
312 if (stricmp(key, "Game") == 0)
321 if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
323 ptr = &(val[sizeof("|gameinfo_path|") - 1]);
328 lptr = mod_path.c_str();
334 size_t ptr_len = strlen(ptr);
335 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
337 ptr[--ptr_len] = '\0';
340 /* No need to append "bin" if key is GameBin */
343 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
347 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
351 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
354 /* If not path to SourceMM... */
355 if (!UTIL_PathCmp(metamod_path.c_str(), temp_path))
357 FILE *temp_fp = fopen(temp_path, "rb");
364 /* Search for a matching game dll */
365 List<game_dll_t *>::iterator iter;
368 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
371 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
373 if (UTIL_PathCmp(temp_path, buffer))
386 HINSTANCE gamedll = dlmount(temp_path);
392 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
399 game_dll_t *pInfo = new game_dll_t;
401 pInfo->lib = gamedll;
402 gamedll_list.push_back(pInfo);
410 if (!is_gamedll_loaded)
412 if (strncmp(iface, "ServerGameDLL", 13) == 0)
414 List<game_dll_t *>::iterator iter;
416 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
419 if ((server = (IServerGameDLL *)((pInfo->factory)(iface, ret))) != NULL)
421 if ((gamedll_version = provider->TryServerGameDLL(iface)) != 0)
423 /* We have a match. Erase us from the list and save our info. */
424 gamedll_list.erase(iter);
425 gamedll_info = *pInfo;
427 is_gamedll_loaded = true;
430 /* :TODO: error otherwise? */
434 if (is_gamedll_loaded)
450 /* wtf do we do... */
451 /* :TODO: .. something a bit more intelligent? */
452 provider->DisplayError("Engine requested unknown interface before GameDLL was known!\n");
457 /* If we got here, there's definitely a GameDLL */
458 IFACE_MACRO(gamedll_info.factory, GameDLL);
461 void ClearGamedllList()
463 List<game_dll_t *>::iterator iter;
466 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
473 gamedll_list.clear();
476 int LoadPluginsFromFile(const char *_file)
479 int total = 0, skipped=0;
483 fp = fopen(_file, "rt");
486 LogMessage("[META] Could not open plugins file %s\n", _file);
490 char buffer[255], error[255], full_path[255];
491 const char *ptr, *ext, *file;
493 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
495 UTIL_TrimLeft(buffer);
496 UTIL_TrimRight(buffer);
498 length = strlen(buffer);
504 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
510 if (buffer[0] == '"')
533 while (*cptr && isspace(*cptr))
538 UTIL_TrimRight(cptr);
539 if (*cptr && isalpha(*cptr))
541 g_PluginMngr.SetAlias(buffer, cptr);
553 /* First find if it's an absolute path or not... */
554 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
556 /* If we're in an absolute path, ignore our normal heuristics */
557 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
558 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
560 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
576 /* Attempt to find a file extension */
577 ptr = UTIL_GetExtension(file);
578 /* Add an extension if there's none there */
581 #if defined WIN32 || defined _WIN32
591 /* Format the new path */
592 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
593 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
594 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
596 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
615 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
619 LogMessage("[META] Loaded %d plugins from file.", total);
627 if (provider->IsAlternatelyLoaded())
633 char engine_file[PATH_SIZE];
634 char engine_path[PATH_SIZE];
635 char rel_path[PATH_SIZE * 2];
637 GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
639 /* Chop off the "engine" file part */
640 len = strlen(engine_file);
641 for (size_t i = len - 1; i >= 0 && i < len; i--)
643 if (engine_file[i] == '/' || engine_file[i] == '\\')
645 engine_file[i] = '\0';
649 abspath(engine_path, engine_file);
651 const char *usepath = metamod_path.c_str();
652 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
657 char command[PATH_SIZE * 2];
658 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
659 provider->ServerCommand(command);
662 /* Wrapper function. This is called when the GameDLL thinks it's using
663 * the engine's real engineFactory.
665 void *EngineFactory(const char *iface, int *ret)
667 IFACE_MACRO(engine_factory, Engine);
670 /* Wrapper function. This is called when the GameDLL thinks it's using
671 * the engine's real physicsFactory.
673 void *PhysicsFactory(const char *iface, int *ret)
675 IFACE_MACRO(physics_factory, Physics);
678 /* Wrapper function. This is called when the GameDLL thinks it's using
679 * the engine's real fileSystemFactory.
681 void *FileSystemFactory(const char *iface, int *ret)
683 IFACE_MACRO(filesystem_factory, FileSystem);
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 (!provider->LogMessage(buffer))
700 fprintf(stdout, "%s", buffer);
704 void DoInitialPluginLoads()
706 const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
707 const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
710 pluginFile = provider->GetConVarString(mm_pluginsfile);
711 if (pluginFile == NULL)
713 pluginFile = "addons/metamod/metaplugins.ini";
718 mmBaseDir = provider->GetConVarString(mm_basedir);
719 if (mmBaseDir == NULL)
721 mmBaseDir = "addons/metamod";
727 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
728 LoadPluginsFromFile(full_path);
730 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
731 LookForVDFs(full_path);
734 void StartupMetamod(bool is_vsp_load)
742 is_vsp_load ? "V" : "");
744 metamod_version = provider->CreateConVar("metamod_version",
746 "Metamod:Source Version",
747 ConVarFlag_Notify|ConVarFlag_SpOnly);
749 provider->SetConVarString(metamod_version, buffer);
751 mm_pluginsfile = provider->CreateConVar("mm_pluginsfile",
752 #if defined WIN32 || defined _WIN32
753 "addons\\metamod\\metaplugins.ini",
755 "addons/metamod/metaplugins.ini",
757 "Metamod:Source Plugins File",
760 mm_basedir = provider->CreateConVar("mm_basedir",
761 #if defined __linux__
766 "Metamod:Source Base Folder",
771 DoInitialPluginLoads();
772 in_first_level = true;
776 void InitializeGlobals(CreateInterfaceFn engineFactory,
777 CreateInterfaceFn physicsFactory,
778 CreateInterfaceFn filesystemFactory,
779 CGlobalVars *pGlobals)
781 engine_factory = engineFactory;
782 physics_factory = physicsFactory;
783 filesystem_factory = filesystemFactory;
784 gpGlobals = pGlobals;
785 provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
788 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
790 InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
791 StartupMetamod(false);
793 RETURN_META_VALUE(MRES_IGNORED, true);
796 bool Handler_GameInit()
803 if (vsp_load_requested)
808 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
810 DoInitialPluginLoads();
811 g_PluginMngr.SetAllLoaded();
812 were_plugins_loaded = true;
817 RETURN_META_VALUE(MRES_IGNORED, true);
820 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
822 g_PluginMngr.SetAllLoaded();
823 RETURN_META_VALUE(MRES_IGNORED, true);
829 g_PluginMngr.UnloadAll();
831 provider->Notify_DLLShutdown_Pre();
833 if (is_gamedll_loaded)
835 SH_CALL(server, &IServerGameDLL::DLLShutdown)();
838 g_SourceHook.CompleteShutdown();
840 if (is_gamedll_loaded && gamedll_info.lib)
842 dlclose(gamedll_info.lib);
843 is_gamedll_loaded = false;
847 void Handler_DLLShutdown()
850 RETURN_META(MRES_SUPERCEDE);
853 void Handler_LevelShutdown(void)
855 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
857 g_PluginMngr.SetAllLoaded();
858 DoInitialPluginLoads();
859 were_plugins_loaded = true;
860 in_first_level = true;
867 g_Metamod.PathFormat(full_path,
871 provider->GetConVarString(mm_pluginsfile));
872 LoadPluginsFromFile(full_path);
874 g_Metamod.PathFormat(full_path,
878 provider->GetConVarString(mm_basedir));
879 LookForVDFs(full_path);
883 in_first_level = false;
886 ITER_EVENT(OnLevelShutdown, ());
888 RETURN_META(MRES_IGNORED);
891 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
893 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
895 RETURN_META_VALUE(MRES_IGNORED, false);
898 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
904 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
907 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
910 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
914 return EngineFactory;
917 return engine_factory;
920 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
924 return PhysicsFactory;
927 return physics_factory;
930 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
934 return FileSystemFactory;
937 return filesystem_factory;
940 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
944 return CreateInterface;
947 return gamedll_info.factory;
950 CGlobalVars *MetamodSource::GetCGlobals()
955 void MetamodSource::SetLastMetaReturn(META_RES res)
960 META_RES MetamodSource::GetLastMetaReturn()
962 return last_meta_res;
965 void MetamodSource::ConPrint(const char *str)
967 provider->ConsolePrint(str);
970 void MetamodSource::ConPrintf(const char *fmt, ...)
976 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
979 provider->ConsolePrint(buffer);
982 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
984 major = METAMOD_API_MAJOR;
985 minor = METAMOD_API_MINOR;
986 plvers = METAMOD_PLAPI_VERSION;
987 plmin = PLAPI_MIN_VERSION;
990 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
992 shvers = SH_IFACE_VERSION;
993 shimpl = SH_IMPL_VERSION;
996 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
998 int length = (int)strlen(iface);
1002 for (i = length - 1; i >= 0; i--)
1004 if (!isdigit(iface[i]))
1006 if (i != length - 1)
1014 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
1019 if (i != length - 1)
1021 num = atoi(&(iface[++i]));
1026 snprintf(&(iface[i]), 4, "%03d", num);
1031 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
1033 char _if[256]; /* assume no interface goes beyond this */
1034 size_t len = strlen(iface);
1043 if (len + 4 > sizeof(_if))
1047 *ret = IFACE_FAILED;
1056 if ((pf = (fn)(_if, ret)) != NULL)
1064 } while ((num = FormatIface(_if, len+1)));
1069 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
1071 char buffer[256]; /* assume no interface will go beyond this */
1072 size_t len = strlen(iface);
1073 int ret; /* just in case something doesn't handle NULL properly */
1075 if (len > sizeof(buffer) - 4)
1080 strcpy(buffer, iface);
1084 char *ptr = &buffer[len - 1];
1086 while (isdigit(*ptr) && digits <=3)
1094 /* for now, assume this is an error */
1095 strcpy(buffer, iface);
1100 min = (min == 0) ? 1 : min;
1101 snprintf(num, sizeof(num), "%03d", min);
1102 strcat(buffer, num);
1106 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
1109 const char *MetamodSource::GetBaseDir()
1111 return mod_path.c_str();
1114 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
1118 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
1121 for (size_t i = 0; i < mylen; i++)
1123 if (buffer[i] == ALT_SEP_CHAR)
1125 buffer[i] = PATH_SEP_CHAR;
1132 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
1138 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1141 provider->ClientConsolePrint(client, buffer);
1144 void MetamodSource::EnableVSPListener()
1146 if (is_game_init && !vsp_load_requested && !vsp_loaded)
1151 vsp_load_requested = true;
1154 int MetamodSource::GetVSPVersion()
1159 int MetamodSource::GetGameDLLVersion()
1161 return gamedll_version;
1164 bool MetamodSource::RemotePrintingAvailable()
1166 return provider->IsRemotePrintingAvailable();
1169 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
1181 /* First check ours... we get first chance! */
1182 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
1188 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
1190 else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
1196 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
1198 else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
1204 return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
1207 CPluginManager::CPlugin *pl;
1208 List<IMetamodListener *>::iterator event;
1209 IMetamodListener *api;
1213 for (PluginIter iter = g_PluginMngr._begin();
1214 iter != g_PluginMngr._end();
1218 for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
1221 subret = IFACE_FAILED;
1222 if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
1239 *ret = IFACE_FAILED;
1245 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
1247 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
1249 pl->m_Events.push_back(pListener);
1252 const char *MetamodSource::GetGameBinaryPath()
1254 return full_bin_path.c_str();
1257 const char *MetamodSource::GetPluginsFile()
1259 return provider->GetConVarString(mm_pluginsfile);
1262 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
1264 return provider->GetConCommandBaseAccessor();
1267 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1269 if (provider->IsConCommandBaseACommand(pCommand))
1271 g_PluginMngr.AddPluginCmd(plugin, pCommand);
1275 g_PluginMngr.AddPluginCvar(plugin, pCommand);
1278 return provider->RegisterConCommandBase(pCommand);
1281 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1283 if (provider->IsConCommandBaseACommand(pCommand))
1285 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
1289 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
1292 CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
1293 UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
1296 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
1299 CPluginManager::CPlugin *pPlugin;
1300 List<IMetamodListener *>::iterator event;
1301 IMetamodListener *pML;
1302 for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
1305 if (pPlugin->m_Status < Pl_Paused)
1309 /* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
1310 if (pPlugin->m_API->GetApiVersion() < 12)
1314 for (event=pPlugin->m_Events.begin();
1315 event!=pPlugin->m_Events.end();
1319 pML->OnUnlinkConCommandBase(id, pCommand);
1323 return provider->UnregisterConCommandBase(pCommand);
1326 int MetamodSource::GetUserMessageCount()
1328 return provider->GetUserMessageCount();
1331 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
1333 return provider->FindUserMessage(name, size);
1336 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
1338 return provider->GetUserMessage(index, size);
1341 int MetamodSource::GetSourceEngineBuild()
1343 return engine_build;
1346 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
1348 ITER_EVENT(OnVSPListening, (callbacks));
1351 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
1355 *pVersion = vsp_version;
1358 return vsp_callbacks;
1361 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
1366 va_start(ap, format);
1367 result = FormatArgs(buffer, maxlength, format, ap);
1373 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
1375 return UTIL_FormatArgs(buffer, maxlength, format, ap);
1378 bool MetamodSource::IsLoadedAsGameDLL()
1380 return is_gamedll_loaded;
1383 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
1385 gamedll_info.factory = serverFactory;
1386 gamedll_version = version;
1389 bool MetamodSource::IsAlternateLoadComplete()
1391 return were_plugins_loaded;
1394 void ProcessVDF(const char *path)
1398 char alias[24], file[255], error[255];
1400 if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
1405 if (alias[0] != '\0')
1407 g_PluginMngr.SetAlias(alias, file);
1410 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
1411 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1413 LogMessage("[META] Failed to load plugin %s: %s", file, error);
1417 void LookForVDFs(const char *dir)
1419 char path[MAX_PATH];
1421 #if defined _MSC_VER
1427 g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
1428 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
1430 DWORD dw = GetLastError();
1431 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
1434 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1438 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
1444 if (strcmp(fd.cFileName, ".") == 0
1445 || strcmp(fd.cFileName, "..") == 0)
1449 extidx = strlen(fd.cFileName) - 4;
1450 if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1454 g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
1456 } while (FindNextFile(hFind, &fd));
1461 struct dirent *pEnt;
1463 if ((pDir = opendir(dir)) == NULL)
1465 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
1469 while ((pEnt = readdir(pDir)) != NULL)
1471 if (strcmp(pEnt->d_name, ".") == 0
1472 || strcmp(pEnt->d_name, "..") == 0)
1476 extidx = strlen(fd.cFileName) - 4;
1477 if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1481 g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);