1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/core-legacy/sourcemm.cpp Fri Nov 14 05:02:00 2008 -0600
1.3 @@ -0,0 +1,1061 @@
1.4 +/* ======== SourceMM ========
1.5 + * Copyright (C) 2004-2008 Metamod:Source Development Team
1.6 + * No warranties of any kind
1.7 + *
1.8 + * License: zlib/libpng
1.9 + *
1.10 + * Author(s): David "BAILOPAN" Anderson
1.11 + * Contributor(s): Scott "Damaged Soul" Ehlert
1.12 + * : Pavol "PM OnoTo" Marko
1.13 + * ============================
1.14 + */
1.15 +
1.16 +#include <interface.h>
1.17 +#include <eiface.h>
1.18 +#include <tier0/icommandline.h>
1.19 +#include "sourcemm.h"
1.20 +#include "concommands.h"
1.21 +#include "CSmmAPI.h"
1.22 +#include "CPlugin.h"
1.23 +#include "util.h"
1.24 +#include "vsp_listener.h"
1.25 +#include "iplayerinfo.h"
1.26 +#include <filesystem.h>
1.27 +
1.28 +using namespace SourceMM;
1.29 +
1.30 +/**
1.31 + * @brief Implementation of main SourceMM GameDLL functionality
1.32 + * @file sourcemm.cpp
1.33 + */
1.34 +
1.35 +#undef CommandLine
1.36 +DLL_IMPORT ICommandLine *CommandLine();
1.37 +
1.38 +SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
1.39 +SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
1.40 +SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
1.41 +SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
1.42 +SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
1.43 +SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
1.44 +
1.45 +bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
1.46 +bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
1.47 +void DLLShutdown_handler();
1.48 +void LevelShutdown_handler();
1.49 +bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
1.50 +bool GameInit_handler();
1.51 +void LookForVDFs(const char *dir);
1.52 +bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID = NULL);
1.53 +
1.54 +GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
1.55 +EngineInfo g_Engine;
1.56 +SourceHook::CSourceHookImpl g_SourceHook;
1.57 +SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
1.58 +SourceHook::String g_ModPath;
1.59 +SourceHook::String g_BinPath;
1.60 +SourceHook::String g_SmmPath;
1.61 +PluginId g_PLID = Pl_Console; /* Technically, SourceMM is the "Console" plugin... :p */
1.62 +bool bInFirstLevel = true;
1.63 +bool gParsedGameInfo = false;
1.64 +bool bGameInit = false;
1.65 +SourceHook::List<GameDllInfo *> gamedll_list;
1.66 +SourceHook::CallClass<IServerGameDLL> *g_GameDllPatch;
1.67 +SourceHook::CallClass<ICvar> *g_CvarPatch;
1.68 +int g_GameDllVersion = 0;
1.69 +const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
1.70 +const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
1.71 +const char GAMEINFO_PATH[] = "|gameinfo_path|";
1.72 +IFileSystem *baseFs = NULL;
1.73 +bool g_bLevelChanged = false;
1.74 +
1.75 +
1.76 +void ClearGamedllList();
1.77 +
1.78 +/* Helper Macro */
1.79 +#define IFACE_MACRO(orig,nam) \
1.80 + CPluginManager::CPlugin *pl; \
1.81 + SourceHook::List<CPluginEventHandler>::iterator event; \
1.82 + IMetamodListener *api; \
1.83 + int mret = 0; \
1.84 + void *val = NULL; \
1.85 + for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
1.86 + pl = (*iter); \
1.87 + for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
1.88 + api = (*event).event; \
1.89 + mret = IFACE_FAILED; \
1.90 + if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
1.91 + if (ret) *ret = mret; \
1.92 + return val; \
1.93 + } \
1.94 + } \
1.95 + } \
1.96 + return (orig)(iface, ret);
1.97 +
1.98 +#define ITER_EVENT(evn, args) \
1.99 + CPluginManager::CPlugin *pl; \
1.100 + SourceHook::List<CPluginEventHandler>::iterator event; \
1.101 + IMetamodListener *api; \
1.102 + for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
1.103 + pl = (*iter); \
1.104 + for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
1.105 + api = (*event).event; \
1.106 + api->evn args; \
1.107 + } \
1.108 + }
1.109 +
1.110 +///////////////////////////////////
1.111 +// Main code for HL2 Interaction //
1.112 +///////////////////////////////////
1.113 +
1.114 +/* Initialize everything here */
1.115 +void InitMainStates()
1.116 +{
1.117 + char full_path[PATH_SIZE] = {0};
1.118 + GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path));
1.119 + g_BinPath.assign(full_path);
1.120 +
1.121 + /* Like Metamod, reload plugins at the end of the map.
1.122 + * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
1.123 + * if the server is shut down (silly, but rare case).
1.124 + */
1.125 + bInFirstLevel = true;
1.126 +
1.127 + SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
1.128 + SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
1.129 + SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
1.130 + SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
1.131 + SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
1.132 + SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
1.133 +}
1.134 +
1.135 +void DoInitialPluginLoads()
1.136 +{
1.137 + const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
1.138 + const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
1.139 +
1.140 + if (!pluginFile)
1.141 + {
1.142 + pluginFile = GetPluginsFile();
1.143 + }
1.144 + if (!mmBaseDir)
1.145 + {
1.146 + mmBaseDir = GetMetamodBaseDir();
1.147 + }
1.148 +
1.149 + char full_path[260];
1.150 +
1.151 + g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), pluginFile);
1.152 + LoadPluginsFromFile(full_path);
1.153 + g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), mmBaseDir);
1.154 + LookForVDFs(full_path);
1.155 +}
1.156 +
1.157 +bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
1.158 +{
1.159 + g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
1.160 +
1.161 + if (!g_Engine.engine)
1.162 + {
1.163 + Error("Could not find IVEngineServer! Metamod cannot load.");
1.164 + return false;
1.165 + }
1.166 + g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
1.167 + if (!g_Engine.icvar)
1.168 + {
1.169 + Error("Could not find ICvar! Metamod cannot load.");
1.170 + return false;
1.171 + }
1.172 +
1.173 + g_Engine.loaded = true;
1.174 +
1.175 + /* The Ship is the only game known at this time that uses the pre-Episode One engine */
1.176 + g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
1.177 +
1.178 + ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
1.179 +
1.180 + g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
1.181 + g_CvarPatch = SH_GET_CALLCLASS(g_Engine.icvar);
1.182 +
1.183 + if (g_GameDll.pGameClients)
1.184 + {
1.185 + SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
1.186 + }
1.187 + else
1.188 + {
1.189 + /* If IServerGameClients isn't found, this really isn't a fatal error so... */
1.190 + LogMessage("[META] Warning: Could not find IServerGameClients!");
1.191 + LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
1.192 + }
1.193 +
1.194 + if (!g_SmmAPI.CacheCmds())
1.195 + {
1.196 + LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
1.197 + LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
1.198 + }
1.199 +
1.200 + if (!g_SmmAPI.CacheUserMessages())
1.201 + {
1.202 + /* Don't know of a mod that has stripped out user messages completely,
1.203 + * but perhaps should do something different here?
1.204 + */
1.205 + LogMessage("[META] Warning: Failed to get list of user messages.");
1.206 + LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
1.207 + }
1.208 +
1.209 + baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
1.210 + if (baseFs == NULL)
1.211 + {
1.212 + LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
1.213 + }
1.214 +
1.215 + if (!g_SMConVarAccessor.InitConCommandBaseList())
1.216 + {
1.217 + /* This is very unlikely considering it's old engine */
1.218 + LogMessage("[META] Warning: Failed to find ConCommandBase list!");
1.219 + LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
1.220 + }
1.221 +
1.222 + if (!bWaitForGameInit)
1.223 + {
1.224 + DoInitialPluginLoads();
1.225 + bInFirstLevel = true;
1.226 + }
1.227 +
1.228 + return true;
1.229 +}
1.230 +
1.231 +bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
1.232 +{
1.233 + g_Engine.engineFactory = engineFactory;
1.234 + g_Engine.fileSystemFactory = filesystemFactory;
1.235 + g_Engine.physicsFactory = physicsFactory;
1.236 + g_Engine.pGlobals = pGlobals;
1.237 +
1.238 + StartupMetamod(engineFactory, false);
1.239 +
1.240 + RETURN_META_VALUE(MRES_IGNORED, true);
1.241 +}
1.242 +
1.243 +bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
1.244 +{
1.245 + g_Engine.engineFactory = ifaceFactory;
1.246 + g_Engine.fileSystemFactory = ifaceFactory;
1.247 + g_Engine.physicsFactory = ifaceFactory;
1.248 +
1.249 + IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
1.250 + if (playerInfoManager == NULL)
1.251 + {
1.252 + Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
1.253 + return false;
1.254 + }
1.255 +
1.256 + g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
1.257 +
1.258 + /* Now find the server */
1.259 + g_GameDll.factory = serverFactory;
1.260 + g_GameDll.lib = NULL;
1.261 +
1.262 + char gamedll_iface[] = "ServerGameDLL000";
1.263 + for (unsigned int i = 3; i <= 50; i++)
1.264 + {
1.265 + gamedll_iface[15] = '0' + i;
1.266 + g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
1.267 + if (g_GameDll.pGameDLL != NULL)
1.268 + {
1.269 + g_GameDllVersion = i;
1.270 + break;
1.271 + }
1.272 + }
1.273 +
1.274 + if (g_GameDll.pGameDLL == NULL)
1.275 + {
1.276 + Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
1.277 + return false;
1.278 + }
1.279 +
1.280 + char gameclients_iface[] = "ServerGameClients000";
1.281 + for (unsigned int i = 3; i <= 4; i++)
1.282 + {
1.283 + gameclients_iface[19] = '0' + i;
1.284 + g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
1.285 + if (g_GameDll.pGameClients != NULL)
1.286 + {
1.287 + break;
1.288 + }
1.289 + }
1.290 +
1.291 + char smm_path[PATH_SIZE];
1.292 + const char *game_dir;
1.293 + GetFileOfAddress((void *)AlternatelyLoadMetamod, smm_path, sizeof(smm_path));
1.294 + g_SmmPath.assign(smm_path);
1.295 +
1.296 + game_dir = CommandLine()->ParmValue("-game", "hl2");
1.297 + abspath(smm_path, game_dir);
1.298 + g_ModPath.assign(smm_path);
1.299 +
1.300 + InitMainStates();
1.301 +
1.302 + if (!StartupMetamod(ifaceFactory, true))
1.303 + {
1.304 + return false;
1.305 + }
1.306 +
1.307 + g_PluginMngr.SetAllLoaded();
1.308 +
1.309 + return true;
1.310 +}
1.311 +
1.312 +bool GameInit_handler()
1.313 +{
1.314 + if (bGameInit)
1.315 + {
1.316 + RETURN_META_VALUE(MRES_IGNORED, true);
1.317 + }
1.318 +
1.319 + if (g_SmmAPI.VSPEnabled() && !g_VspListener.IsRootLoadMethod())
1.320 + {
1.321 + g_SmmAPI.LoadAsVSP();
1.322 + }
1.323 +
1.324 + if (g_VspListener.IsRootLoadMethod())
1.325 + {
1.326 + DoInitialPluginLoads();
1.327 + //gaben
1.328 + }
1.329 +
1.330 + bGameInit = true;
1.331 +
1.332 + RETURN_META_VALUE(MRES_IGNORED, true);
1.333 +}
1.334 +
1.335 +bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
1.336 +{
1.337 + g_PluginMngr.SetAllLoaded();
1.338 + RETURN_META_VALUE(MRES_IGNORED, true);
1.339 +}
1.340 +
1.341 +/* This is where the magic happens */
1.342 +SMM_API void *CreateInterface(const char *iface, int *ret)
1.343 +{
1.344 + /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
1.345 + if (strcmp(iface, PLAPI_NAME) == 0)
1.346 + {
1.347 + Warning("Do not try loading Metamod:Source as a Metamod:Source plugin");
1.348 +
1.349 + if (ret)
1.350 + {
1.351 + *ret = IFACE_FAILED;
1.352 + }
1.353 +
1.354 + return NULL;
1.355 + }
1.356 +
1.357 + /* We check these separately because we can't reply
1.358 + * unless our interface version really matches.
1.359 + */
1.360 + if ((strcmp(iface, VSPIFACE_002) == 0)
1.361 + || strcmp(iface, VSPIFACE_001) == 0)
1.362 + {
1.363 + if (ret)
1.364 + {
1.365 + *ret = IFACE_OK;
1.366 + }
1.367 + return &g_VspListener;
1.368 + }
1.369 +
1.370 + /* If we're a VSP, bypass this by default */
1.371 + if (g_VspListener.IsRootLoadMethod())
1.372 + {
1.373 + IFACE_MACRO(g_GameDll.factory, GameDLL);
1.374 + }
1.375 +
1.376 + if (!gParsedGameInfo)
1.377 + {
1.378 + gParsedGameInfo = true;
1.379 + const char *gameDir = NULL;
1.380 + char gamePath[PATH_SIZE];
1.381 + char smmPath[PATH_SIZE];
1.382 +
1.383 + /* Get path to SourceMM DLL */
1.384 + if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
1.385 + {
1.386 + Error("GetFileOfAddress() failed! Metamod cannot load.\n");
1.387 + return NULL;
1.388 + }
1.389 +
1.390 + g_SmmPath.assign(smmPath);
1.391 +
1.392 + /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
1.393 + gameDir = CommandLine()->ParmValue("-game", "hl2");
1.394 +
1.395 + /* Get absolute path */
1.396 + abspath(gamePath, gameDir);
1.397 + g_ModPath.assign(gamePath);
1.398 +
1.399 + char tempPath[PATH_SIZE];
1.400 +
1.401 + /* Path to gameinfo.txt */
1.402 + g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
1.403 +
1.404 + FILE *fp = fopen(tempPath, "rt");
1.405 +
1.406 + if (!fp)
1.407 + {
1.408 + Error("Unable to open gameinfo.txt! Metamod cannot load.\n");
1.409 + return NULL;
1.410 + }
1.411 +
1.412 + char buffer[255];
1.413 + char key[128], val[128];
1.414 + size_t len = 0;
1.415 + bool search = false;
1.416 + bool gamebin = false;
1.417 + char *ptr;
1.418 + const char *lptr;
1.419 + char curPath[PATH_SIZE];
1.420 +
1.421 + getcwd(curPath, PATH_SIZE);
1.422 +
1.423 + while (!feof(fp))
1.424 + {
1.425 + buffer[0] = '\0';
1.426 + fgets(buffer, sizeof(buffer), fp);
1.427 + len = strlen(buffer);
1.428 + if (buffer[len-1] == '\n')
1.429 + buffer[--len] = '\0';
1.430 + UTIL_TrimComments(buffer);
1.431 + UTIL_TrimLeft(buffer);
1.432 + UTIL_TrimRight(buffer);
1.433 + if (stricmp(buffer, "SearchPaths") == 0)
1.434 + search = true;
1.435 + if (!search)
1.436 + continue;
1.437 + UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
1.438 + if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
1.439 + {
1.440 + if (stricmp(key, "Game") == 0)
1.441 + gamebin = false;
1.442 + else
1.443 + gamebin = true;
1.444 +
1.445 + if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
1.446 + {
1.447 + ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
1.448 + if (ptr[0] == '.')
1.449 + ptr++;
1.450 + lptr = g_ModPath.c_str();
1.451 + } else {
1.452 + ptr = val;
1.453 + lptr = curPath;
1.454 + }
1.455 +
1.456 + size_t ptr_len = strlen(ptr);
1.457 + if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
1.458 + ptr[--ptr_len] = '\0';
1.459 +
1.460 + /* No need to append "bin" if key is GameBin */
1.461 + if (gamebin)
1.462 + {
1.463 + g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
1.464 + } else if (!ptr[0]) {
1.465 + g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
1.466 + } else {
1.467 + g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
1.468 + }
1.469 +
1.470 + /* If not path to SourceMM... */
1.471 + if (!UTIL_PathCmp(smmPath, tempPath))
1.472 + {
1.473 + FILE *fp = fopen(tempPath, "rb");
1.474 + if (!fp)
1.475 + continue;
1.476 + //:TODO: Optimize this a bit!
1.477 + SourceHook::List<GameDllInfo *>::iterator iter;
1.478 + GameDllInfo *pCheck;
1.479 + bool found = false;
1.480 + for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
1.481 + {
1.482 + pCheck = (*iter);
1.483 + if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
1.484 + {
1.485 + if (UTIL_PathCmp(tempPath, buffer))
1.486 + {
1.487 + found = true;
1.488 + break;
1.489 + }
1.490 + }
1.491 + }
1.492 + if (found)
1.493 + continue;
1.494 + fclose(fp);
1.495 + HINSTANCE gamedll = dlmount(tempPath);
1.496 + if (gamedll == NULL)
1.497 + continue;
1.498 + CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
1.499 + if (fn == NULL)
1.500 + {
1.501 + dlclose(gamedll);
1.502 + continue;
1.503 + }
1.504 + GameDllInfo *pInfo = new GameDllInfo;
1.505 + pInfo->factory = fn;
1.506 + pInfo->lib = gamedll;
1.507 + pInfo->loaded = true;
1.508 + pInfo->pGameDLL = NULL;
1.509 + gamedll_list.push_back(pInfo);
1.510 + break;
1.511 + }
1.512 + }
1.513 + }
1.514 + fclose(fp);
1.515 + }
1.516 +
1.517 + if (!g_GameDll.loaded)
1.518 + {
1.519 + const char *str = "ServerGameDLL";
1.520 + size_t len = strlen(str);
1.521 +
1.522 + if (strncmp(iface, str, len) == 0)
1.523 + {
1.524 + /* This is the interface we want! Right now we support versions 3 through 8 */
1.525 + g_GameDllVersion = atoi(&(iface[len]));
1.526 + int sizeTooBig = 0; //rename this to sizeWrong in the future!
1.527 + if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
1.528 + {
1.529 + /* Maybe this will get used in the future */
1.530 + sizeTooBig = g_GameDllVersion;
1.531 + if (ret)
1.532 + {
1.533 + *ret = IFACE_FAILED;
1.534 + }
1.535 + }
1.536 + SourceHook::List<GameDllInfo *>::iterator iter;
1.537 + GameDllInfo *pInfo = NULL;
1.538 + void *ptr;
1.539 + for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
1.540 + {
1.541 + pInfo = (*iter);
1.542 + ptr = (pInfo->factory)(iface, ret);
1.543 + if (ptr)
1.544 + {
1.545 + /* This is our GameDLL. Unload the others. */
1.546 + gamedll_list.erase(iter);
1.547 + ClearGamedllList();
1.548 + pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
1.549 + g_GameDll = *pInfo;
1.550 + delete pInfo;
1.551 + break;
1.552 + }
1.553 + }
1.554 + if (g_GameDll.loaded)
1.555 + {
1.556 + if (sizeTooBig)
1.557 + {
1.558 + Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
1.559 + if (ret)
1.560 + {
1.561 + *ret = IFACE_FAILED;
1.562 + }
1.563 + return NULL;
1.564 + } else {
1.565 + InitMainStates();
1.566 + }
1.567 + } else {
1.568 + sizeTooBig = 0;
1.569 + if (ret)
1.570 + *ret = IFACE_FAILED;
1.571 + return NULL;
1.572 + }
1.573 + } else {
1.574 + /* wtf do we do... */
1.575 + /* :TODO: .. something a bit more intelligent? */
1.576 + Error("Engine requested unknown interface before GameDLL was known!\n");
1.577 + return NULL;
1.578 + }
1.579 + }
1.580 +
1.581 + /* We use this interface for responding to the meta client command */
1.582 + if (strncmp(iface, "ServerGameClients", 17) == 0)
1.583 + {
1.584 + void *ptr = (g_GameDll.factory)(iface, ret);
1.585 + g_GameDll.pGameClients = static_cast<IServerGameClients *>(ptr);
1.586 +
1.587 + return ptr;
1.588 + }
1.589 +
1.590 + /* If we got here, there's definitely a GameDLL */
1.591 + IFACE_MACRO(g_GameDll.factory, GameDLL);
1.592 +}
1.593 +
1.594 +void ClearGamedllList()
1.595 +{
1.596 + SourceHook::List<GameDllInfo *>::iterator iter;
1.597 +
1.598 + GameDllInfo *pInfo;
1.599 + for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
1.600 + {
1.601 + pInfo = (*iter);
1.602 + dlclose(pInfo->lib);
1.603 + delete pInfo;
1.604 + }
1.605 +
1.606 + gamedll_list.clear();
1.607 +}
1.608 +
1.609 +void UnloadMetamod(bool shutting_down)
1.610 +{
1.611 + /* Unload plugins */
1.612 + g_PluginMngr.UnloadAll();
1.613 +
1.614 + if (shutting_down)
1.615 + {
1.616 + /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
1.617 + g_SMConVarAccessor.MarkCommandsAsGameDLL();
1.618 + g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
1.619 +
1.620 + SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
1.621 + }
1.622 +
1.623 + SH_RELEASE_CALLCLASS(g_GameDllPatch);
1.624 + SH_RELEASE_CALLCLASS(g_CvarPatch);
1.625 + g_GameDllPatch = NULL;
1.626 + g_CvarPatch = NULL;
1.627 +
1.628 + g_SourceHook.CompleteShutdown();
1.629 +
1.630 + if (g_GameDll.lib && g_GameDll.loaded)
1.631 + {
1.632 + dlclose(g_GameDll.lib);
1.633 + }
1.634 + memset(&g_GameDll, 0, sizeof(GameDllInfo));
1.635 +}
1.636 +
1.637 +void DLLShutdown_handler()
1.638 +{
1.639 + UnloadMetamod(true);
1.640 + RETURN_META(MRES_SUPERCEDE);
1.641 +}
1.642 +
1.643 +void LoadFromVDF(const char *file)
1.644 +{
1.645 + PluginId id;
1.646 + bool already, kvfileLoaded;
1.647 + KeyValues *pValues;
1.648 + const char *plugin_file, *alias;
1.649 + char full_path[256], error[256];
1.650 +
1.651 + pValues = new KeyValues("Metamod Plugin");
1.652 +
1.653 + if (g_Engine.original)
1.654 + {
1.655 + /* The Ship must use a special version of this function */
1.656 + kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
1.657 + }
1.658 + else
1.659 + {
1.660 + kvfileLoaded = pValues->LoadFromFile(baseFs, file);
1.661 + }
1.662 +
1.663 + if (!kvfileLoaded)
1.664 + {
1.665 + pValues->deleteThis();
1.666 + return;
1.667 + }
1.668 +
1.669 + if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
1.670 + {
1.671 + pValues->deleteThis();
1.672 + return;
1.673 + }
1.674 +
1.675 + if ((alias = pValues->GetString("alias", NULL)) != NULL)
1.676 + {
1.677 + g_PluginMngr.SetAlias(alias, plugin_file);
1.678 + }
1.679 +
1.680 + /* Attempt to find a file extension */
1.681 + if (UTIL_GetExtension(plugin_file) == NULL)
1.682 + {
1.683 + g_SmmAPI.PathFormat(full_path,
1.684 + sizeof(full_path),
1.685 + "%s/%s%s",
1.686 + g_ModPath.c_str(),
1.687 + plugin_file,
1.688 +#if defined WIN32 || defined _WIN32
1.689 + ".dll"
1.690 +#else
1.691 + "_i486.so"
1.692 +#endif
1.693 + );
1.694 + }
1.695 + else
1.696 + {
1.697 + g_SmmAPI.PathFormat(full_path,
1.698 + sizeof(full_path),
1.699 + "%s/%s",
1.700 + g_ModPath.c_str(),
1.701 + plugin_file);
1.702 + }
1.703 +
1.704 + id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
1.705 + if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1.706 + {
1.707 + LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
1.708 + }
1.709 +
1.710 + pValues->deleteThis();
1.711 +}
1.712 +
1.713 +void LookForVDFs(const char *dir)
1.714 +{
1.715 + char path[MAX_PATH];
1.716 + int extidx;
1.717 +
1.718 +#if defined _MSC_VER
1.719 + HANDLE hFind;
1.720 + WIN32_FIND_DATA fd;
1.721 + char error[255];
1.722 +
1.723 + g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.*", dir);
1.724 + if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
1.725 + {
1.726 + DWORD dw = GetLastError();
1.727 + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
1.728 + NULL,
1.729 + dw,
1.730 + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1.731 + error,
1.732 + sizeof(error),
1.733 + NULL);
1.734 + LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
1.735 + return;
1.736 + }
1.737 +
1.738 + do
1.739 + {
1.740 + if (strcmp(fd.cFileName, ".") == 0
1.741 + || strcmp(fd.cFileName, "..") == 0)
1.742 + {
1.743 + continue;
1.744 + }
1.745 + extidx = strlen(fd.cFileName) - 4;
1.746 + if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1.747 + {
1.748 + continue;
1.749 + }
1.750 + g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
1.751 + LoadFromVDF(path);
1.752 + } while (FindNextFile(hFind, &fd));
1.753 +
1.754 + FindClose(hFind);
1.755 +#else
1.756 + DIR *pDir;
1.757 + struct dirent *pEnt;
1.758 +
1.759 + if ((pDir = opendir(dir)) == NULL)
1.760 + {
1.761 + LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
1.762 + return;
1.763 + }
1.764 +
1.765 + while ((pEnt = readdir(pDir)) != NULL)
1.766 + {
1.767 + if (strcmp(pEnt->d_name, ".") == 0
1.768 + || strcmp(pEnt->d_name, "..") == 0)
1.769 + {
1.770 + continue;
1.771 + }
1.772 + extidx = strlen(pEnt->d_name) - 4;
1.773 + if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
1.774 + {
1.775 + continue;
1.776 + }
1.777 + g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
1.778 + LoadFromVDF(path);
1.779 + }
1.780 +
1.781 + closedir(pDir);
1.782 +#endif
1.783 +}
1.784 +
1.785 +bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
1.786 +{
1.787 + Assert(filesystem);
1.788 +#ifdef _MSC_VER
1.789 + Assert(_heapchk() == _HEAPOK);
1.790 +#endif
1.791 +
1.792 + FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
1.793 + if (!f)
1.794 + return false;
1.795 +
1.796 + // load file into a null-terminated buffer
1.797 + int fileSize = filesystem->Size(f);
1.798 + char *buffer = (char *)MemAllocScratch(fileSize + 1);
1.799 +
1.800 + Assert(buffer);
1.801 +
1.802 + filesystem->Read(buffer, fileSize, f); // read into local buffer
1.803 +
1.804 + buffer[fileSize] = 0; // null terminate file as EOF
1.805 +
1.806 + filesystem->Close( f ); // close file after reading
1.807 +
1.808 + bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
1.809 +
1.810 + MemFreeScratch();
1.811 +
1.812 + return retOK;
1.813 +}
1.814 +
1.815 +int LoadPluginsFromFile(const char *_file)
1.816 +{
1.817 + FILE *fp;
1.818 + int total = 0, skipped=0;
1.819 + PluginId id;
1.820 + bool already;
1.821 +
1.822 + fp = fopen(_file, "rt");
1.823 + if (!fp)
1.824 + {
1.825 + LogMessage("[META] Could not open plugins file %s\n", _file);
1.826 + return -1;
1.827 + }
1.828 +
1.829 + char buffer[255], error[255], full_path[255];
1.830 + const char *ptr, *ext, *file;
1.831 + size_t length;
1.832 + while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
1.833 + {
1.834 + UTIL_TrimLeft(buffer);
1.835 + UTIL_TrimRight(buffer);
1.836 +
1.837 + length = strlen(buffer);
1.838 + if (!length)
1.839 + {
1.840 + continue;
1.841 + }
1.842 +
1.843 + if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
1.844 + {
1.845 + continue;
1.846 + }
1.847 +
1.848 + file = buffer;
1.849 + if (buffer[0] == '"')
1.850 + {
1.851 + char *cptr = buffer;
1.852 + file = ++cptr;
1.853 +
1.854 + while (*cptr)
1.855 + {
1.856 + if (*cptr == '"')
1.857 + {
1.858 + *cptr = '\0';
1.859 + break;
1.860 + }
1.861 + cptr++;
1.862 + }
1.863 + }
1.864 + else
1.865 + {
1.866 + char *cptr = buffer;
1.867 + while (*cptr)
1.868 + {
1.869 + if (isspace(*cptr))
1.870 + {
1.871 + char *optr = cptr;
1.872 + while (*cptr && isspace(*cptr))
1.873 + {
1.874 + cptr++;
1.875 + }
1.876 + *optr = '\0';
1.877 + UTIL_TrimRight(cptr);
1.878 + if (*cptr && isalpha(*cptr))
1.879 + {
1.880 + g_PluginMngr.SetAlias(buffer, cptr);
1.881 + file = cptr;
1.882 + }
1.883 + break;
1.884 + }
1.885 + cptr++;
1.886 + }
1.887 + }
1.888 + if (!file[0])
1.889 + {
1.890 + continue;
1.891 + }
1.892 + /* First find if it's an absolute path or not... */
1.893 + if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
1.894 + {
1.895 + /* If we're in an absolute path, ignore our normal heuristics */
1.896 + id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
1.897 + if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1.898 + {
1.899 + LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
1.900 + }
1.901 + else
1.902 + {
1.903 + if (already)
1.904 + {
1.905 + skipped++;
1.906 + }
1.907 + else
1.908 + {
1.909 + total++;
1.910 + }
1.911 + }
1.912 + }
1.913 + else
1.914 + {
1.915 + /* Attempt to find a file extension */
1.916 + ptr = UTIL_GetExtension(file);
1.917 + /* Add an extension if there's none there */
1.918 + if (!ptr)
1.919 + {
1.920 +#if defined WIN32 || defined _WIN32
1.921 + ext = ".dll";
1.922 +#else
1.923 + ext = "_i486.so";
1.924 +#endif
1.925 + }
1.926 + else
1.927 + {
1.928 + ext = "";
1.929 + }
1.930 + /* Format the new path */
1.931 + g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
1.932 + id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
1.933 + if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1.934 + {
1.935 + LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
1.936 + }
1.937 + else
1.938 + {
1.939 + if (already)
1.940 + {
1.941 + skipped++;
1.942 + }
1.943 + else
1.944 + {
1.945 + total++;
1.946 + }
1.947 + }
1.948 + }
1.949 + }
1.950 + fclose(fp);
1.951 +
1.952 + if (skipped)
1.953 + {
1.954 + LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
1.955 + }
1.956 + else
1.957 + {
1.958 + LogMessage("[META] Loaded %d plugins from file.", total);
1.959 + }
1.960 +
1.961 + return total;
1.962 +}
1.963 +
1.964 +
1.965 +/* Wrapper function. This is called when the GameDLL thinks it's using
1.966 + * the engine's real engineFactory.
1.967 + */
1.968 +void *EngineFactory(const char *iface, int *ret)
1.969 +{
1.970 + IFACE_MACRO(g_Engine.engineFactory, Engine);
1.971 +}
1.972 +
1.973 +/* Wrapper function. This is called when the GameDLL thinks it's using
1.974 + * the engine's real physicsFactory.
1.975 + */
1.976 +void *PhysicsFactory(const char *iface, int *ret)
1.977 +{
1.978 + IFACE_MACRO(g_Engine.physicsFactory, Physics);
1.979 +}
1.980 +
1.981 +/* Wrapper function. This is called when the GameDLL thinks it's using
1.982 + * the engine's real fileSystemFactory.
1.983 + */
1.984 +void *FileSystemFactory(const char *iface, int *ret)
1.985 +{
1.986 + IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
1.987 +}
1.988 +
1.989 +void LogMessage(const char *msg, ...)
1.990 +{
1.991 + va_list ap;
1.992 + static char buffer[2048];
1.993 +
1.994 + va_start(ap, msg);
1.995 + size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
1.996 + va_end(ap);
1.997 +
1.998 + buffer[len++] = '\n';
1.999 + buffer[len] = '\0';
1.1000 +
1.1001 + if (!g_Engine.engine)
1.1002 + {
1.1003 + fprintf(stdout, "%s", buffer);
1.1004 + } else {
1.1005 + g_Engine.engine->LogPrint(buffer);
1.1006 + }
1.1007 +}
1.1008 +
1.1009 +void LevelShutdown_handler(void)
1.1010 +{
1.1011 + if (!bInFirstLevel)
1.1012 + {
1.1013 + char full_path[255];
1.1014 +
1.1015 + g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
1.1016 + LoadPluginsFromFile(full_path);
1.1017 +
1.1018 + g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
1.1019 + LookForVDFs(full_path);
1.1020 + }
1.1021 + else
1.1022 + {
1.1023 + bInFirstLevel = false;
1.1024 + }
1.1025 +
1.1026 + g_bLevelChanged = true;
1.1027 +
1.1028 + ITER_EVENT(OnLevelShutdown, ());
1.1029 +
1.1030 + RETURN_META(MRES_IGNORED);
1.1031 +}
1.1032 +
1.1033 +bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
1.1034 +{
1.1035 + if (!g_SmmAPI.CmdCacheSuccessful())
1.1036 + {
1.1037 + LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
1.1038 + LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
1.1039 + }
1.1040 +
1.1041 + ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
1.1042 +
1.1043 + RETURN_META_VALUE(MRES_IGNORED, false);
1.1044 +}
1.1045 +
1.1046 +#if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
1.1047 +void * operator new(size_t size) {
1.1048 + return(calloc(1, size));
1.1049 +}
1.1050 +
1.1051 +void * operator new[](size_t size) {
1.1052 + return(calloc(1, size));
1.1053 +}
1.1054 +
1.1055 +void operator delete(void * ptr) {
1.1056 + if(ptr)
1.1057 + free(ptr);
1.1058 +}
1.1059 +
1.1060 +void operator delete[](void * ptr) {
1.1061 + if(ptr)
1.1062 + free(ptr);
1.1063 +}
1.1064 +#endif