El horrible: Fixed build.
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 SourceHook::CallClass<IServerGameDLL> *g_GameDllPatch;
64 SourceHook::CallClass<ICvar> *g_CvarPatch;
65 int g_GameDllVersion = 0;
66 static const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
67 static const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
68 static const char GAMEINFO_PATH[] = "|gameinfo_path|";
69 IFileSystem *baseFs = NULL;
70 bool g_bLevelChanged = false;
71 IServerPluginCallbacks *g_pRealVspCallbacks = &g_VspListener;
73 #define ITER_EVENT(evn, args) \
74 CPluginManager::CPlugin *pl; \
75 SourceHook::List<CPluginEventHandler>::iterator event; \
76 IMetamodListener *api; \
77 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
79 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
80 api = (*event).event; \
85 ///////////////////////////////////
86 // Main code for HL2 Interaction //
87 ///////////////////////////////////
89 /* Initialize everything here */
92 /* Like Metamod, reload plugins at the end of the map.
93 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
94 * if the server is shut down (silly, but rare case).
98 char smm_path[PATH_SIZE];
99 const char *game_dir = CommandLine()->ParmValue("-game", "hl2");
100 abspath(smm_path, game_dir);
101 g_ModPath.assign(smm_path);
103 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
104 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
105 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
108 void DoInitialPluginLoads()
110 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
111 const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
115 pluginFile = GetPluginsFile();
119 mmBaseDir = GetMetamodBaseDir();
122 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
124 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), pluginFile);
125 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), mmBaseDir);
126 LoadPlugins(filepath, vdfpath);
130 CreateInterface(const char *iface, int *ret)
134 if (!g_bIsBridgedAsVsp && strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
136 if (g_VspListener.IsLoaded())
143 assert(&g_VspListener == g_pRealVspCallbacks);
145 int vsp_version = atoi(&iface[22]);
146 if (vsp_version < 1 || vsp_version > 2)
153 return g_pRealVspCallbacks;
157 *ret = (ptr != NULL) ? IFACE_OK : IFACE_FAILED;
162 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
164 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
166 if (!g_Engine.engine)
168 Error("Could not find IVEngineServer! Metamod cannot load.");
171 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
174 Error("Could not find ICvar! Metamod cannot load.");
178 g_Engine.loaded = true;
180 /* The Ship is the only game known at this time that uses the pre-Episode One engine */
181 g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
183 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
185 g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
186 g_CvarPatch = SH_GET_CALLCLASS(g_Engine.icvar);
188 if (g_GameDll.pGameClients)
190 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
194 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
195 LogMessage("[META] Warning: Could not find IServerGameClients!");
196 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
199 if (!g_SmmAPI.CacheCmds())
201 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
202 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
205 if (!g_SmmAPI.CacheUserMessages())
207 /* Don't know of a mod that has stripped out user messages completely,
208 * but perhaps should do something different here?
210 LogMessage("[META] Warning: Failed to get list of user messages.");
211 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
214 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
217 LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
220 if (!g_SMConVarAccessor.InitConCommandBaseList())
222 /* This is very unlikely considering it's old engine */
223 LogMessage("[META] Warning: Failed to find ConCommandBase list!");
224 LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
227 if (!bWaitForGameInit)
229 DoInitialPluginLoads();
230 bInFirstLevel = true;
236 void LoadAsGameDLL(const gamedll_bridge_info *info)
238 g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
239 g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
240 g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
241 g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
242 g_GameDll.loaded = true;
243 g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
244 g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
245 g_GameDllVersion = info->dllVersion;
249 StartupMetamod(g_Engine.engineFactory, false);
252 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
254 g_Engine.engineFactory = ifaceFactory;
255 g_Engine.fileSystemFactory = ifaceFactory;
256 g_Engine.physicsFactory = ifaceFactory;
258 IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
259 if (playerInfoManager == NULL)
261 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
265 g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
267 /* Now find the server */
268 g_GameDll.factory = serverFactory;
270 char gamedll_iface[] = "ServerGameDLL000";
271 for (unsigned int i = 3; i <= 50; i++)
273 gamedll_iface[15] = '0' + i;
274 g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
275 if (g_GameDll.pGameDLL != NULL)
277 g_GameDllVersion = i;
282 if (g_GameDll.pGameDLL == NULL)
284 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
288 char gameclients_iface[] = "ServerGameClients000";
289 for (unsigned int i = 3; i <= 4; i++)
291 gameclients_iface[19] = '0' + i;
292 g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
293 if (g_GameDll.pGameClients != NULL)
301 if (!StartupMetamod(ifaceFactory, true))
306 g_PluginMngr.SetAllLoaded();
311 bool GameInit_handler()
314 RETURN_META_VALUE(MRES_IGNORED, true);
316 if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
317 g_SmmAPI.LoadAsVSP();
319 if (g_bIsBridgedAsVsp)
320 DoInitialPluginLoads();
324 RETURN_META_VALUE(MRES_IGNORED, true);
327 void UnloadMetamod(bool shutting_down)
330 g_PluginMngr.UnloadAll();
334 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
335 g_SMConVarAccessor.MarkCommandsAsGameDLL();
336 g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
339 SH_RELEASE_CALLCLASS(g_GameDllPatch);
340 SH_RELEASE_CALLCLASS(g_CvarPatch);
341 g_GameDllPatch = NULL;
344 g_SourceHook.CompleteShutdown();
347 bool LoadFromVDF(const char *file, bool &skipped)
350 bool already, kvfileLoaded;
352 const char *plugin_file, *alias;
353 char full_path[256], error[256];
355 pValues = new KeyValues("Metamod Plugin");
357 if (g_Engine.original)
359 /* The Ship must use a special version of this function */
360 kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
364 kvfileLoaded = pValues->LoadFromFile(baseFs, file);
369 pValues->deleteThis();
374 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
376 pValues->deleteThis();
381 if ((alias = pValues->GetString("alias", NULL)) != NULL)
383 g_PluginMngr.SetAlias(alias, plugin_file);
386 /* Attempt to find a file extension */
387 if (UTIL_GetExtension(plugin_file) == NULL)
389 g_SmmAPI.PathFormat(full_path,
394 #if defined WIN32 || defined _WIN32
403 g_SmmAPI.PathFormat(full_path,
410 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
412 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
414 LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
418 pValues->deleteThis();
422 int LoadVDFPluginsFromDir(const char *dir, int &skipped)
435 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
436 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
438 DWORD dw = GetLastError();
439 if (dw == ERROR_FILE_NOT_FOUND)
442 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
445 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
449 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
455 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
456 success = LoadFromVDF(path, skip);
461 } while (FindNextFile(hFind, &fd));
469 if ((pDir = opendir(dir)) == NULL)
471 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
475 while ((pEnt = readdir(pDir)) != NULL)
477 if (strcmp(pEnt->d_name, ".") == 0
478 || strcmp(pEnt->d_name, "..") == 0)
482 extidx = strlen(pEnt->d_name) - 4;
483 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
487 g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
488 success = LoadFromVDF(path, skip);
501 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
505 Assert(_heapchk() == _HEAPOK);
508 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
512 // load file into a null-terminated buffer
513 int fileSize = filesystem->Size(f);
514 char *buffer = (char *)MemAllocScratch(fileSize + 1);
518 filesystem->Read(buffer, fileSize, f); // read into local buffer
520 buffer[fileSize] = 0; // null terminate file as EOF
522 filesystem->Close( f ); // close file after reading
524 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
531 int LoadPluginsFromFile(const char *filepath, int &skipped)
540 fp = fopen(filepath, "rt");
546 char buffer[255], error[255], full_path[PATH_SIZE];
547 const char *ptr, *ext, *file;
549 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
551 UTIL_TrimLeft(buffer);
552 UTIL_TrimRight(buffer);
554 length = strlen(buffer);
560 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
566 if (buffer[0] == '"')
589 while (*cptr && isspace(*cptr))
594 UTIL_TrimRight(cptr);
595 if (*cptr && isalpha(*cptr))
597 g_PluginMngr.SetAlias(buffer, cptr);
609 /* First find if it's an absolute path or not... */
610 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
612 /* If we're in an absolute path, ignore our normal heuristics */
613 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
614 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
616 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
632 /* Attempt to find a file extension */
633 ptr = UTIL_GetExtension(file);
634 /* Add an extension if there's none there */
637 #if defined WIN32 || defined _WIN32
647 /* Format the new path */
648 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
649 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
650 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
652 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
672 int LoadPlugins(const char *filepath, const char *vdfpath)
674 int total, skipped, fskipped, vskipped;
677 total = LoadPluginsFromFile(filepath, fskipped);
678 total += LoadVDFPluginsFromDir(vdfpath, vskipped);
679 skipped = fskipped + vskipped;
681 if (total == 0 || total > 1)
685 LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
687 LogMessage("[META] Loaded %d plugin%s.", total, s);
692 void LogMessage(const char *msg, ...)
695 static char buffer[2048];
698 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
701 buffer[len++] = '\n';
704 if (!g_Engine.engine)
706 fprintf(stdout, "%s", buffer);
708 g_Engine.engine->LogPrint(buffer);
712 void LevelShutdown_handler(void)
716 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
718 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
719 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
720 LoadPlugins(filepath, vdfpath);
724 bInFirstLevel = false;
727 g_bLevelChanged = true;
729 ITER_EVENT(OnLevelShutdown, ());
731 RETURN_META(MRES_IGNORED);
734 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
736 if (!g_SmmAPI.CmdCacheSuccessful())
738 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
739 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
742 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
744 RETURN_META_VALUE(MRES_IGNORED, false);
747 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
748 void * operator new(size_t size) {
749 return(calloc(1, size));
752 void * operator new[](size_t size) {
753 return(calloc(1, size));
756 void operator delete(void * ptr) {
761 void operator delete[](void * ptr) {