1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2007 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"
23 using namespace SourceMM;
26 * @brief Implementation of main SourceMM GameDLL functionality
31 DLL_IMPORT ICommandLine *CommandLine();
33 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
34 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
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 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
41 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
42 void DLLShutdown_handler();
43 void LevelShutdown_handler();
44 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
45 bool GameInit_handler();
47 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
49 SourceHook::CSourceHookImpl g_SourceHook;
50 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
51 SourceHook::String g_ModPath;
52 SourceHook::String g_BinPath;
53 SourceHook::String g_SmmPath;
54 PluginId g_PLID = Pl_Console; /* Technically, SourceMM is the "Console" plugin... :p */
55 bool bInFirstLevel = true;
56 bool gParsedGameInfo = false;
57 bool bGameInit = false;
58 SourceHook::List<GameDllInfo *> gamedll_list;
59 SourceHook::CallClass<IServerGameDLL> *g_GameDllPatch;
60 int g_GameDllVersion = 0;
61 int g_GameClientsVersion = 0;
63 const char VSPIFACE[] = "ISERVERPLUGINCALLBACKS";
64 const char GAMEINFO_PATH[] = "|gameinfo_path|";
66 void ClearGamedllList();
69 #define IFACE_MACRO(orig,nam) \
70 CPluginManager::CPlugin *pl; \
71 SourceHook::List<IMetamodListener *>::iterator event; \
72 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++) { \
79 mret = IFACE_FAILED; \
80 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
81 if (ret) *ret = mret; \
86 return (orig)(iface, ret);
88 #define ITER_EVENT(evn, args) \
89 CPluginManager::CPlugin *pl; \
90 SourceHook::List<IMetamodListener *>::iterator event; \
91 IMetamodListener *api; \
92 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
94 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
100 ///////////////////////////////////
101 // Main code for HL2 Interaction //
102 ///////////////////////////////////
104 /* Initialize everything here */
105 void InitMainStates()
107 char full_path[PATH_SIZE] = {0};
108 GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path));
109 g_BinPath.assign(full_path);
111 /* Like Metamod, reload plugins at the end of the map.
112 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
113 * if the server is shut down (silly, but rare case).
115 bInFirstLevel = true;
117 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
118 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
119 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
120 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
121 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
122 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
125 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
127 g_Engine.engineFactory = engineFactory;
128 g_Engine.fileSystemFactory = filesystemFactory;
129 g_Engine.physicsFactory = physicsFactory;
130 g_Engine.pGlobals = pGlobals;
132 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
133 if (!g_Engine.engine)
135 Error("Could not find IVEngineServer! Metamod cannot load.");
138 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
141 Error("Could not find ICvar! Metamod cannot load.");
145 g_Engine.loaded = true;
147 /* Initialize our console hooks */
148 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
150 g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
152 if (g_GameDll.pGameClients)
154 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
156 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
157 LogMessage("[META] Warning: Could not find IServerGameClients!");
158 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
161 if (!g_SmmAPI.CacheCmds())
163 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
164 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
167 if (!g_SmmAPI.CacheUserMessages())
169 /* Don't know of a mod that has stripped out user messages completely,
170 * but perhaps should do something different here?
172 LogMessage("[META] Warning: Failed to get list of user messages.");
173 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
176 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
179 pluginFile = GetPluginsFile();
183 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), pluginFile);
185 LoadPluginsFromFile(full_path);
187 bInFirstLevel = true;
189 RETURN_META_VALUE(MRES_IGNORED, true);
192 bool GameInit_handler()
199 if (g_SmmAPI.VSPEnabled())
201 g_SmmAPI.LoadAsVSP();
206 RETURN_META_VALUE(MRES_IGNORED, true);
209 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
211 g_PluginMngr.SetAllLoaded();
212 RETURN_META_VALUE(MRES_IGNORED, true);
215 /* This is where the magic happens */
216 SMM_API void *CreateInterface(const char *iface, int *ret)
218 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
219 if (strcmp(iface, PLAPI_NAME) == 0)
221 Warning("Do not try loading Metamod:Source as a SourceMM or Valve server plugin.\n");
231 if (strncmp(iface, VSPIFACE, 22) == 0)
233 g_VspVersion = atoi(&(iface[22]));
235 if (g_VspVersion <= MAX_VSP_VERSION)
241 return &g_VspListener;
245 if (!gParsedGameInfo)
247 gParsedGameInfo = true;
248 const char *gameDir = NULL;
249 char gamePath[PATH_SIZE];
250 char smmPath[PATH_SIZE];
252 /* Get path to SourceMM DLL */
253 if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
255 Error("GetFileOfAddress() failed! Metamod cannot load.\n");
259 g_SmmPath.assign(smmPath);
261 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
262 gameDir = CommandLine()->ParmValue("-game", "hl2");
264 /* Get absolute path */
265 abspath(gamePath, gameDir);
266 g_ModPath.assign(gamePath);
268 char tempPath[PATH_SIZE];
270 /* Path to gameinfo.txt */
271 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
273 FILE *fp = fopen(tempPath, "rt");
277 Error("Unable to open gameinfo.txt! Metamod cannot load.\n");
282 char key[128], val[128];
284 bool gamebin = false;
287 char curPath[PATH_SIZE];
289 getcwd(curPath, PATH_SIZE);
294 fgets(buffer, sizeof(buffer), fp);
295 UTIL_TrimComments(buffer);
296 UTIL_TrimLeft(buffer);
297 UTIL_TrimRight(buffer);
298 if (stricmp(buffer, "SearchPaths") == 0)
302 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
303 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
305 if (stricmp(key, "Game") == 0)
310 if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
312 ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
315 lptr = g_ModPath.c_str();
321 size_t ptr_len = strlen(ptr);
322 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
323 ptr[--ptr_len] = '\0';
325 /* No need to append "bin" if key is GameBin */
328 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
329 } else if (!ptr[0]) {
330 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
332 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
335 /* If not path to SourceMM... */
336 if (!UTIL_PathCmp(smmPath, tempPath))
338 FILE *fp = fopen(tempPath, "rb");
341 //:TODO: Optimize this a bit!
342 SourceHook::List<GameDllInfo *>::iterator iter;
345 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
348 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
350 if (UTIL_PathCmp(tempPath, buffer))
360 HINSTANCE gamedll = dlmount(tempPath);
363 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
369 GameDllInfo *pInfo = new GameDllInfo;
371 pInfo->lib = gamedll;
372 pInfo->loaded = true;
373 pInfo->pGameDLL = NULL;
374 gamedll_list.push_back(pInfo);
382 if (!g_GameDll.loaded)
384 const char *str = "ServerGameDLL";
385 size_t len = strlen(str);
387 if (strncmp(iface, str, len) == 0)
389 /* This is the interface we want! Right now we support versions 3 through 8 */
390 g_GameDllVersion = atoi(&(iface[len]));
391 int sizeTooBig = 0; //rename this to sizeWrong in the future!
392 if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
394 /* Maybe this will get used in the future */
395 sizeTooBig = g_GameDllVersion;
401 SourceHook::List<GameDllInfo *>::iterator iter;
402 GameDllInfo *pInfo = NULL;
404 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
407 ptr = (pInfo->factory)(iface, ret);
410 /* This is our GameDLL. Unload the others. */
411 gamedll_list.erase(iter);
413 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
419 if (g_GameDll.loaded)
423 Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
439 /* wtf do we do... */
440 /* :TODO: .. something a bit more intelligent? */
441 Error("Engine requested unknown interface before GameDLL was known!\n");
446 /* We use this interface for responding to the meta client command */
447 if (strncmp(iface, "ServerGameClients", 17) == 0)
449 void *ptr = (g_GameDll.factory)(iface, ret);
450 g_GameDll.pGameClients = static_cast<IServerGameClients *>(ptr);
451 g_GameClientsVersion = atoi(&iface[17]);
456 /* If we got here, there's definitely a GameDLL */
457 IFACE_MACRO(g_GameDll.factory, GameDLL);
460 void ClearGamedllList()
462 SourceHook::List<GameDllInfo *>::iterator iter;
465 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
472 gamedll_list.clear();
475 void DLLShutdown_handler()
478 g_PluginMngr.UnloadAll();
480 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
481 g_SMConVarAccessor.MarkCommandsAsGameDLL();
482 g_SMConVarAccessor.UnregisterGameDLLCommands();
484 SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
486 SH_RELEASE_CALLCLASS(g_GameDllPatch);
487 g_GameDllPatch = NULL;
489 g_SourceHook.CompleteShutdown();
491 if (g_GameDll.lib && g_GameDll.loaded)
492 dlclose(g_GameDll.lib);
493 memset(&g_GameDll, 0, sizeof(GameDllInfo));
495 RETURN_META(MRES_SUPERCEDE);
498 int LoadPluginsFromFile(const char *_file)
501 int total = 0, skipped=0;
505 fp = fopen(_file, "rt");
508 LogMessage("[META] Could not open plugins file %s\n", _file);
512 char buffer[255], error[255], full_path[255];
513 const char *ptr, *ext, *file;
518 fgets(buffer, sizeof(buffer), fp);
519 length = strlen(buffer);
522 if (buffer[length-1] == '\n')
523 buffer[--length] = '\0';
525 UTIL_TrimLeft(buffer);
526 UTIL_TrimRight(buffer);
528 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
531 if (buffer[0] == '"')
552 while (*cptr && isspace(*cptr))
555 UTIL_TrimRight(cptr);
556 if (*cptr && isalpha(*cptr))
558 g_PluginMngr.SetAlias(buffer, cptr);
570 /* First find if it's an absolute path or not... */
571 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
573 /* If we're in an absolute path, ignore our normal heuristics */
574 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
575 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
577 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
598 /* Format the new path */
599 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
600 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
601 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
603 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
616 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
618 LogMessage("[META] Loaded %d plugins from file.", total);
624 /* Wrapper function. This is called when the GameDLL thinks it's using
625 * the engine's real engineFactory.
627 void *EngineFactory(const char *iface, int *ret)
629 IFACE_MACRO(g_Engine.engineFactory, Engine);
632 /* Wrapper function. This is called when the GameDLL thinks it's using
633 * the engine's real physicsFactory.
635 void *PhysicsFactory(const char *iface, int *ret)
637 IFACE_MACRO(g_Engine.physicsFactory, Physics);
640 /* Wrapper function. This is called when the GameDLL thinks it's using
641 * the engine's real fileSystemFactory.
643 void *FileSystemFactory(const char *iface, int *ret)
645 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
648 void LogMessage(const char *msg, ...)
651 static char buffer[2048];
654 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
657 buffer[len++] = '\n';
660 if (!g_Engine.engine)
662 fprintf(stdout, "%s", buffer);
664 g_Engine.engine->LogPrint(buffer);
668 void LevelShutdown_handler(void)
673 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
675 LoadPluginsFromFile(full_path);
677 bInFirstLevel = false;
680 ITER_EVENT(OnLevelShutdown, ());
682 RETURN_META(MRES_IGNORED);
685 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
687 if (!g_SmmAPI.CmdCacheSuccessful())
689 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
690 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
693 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
695 RETURN_META_VALUE(MRES_IGNORED, false);
698 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
699 void * operator new(size_t size) {
700 return(calloc(1, size));
703 void * operator new[](size_t size) {
704 return(calloc(1, size));
707 void operator delete(void * ptr) {
712 void operator delete[](void * ptr) {