core/metamod.cpp
author Scott Ehlert <ds@alliedmods.net>
Mon Nov 17 00:57:17 2008 -0600 (2008-11-17)
changeset 557 0a8ad2b12708
parent 554 40c8522a2a75
child 558 0ed2a4a6e31d
permissions -rw-r--r--
Added Windows support for loader, core, and core-legacy
     1 /**
     2  * vim: set ts=4 :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2008 AlliedModders LLC and authors.
     6  * All rights reserved.
     7  * ======================================================
     8  *
     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.
    12  * 
    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:
    16  *
    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.
    24  *
    25  * Version: $Id$
    26  */
    27 
    28 #include <stdio.h>
    29 #include "metamod_oslink.h"
    30 #include "metamod.h"
    31 #include <interface.h>
    32 #include <eiface.h>
    33 #include "metamod_provider.h"
    34 #include "metamod_plugins.h"
    35 #include "metamod_util.h"
    36 #include "metamod_console.h"
    37 #include "provider/provider_ep2.h"
    38 
    39 using namespace SourceMM;
    40 using namespace SourceHook;
    41 using namespace SourceHook::Impl;
    42 
    43 /**
    44  * @brief Implementation of main SourceMM GameDLL functionality
    45  * @file sourcemm.cpp
    46  */
    47 
    48 SH_DECL_MANUALHOOK4(SGD_DLLInit, 0, 0, 0, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
    49 SH_DECL_MANUALHOOK0(SGD_GameInit, 0, 0, 0, bool);
    50 SH_DECL_MANUALHOOK6(SGD_LevelInit, 0, 0, 0, bool, const char *, const char *, const char *, const char *, bool, bool);
    51 SH_DECL_MANUALHOOK0_void(SGD_LevelShutdown, 0, 0, 0);
    52 SH_DECL_MANUALHOOK0_void(SGD_DLLShutdown, 0, 0, 0);
    53 
    54 static bool
    55 Handler_DLLInit(CreateInterfaceFn engineFactory,
    56 				CreateInterfaceFn physicsFactory,
    57 				CreateInterfaceFn filesystemFactory,
    58 				CGlobalVars *pGlobals);
    59 
    60 static bool
    61 Handler_DLLInit_Post(CreateInterfaceFn engineFactory,
    62 					 CreateInterfaceFn physicsFactory,
    63 					 CreateInterfaceFn filesystemFactory,
    64 					 CGlobalVars *pGlobals);
    65 
    66 static void
    67 Handler_DLLShutdown();
    68 
    69 static void
    70 Handler_LevelShutdown();
    71 
    72 static bool
    73 Handler_LevelInit(char const *pMapName,
    74 				  char const *pMapEntities,
    75 				  char const *pOldLevel,
    76 				  char const *pLandmarkName,
    77 				  bool loadGame,
    78 				  bool background);
    79 
    80 static bool
    81 Handler_GameInit();
    82 
    83 static void
    84 InitializeVSP();
    85 
    86 static void
    87 LookForVDFs(const char *dir);
    88 
    89 struct game_dll_t
    90 {
    91 	HINSTANCE lib;
    92 	CreateInterfaceFn factory;
    93 };
    94 
    95 static String mod_path;
    96 static String metamod_path;
    97 static String full_bin_path;
    98 static bool parsed_game_info = false;
    99 static int vsp_version = 0;
   100 static int gamedll_version = 0;
   101 static int engine_build = SOURCE_ENGINE_UNKNOWN;
   102 static List<game_dll_t *> gamedll_list;
   103 static bool is_gamedll_loaded = false;
   104 static bool in_first_level = true;
   105 static bool is_game_init = false;
   106 static bool vsp_load_requested = false;
   107 static bool vsp_loaded = false;
   108 static game_dll_t gamedll_info;
   109 static ConVar *metamod_version = NULL;
   110 static ConVar *mm_pluginsfile = NULL;
   111 static ConVar *mm_basedir = NULL;
   112 static CreateInterfaceFn engine_factory = NULL;
   113 static CreateInterfaceFn physics_factory = NULL;
   114 static CreateInterfaceFn filesystem_factory = NULL;
   115 static CGlobalVars *gpGlobals = NULL;
   116 static CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
   117 static META_RES last_meta_res;
   118 static IServerPluginCallbacks *vsp_callbacks = NULL;
   119 static bool were_plugins_loaded = false;
   120 static bool g_bIsVspBridged = false;
   121 
   122 MetamodSource g_Metamod;
   123 PluginId g_PLID = Pl_Console;
   124 CSourceHookImpl g_SourceHook;
   125 ISourceHook *g_SHPtr = &g_SourceHook;
   126 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
   127 
   128 static void
   129 ClearGamedllList();
   130 
   131 /* Helper Macro */
   132 #define	IFACE_MACRO(orig,nam) \
   133 	CPluginManager::CPlugin *pl; \
   134 	SourceHook::List<IMetamodListener *>::iterator event; \
   135 	IMetamodListener *api; \
   136 	int mret = 0; \
   137 	void *val = NULL; \
   138 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   139 		pl = (*iter); \
   140 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   141 			api = (*event); \
   142 			mret = IFACE_FAILED; \
   143 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
   144 				if (ret) *ret = mret; \
   145 				return val; \
   146 			} \
   147 		} \
   148 	} \
   149 	return (orig)(iface, ret);
   150 
   151 #define ITER_EVENT(evn, args) \
   152 	CPluginManager::CPlugin *pl; \
   153 	SourceHook::List<IMetamodListener *>::iterator event; \
   154 	IMetamodListener *api; \
   155 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   156 		pl = (*iter); \
   157 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   158 			api = (*event); \
   159 			api->evn args; \
   160 		} \
   161 	}
   162 
   163 void
   164 mm_SetVspInfo(IServerPluginCallbacks *ispc, unsigned int version)
   165 {
   166 	vsp_version = version;
   167 }
   168 
   169 /* Initialize everything here */
   170 void
   171 mm_InitializeForLoad()
   172 {
   173 	char full_path[PATH_SIZE] = {0};
   174 	GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
   175 	full_bin_path.assign(full_path);
   176 
   177 	/* Like Metamod, reload plugins at the end of the map.
   178 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   179 	 * if the server is shut down (silly, but rare case).
   180 	 */
   181 	in_first_level = true;
   182 
   183 	SourceHook::MemFuncInfo info;
   184 
   185 	if (!provider->GetHookInfo(ProvidedHook_DLLInit, &info))
   186 	{
   187 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLInit");
   188 	}
   189 	SH_MANUALHOOK_RECONFIGURE(SGD_DLLInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   190 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit, false);
   191 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit_Post, true);
   192 
   193 	if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
   194 	{
   195 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
   196 	}
   197 	SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   198 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
   199 
   200 	if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
   201 	{
   202 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
   203 	}
   204 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   205 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
   206 
   207 	if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
   208 	{
   209 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
   210 	}
   211 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
   212 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
   213 
   214 	if (!provider->GetHookInfo(ProvidedHook_DLLShutdown, &info))
   215 	{
   216 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLShutdown");
   217 	}
   218 	SH_MANUALHOOK_RECONFIGURE(SGD_DLLShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
   219 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLShutdown, server, Handler_DLLShutdown, false);
   220 }
   221 
   222 bool
   223 mm_DetectGameInformation()
   224 {
   225 	char mm_path[PATH_SIZE];
   226 	char game_path[PATH_SIZE];
   227 
   228 	/* Get path to SourceMM DLL */
   229 	if (!GetFileOfAddress((void *)mm_InitializeForLoad, mm_path, sizeof(mm_path)))
   230 	{
   231 		return false;
   232 	}
   233 
   234 	metamod_path.assign(mm_path);
   235 
   236 	/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   237 	const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
   238 
   239 	/* Get absolute path */
   240 	abspath(game_path, game_dir);
   241 	mod_path.assign(game_path);
   242 
   243 	engine_build = provider->DetermineSourceEngine(game_dir);;
   244 
   245 	return true;
   246 }
   247 
   248 /* This is where the magic happens */
   249 SMM_API void *
   250 CreateInterface(const char *iface, int *ret)
   251 {
   252 	/* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
   253 	if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
   254 	{
   255 		provider->DisplayWarning("Do not try loading Metamod:Source as a plugin.\n");
   256 
   257 		if (ret)
   258 		{
   259 			*ret = IFACE_FAILED;
   260 		}
   261 
   262 		return NULL;
   263 	}
   264 
   265 	if (!g_bIsVspBridged && strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
   266 	{
   267 		if (vsp_callbacks != NULL && atoi(&iface[22]) != vsp_version)
   268 		{
   269 			if (ret != NULL)
   270 				*ret = IFACE_FAILED;
   271 			return NULL;
   272 		}
   273 
   274 		vsp_version = atoi(&iface[22]);
   275 		vsp_callbacks = provider->GetVSPCallbacks(vsp_version);
   276 
   277 		if (ret)
   278 			*ret = (vsp_callbacks != NULL) ? IFACE_OK : IFACE_FAILED;
   279 
   280 		if (vsp_callbacks == NULL)
   281 			vsp_version = 0;
   282 
   283 		return vsp_callbacks;
   284 	}
   285 
   286 	if (g_bIsVspBridged)
   287 	{
   288 		IFACE_MACRO(gamedll_info.factory, GameDLL);
   289 	}
   290 
   291 	if (!parsed_game_info)
   292 	{
   293 		parsed_game_info = true;
   294 
   295 		if (!mm_DetectGameInformation())
   296 		{
   297 			provider->DisplayError("GetFileOfAddress() failed! Metamod cannot load.\n");
   298 			return NULL;
   299 		}
   300 
   301 		char temp_path[PATH_SIZE];
   302 
   303 		/* Path to gameinfo.txt */
   304 		g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s", mod_path.c_str(), "gameinfo.txt");
   305 
   306 		FILE *fp = fopen(temp_path, "rt");
   307 
   308 		if (!fp)
   309 		{
   310 			provider->DisplayError("Unable to open gameinfo.txt!  Metamod cannot load.\n");
   311 			return NULL;
   312 		}
   313 
   314 		char buffer[255];
   315 		char key[128], val[128];
   316 		bool search = false;
   317 		bool gamebin = false;
   318 		char *ptr;
   319 		const char *lptr;
   320 		char cur_path[PATH_SIZE];
   321 
   322 		getcwd(cur_path, PATH_SIZE);
   323 
   324 		while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   325 		{
   326 			UTIL_TrimComments(buffer);
   327 			UTIL_TrimLeft(buffer);
   328 			UTIL_TrimRight(buffer);
   329 
   330 			if (stricmp(buffer, "SearchPaths") == 0)
   331 			{
   332 				search = true;
   333 			}
   334 
   335 			if (!search)
   336 			{
   337 				continue;
   338 			}
   339 
   340 			UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   341 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   342 			{
   343 				if (stricmp(key, "Game") == 0)
   344 				{
   345 					gamebin = false;
   346 				}
   347 				else
   348 				{
   349 					gamebin = true;
   350 				}
   351 
   352 				if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
   353 				{
   354 					ptr = &(val[sizeof("|gameinfo_path|") - 1]);
   355 					if (ptr[0] == '.')
   356 					{
   357 						ptr++;
   358 					}
   359 					lptr = mod_path.c_str();
   360 				} else {
   361 					ptr = val;
   362 					lptr = cur_path;
   363 				}
   364 
   365 				size_t ptr_len = strlen(ptr);
   366 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   367 				{
   368 					ptr[--ptr_len] = '\0';
   369 				}
   370 
   371 				/* No need to append "bin" if key is GameBin */
   372 				if (gamebin)
   373 				{
   374 					g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   375 				}
   376 				else if (!ptr[0])
   377 				{
   378 					g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
   379 				}
   380 				else
   381 				{
   382 					g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   383 				}
   384 
   385 				/* If not path to SourceMM... */
   386 				if (!UTIL_PathCmp(metamod_path.c_str(), temp_path))
   387 				{
   388 					FILE *temp_fp = fopen(temp_path, "rb");
   389 					if (!temp_fp)
   390 					{
   391 						continue;
   392 					}
   393 					fclose(temp_fp);
   394 
   395 					/* Search for a matching game dll */
   396 					List<game_dll_t *>::iterator iter;
   397 					game_dll_t *pCheck;
   398 					bool found = false;
   399 					for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
   400 					{
   401 						pCheck = (*iter);
   402 						if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
   403 						{
   404 							if (UTIL_PathCmp(temp_path, buffer))
   405 							{
   406 								found = true;
   407 								break;
   408 							}
   409 						}
   410 					}
   411 
   412 					if (found)
   413 					{
   414 						continue;
   415 					}
   416 					
   417 					HINSTANCE gamedll = dlmount(temp_path);
   418 					if (gamedll == NULL)
   419 					{
   420 						continue;
   421 					}
   422 
   423 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   424 					if (fn == NULL)
   425 					{
   426 						dlclose(gamedll);
   427 						continue;
   428 					}
   429 
   430 					game_dll_t *pInfo = new game_dll_t;
   431 					pInfo->factory = fn;
   432 					pInfo->lib = gamedll;
   433 					gamedll_list.push_back(pInfo);
   434 					break;
   435 				}
   436 			}
   437 		}
   438 		fclose(fp);
   439 	}
   440 
   441 	if (!is_gamedll_loaded)
   442 	{
   443 		if (strncmp(iface, "ServerGameDLL", 13) == 0)
   444 		{
   445 			List<game_dll_t *>::iterator iter;
   446 			game_dll_t *pInfo;
   447 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   448 			{
   449 				pInfo = (*iter);
   450 				if ((server = (IServerGameDLL *)((pInfo->factory)(iface, ret))) != NULL)
   451 				{
   452 					if ((gamedll_version = provider->TryServerGameDLL(iface)) != 0)
   453 					{
   454 						/* We have a match.  Erase us from the list and save our info. */
   455 						gamedll_list.erase(iter);
   456 						gamedll_info = *pInfo;
   457 						delete pInfo;
   458 						is_gamedll_loaded = true;
   459 						break;
   460 					}
   461 					/* :TODO: error otherwise? */
   462 				}
   463 			}
   464 
   465 			if (is_gamedll_loaded)
   466 			{
   467 				ClearGamedllList();
   468 				mm_InitializeForLoad();
   469 			}
   470 			else
   471 			{
   472 				if (ret)
   473 				{
   474 					*ret = IFACE_FAILED;
   475 				}
   476 				return NULL;
   477 			}
   478 		}
   479 		else
   480 		{
   481 			/* wtf do we do... */
   482 			/* :TODO: .. something a bit more intelligent? */
   483 			provider->DisplayError("Engine requested unknown interface before GameDLL was known!\n");
   484 			return NULL;
   485 		}
   486 	}
   487 
   488 	/* If we got here, there's definitely a GameDLL */
   489 	IFACE_MACRO(gamedll_info.factory, GameDLL);
   490 }
   491 
   492 static void
   493 ClearGamedllList()
   494 {
   495 	List<game_dll_t *>::iterator iter;
   496 
   497 	game_dll_t *pInfo;
   498 	for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
   499 	{
   500 		pInfo = (*iter);
   501 		dlclose(pInfo->lib);
   502 		delete pInfo;
   503 	}
   504 
   505 	gamedll_list.clear();
   506 }
   507 
   508 int
   509 mm_LoadPluginsFromFile(const char *_file)
   510 {
   511 	FILE *fp;
   512 	int total = 0, skipped=0;
   513 	PluginId id;
   514 	bool already;
   515 
   516 	fp = fopen(_file, "rt");
   517 	if (!fp)
   518 	{
   519 		mm_LogMessage("[META] Could not open plugins file %s\n", _file);
   520 		return -1;
   521 	}
   522 
   523 	char buffer[255], error[255], full_path[255];
   524 	const char *ptr, *ext, *file;
   525 	size_t length;
   526 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   527 	{
   528 		UTIL_TrimLeft(buffer);
   529 		UTIL_TrimRight(buffer);
   530 
   531 		length = strlen(buffer);
   532 		if (!length)
   533 		{
   534 			continue;
   535 		}
   536 
   537 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   538 		{
   539 			continue;
   540 		}
   541 
   542 		file = buffer;
   543 		if (buffer[0] == '"')
   544 		{
   545 			char *cptr = buffer;
   546 			file = ++cptr;
   547 
   548 			while (*cptr)
   549 			{
   550 				if (*cptr == '"')
   551 				{
   552 					*cptr = '\0';
   553 					break;
   554 				}
   555 				cptr++;
   556 			}
   557 		}
   558 		else
   559 		{
   560 			char *cptr = buffer;
   561 			while (*cptr)
   562 			{
   563 				if (isspace(*cptr))
   564 				{
   565 					char *optr = cptr;
   566 					while (*cptr && isspace(*cptr))
   567 					{
   568 						cptr++;
   569 					}
   570 					*optr = '\0';
   571 					UTIL_TrimRight(cptr);
   572 					if (*cptr && isalpha(*cptr))
   573 					{
   574 						g_PluginMngr.SetAlias(buffer, cptr);
   575 						file = cptr;
   576 					}
   577 					break;
   578 				}
   579 				cptr++;
   580 			}
   581 		}
   582 		if (!file[0])
   583 		{
   584 			continue;
   585 		}
   586 		/* First find if it's an absolute path or not... */
   587 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   588 		{
   589 			/* If we're in an absolute path, ignore our normal heuristics */
   590 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   591 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   592 			{
   593 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   594 			}
   595 			else
   596 			{
   597 				if (already)
   598 					skipped++;
   599 				else
   600 					total++;
   601 			}
   602 		}
   603 		else
   604 		{
   605 			/* Attempt to find a file extension */
   606 			ptr = UTIL_GetExtension(file);
   607 			/* Add an extension if there's none there */
   608 			if (!ptr)
   609 			{
   610 #if defined WIN32 || defined _WIN32
   611 				ext = ".dll";
   612 #else
   613 				ext = "_i486.so";
   614 #endif
   615 			}
   616 			else
   617 			{
   618 				ext = "";
   619 			}
   620 			/* Format the new path */
   621 			g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
   622 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   623 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   624 			{
   625 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   626 			}
   627 			else
   628 			{
   629 				if (already)
   630 					skipped++;
   631 				else
   632 					total++;
   633 			}
   634 		}
   635 	}
   636 	fclose(fp);
   637 
   638 	if (skipped)
   639 		mm_LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   640 	else
   641 		mm_LogMessage("[META] Loaded %d plugins from file.", total);
   642 	
   643 	return total;
   644 }
   645 
   646 void InitializeVSP()
   647 {
   648 	if (g_bIsVspBridged)
   649 		return;
   650 
   651 	size_t len;
   652 	char engine_file[PATH_SIZE];
   653 	char engine_path[PATH_SIZE];
   654 	char rel_path[PATH_SIZE * 2];
   655 
   656 	GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
   657 
   658 	/* Chop off the "engine" file part */
   659 	len = strlen(engine_file);
   660 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   661 	{
   662 		if (engine_file[i] == '/' || engine_file[i] == '\\')
   663 		{
   664 			engine_file[i] = '\0';
   665 			break;
   666 		}
   667 	}
   668 	abspath(engine_path, engine_file);
   669 
   670 	const char *usepath = metamod_path.c_str();
   671 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
   672 	{
   673 		usepath = rel_path;
   674 	}
   675 
   676 	char command[PATH_SIZE * 2];
   677 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   678 	provider->ServerCommand(command);
   679 }
   680 
   681 /* Wrapper function.  This is called when the GameDLL thinks it's using
   682  * the engine's real engineFactory.
   683  */
   684 static void *
   685 EngineFactory(const char *iface, int *ret)
   686 {
   687 	IFACE_MACRO(engine_factory, Engine);
   688 }
   689 
   690 /* Wrapper function.  This is called when the GameDLL thinks it's using
   691  * the engine's real physicsFactory.
   692  */
   693 static void *
   694 PhysicsFactory(const char *iface, int *ret)
   695 {
   696 	IFACE_MACRO(physics_factory, Physics);
   697 }
   698 
   699 /* Wrapper function.  This is called when the GameDLL thinks it's using
   700  * the engine's real fileSystemFactory.
   701  */
   702 static void *
   703 FileSystemFactory(const char *iface, int *ret)
   704 {
   705 	IFACE_MACRO(filesystem_factory, FileSystem);
   706 }
   707 
   708 void
   709 mm_LogMessage(const char *msg, ...)
   710 {
   711 	va_list ap;
   712 	static char buffer[2048];
   713 
   714 	va_start(ap, msg);
   715 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   716 	va_end(ap);
   717 
   718 	buffer[len++] = '\n';
   719 	buffer[len] = '\0';
   720 
   721 	if (!provider->LogMessage(buffer))
   722 	{
   723 		fprintf(stdout, "%s", buffer);
   724 	}
   725 }
   726 
   727 static void
   728 DoInitialPluginLoads()
   729 {
   730 	const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
   731 	const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
   732 	if (!pluginFile) 
   733 	{
   734 		pluginFile = provider->GetConVarString(mm_pluginsfile);
   735 		if (pluginFile == NULL)
   736 		{
   737 			pluginFile = "addons/metamod/metaplugins.ini";
   738 		}
   739 	}
   740 	if (!mmBaseDir)
   741 	{
   742 		mmBaseDir = provider->GetConVarString(mm_basedir);
   743 		if (mmBaseDir == NULL)
   744 		{
   745 			mmBaseDir = "addons/metamod";
   746 		}
   747 	}
   748 
   749 	char full_path[260];
   750 
   751 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
   752 	mm_LoadPluginsFromFile(full_path);
   753 
   754 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
   755 	LookForVDFs(full_path);
   756 }
   757 
   758 void
   759 mm_StartupMetamod(bool is_vsp_load)
   760 {
   761 	char buffer[255];
   762 
   763 	UTIL_Format(buffer,
   764 		sizeof(buffer),
   765 		"%s%s",
   766 		SOURCEMM_VERSION,
   767 		is_vsp_load ? "V" : "");
   768 
   769 	metamod_version = provider->CreateConVar("metamod_version", 
   770 		SOURCEMM_VERSION, 
   771 		"Metamod:Source Version",
   772 		ConVarFlag_Notify|ConVarFlag_SpOnly);
   773 
   774 	provider->SetConVarString(metamod_version, buffer);
   775 
   776 	mm_pluginsfile = provider->CreateConVar("mm_pluginsfile", 
   777 #if defined WIN32 || defined _WIN32
   778 		"addons\\metamod\\metaplugins.ini", 
   779 #else
   780 		"addons/metamod/metaplugins.ini",
   781 #endif
   782 		"Metamod:Source Plugins File",
   783 		ConVarFlag_SpOnly);
   784 
   785 	mm_basedir = provider->CreateConVar("mm_basedir",
   786 #if defined __linux__
   787 		"addons/metamod",
   788 #else
   789 		"addons\\metamod",
   790 #endif
   791 		"Metamod:Source Base Folder",
   792 		ConVarFlag_SpOnly);
   793 	
   794 	g_bIsVspBridged = true;
   795 
   796 	if (!is_vsp_load)
   797 	{
   798 		DoInitialPluginLoads();
   799 		in_first_level = true;
   800 	}
   801 }
   802 
   803 void
   804 mm_InitializeGlobals(CreateInterfaceFn engineFactory, 
   805 					 CreateInterfaceFn physicsFactory,
   806 					 CreateInterfaceFn filesystemFactory,
   807 					 CGlobalVars *pGlobals)
   808 {
   809 	engine_factory = engineFactory;
   810 	physics_factory = physicsFactory;
   811 	filesystem_factory = filesystemFactory;
   812 	gpGlobals = pGlobals;
   813 	provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
   814 }
   815 
   816 static bool
   817 Handler_DLLInit(CreateInterfaceFn engineFactory,
   818 				CreateInterfaceFn physicsFactory,
   819 				CreateInterfaceFn filesystemFactory,
   820 				CGlobalVars *pGlobals)
   821 {
   822 	mm_InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
   823 	mm_StartupMetamod(false);
   824 
   825 	RETURN_META_VALUE(MRES_IGNORED, true);
   826 }
   827 
   828 static bool
   829 Handler_GameInit()
   830 {
   831 	if (is_game_init)
   832 		return true;
   833 
   834 	if (vsp_load_requested)
   835 		InitializeVSP();
   836 
   837 	if (g_bIsVspBridged && !were_plugins_loaded)
   838 	{
   839 		DoInitialPluginLoads();
   840 		g_PluginMngr.SetAllLoaded();
   841 		were_plugins_loaded = true;
   842 	}
   843 
   844 	is_game_init = true;
   845 
   846 	RETURN_META_VALUE(MRES_IGNORED, true);
   847 }
   848 
   849 static bool
   850 Handler_DLLInit_Post(CreateInterfaceFn engineFactory,
   851 					 CreateInterfaceFn physicsFactory,
   852 					 CreateInterfaceFn filesystemFactory,
   853 					 CGlobalVars *pGlobals)
   854 {
   855 	g_PluginMngr.SetAllLoaded();
   856 	RETURN_META_VALUE(MRES_IGNORED, true);
   857 }
   858 
   859 void
   860 mm_UnloadMetamod()
   861 {
   862 	/* Unload plugins */
   863 	g_PluginMngr.UnloadAll();
   864 
   865 	provider->Notify_DLLShutdown_Pre();
   866 
   867 	if (is_gamedll_loaded)
   868 	{
   869 		SH_CALL(server, &IServerGameDLL::DLLShutdown)();
   870 	}
   871 
   872 	g_SourceHook.CompleteShutdown();
   873 
   874 	if (is_gamedll_loaded && gamedll_info.lib)
   875 	{
   876 		dlclose(gamedll_info.lib);
   877 		is_gamedll_loaded = false;
   878 	}
   879 }
   880 
   881 static void
   882 Handler_DLLShutdown()
   883 {
   884 	mm_UnloadMetamod();
   885 	RETURN_META(MRES_SUPERCEDE);
   886 }
   887 
   888 static void
   889 Handler_LevelShutdown(void)
   890 {
   891 	if (g_bIsVspBridged && !were_plugins_loaded)
   892 	{
   893 		g_PluginMngr.SetAllLoaded();
   894 		DoInitialPluginLoads();
   895 		were_plugins_loaded = true;
   896 		in_first_level = true;
   897 	}
   898 
   899 	if (!in_first_level)
   900 	{
   901 		char full_path[255];
   902 
   903 		g_Metamod.PathFormat(full_path, 
   904 			sizeof(full_path), 
   905 			"%s/%s", 
   906 			mod_path.c_str(),
   907 			provider->GetConVarString(mm_pluginsfile));
   908 		mm_LoadPluginsFromFile(full_path);
   909 
   910 		g_Metamod.PathFormat(full_path,
   911 			sizeof(full_path),
   912 			"%s/%s",
   913 			mod_path.c_str(),
   914 			provider->GetConVarString(mm_basedir));
   915 		LookForVDFs(full_path);
   916 	}
   917 	else
   918 	{
   919 		in_first_level = false;
   920 	}
   921 
   922 	ITER_EVENT(OnLevelShutdown, ());
   923 
   924 	RETURN_META(MRES_IGNORED);
   925 }
   926 
   927 static bool
   928 Handler_LevelInit(char const *pMapName,
   929 				  char const *pMapEntities,
   930 				  char const *pOldLevel,
   931 				  char const *pLandmarkName,
   932 				  bool loadGame,
   933 				  bool background)
   934 {
   935 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   936 
   937 	RETURN_META_VALUE(MRES_IGNORED, false);
   938 }
   939 
   940 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
   941 {
   942 	va_list ap;
   943 	char buffer[2048];
   944 	
   945 	va_start(ap, msg);
   946 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
   947 	va_end(ap);
   948 
   949 	mm_LogMessage("[%s] %s", pl->GetLogTag(), buffer);
   950 }
   951 
   952 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
   953 {
   954 	if (syn)
   955 		return EngineFactory;
   956 	return engine_factory;
   957 }
   958 
   959 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
   960 {
   961 	if (syn)
   962 		return PhysicsFactory;
   963 	return physics_factory;
   964 }
   965 
   966 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
   967 {
   968 	if (syn)
   969 		return FileSystemFactory;
   970 	return filesystem_factory;
   971 }
   972 
   973 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
   974 {
   975 	if (syn)
   976 		return CreateInterface;
   977 	return gamedll_info.factory;
   978 }
   979 
   980 CGlobalVars *MetamodSource::GetCGlobals()
   981 {
   982 	return gpGlobals;
   983 }
   984 
   985 void MetamodSource::SetLastMetaReturn(META_RES res)
   986 {
   987 	last_meta_res = res;
   988 }
   989 
   990 META_RES MetamodSource::GetLastMetaReturn()
   991 {
   992 	return last_meta_res;
   993 }
   994 
   995 void MetamodSource::ConPrint(const char *str)
   996 {
   997 	provider->ConsolePrint(str);
   998 }
   999 
  1000 void MetamodSource::ConPrintf(const char *fmt, ...)
  1001 {
  1002 	va_list ap;
  1003 	char buffer[2048];
  1004 
  1005 	va_start(ap, fmt);
  1006 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
  1007 	va_end(ap);
  1008 
  1009 	provider->ConsolePrint(buffer);
  1010 }
  1011 
  1012 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
  1013 {
  1014 	major = METAMOD_API_MAJOR;
  1015 	minor = METAMOD_API_MINOR;
  1016 	plvers = METAMOD_PLAPI_VERSION;
  1017 	plmin = PLAPI_MIN_VERSION;
  1018 }
  1019 
  1020 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
  1021 {
  1022 	shvers = SH_IFACE_VERSION;
  1023 	shimpl = SH_IMPL_VERSION;
  1024 }
  1025 
  1026 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
  1027 {
  1028 	int length = (int)strlen(iface);
  1029 	int i;
  1030 	int num = 0;
  1031 
  1032 	for (i = length - 1; i >= 0; i--)
  1033 	{
  1034 		if (!isdigit(iface[i]))
  1035 		{
  1036 			if (i != length - 1)
  1037 			{
  1038 				num = 1;
  1039 			}
  1040 			break;
  1041 		}
  1042 	}
  1043 
  1044 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
  1045 	{
  1046 		return -1;
  1047 	}
  1048 
  1049 	if (i != length - 1)
  1050 	{
  1051 		num = atoi(&(iface[++i]));
  1052 	}
  1053 
  1054 	num++;
  1055 
  1056 	snprintf(&(iface[i]), 4, "%03d", num);
  1057 
  1058 	return num;
  1059 }
  1060 
  1061 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
  1062 {
  1063 	char _if[256];	/* assume no interface goes beyond this */
  1064 	size_t len = strlen(iface);
  1065 	int num = 0;
  1066 	void *pf = NULL;
  1067 
  1068 	if (max > 999)
  1069 	{
  1070 		max = 999;
  1071 	}
  1072 
  1073 	if (len + 4 > sizeof(_if))
  1074 	{
  1075 		if (ret)
  1076 		{
  1077 			*ret = IFACE_FAILED;
  1078 		}
  1079 		return NULL;
  1080 	}
  1081 
  1082 	strcpy(_if, iface);
  1083 
  1084 	do
  1085 	{
  1086 		if ((pf = (fn)(_if, ret)) != NULL)
  1087 		{
  1088 			break;
  1089 		}
  1090 		if (num > max)
  1091 		{
  1092 			break;
  1093 		}
  1094 	} while ((num = FormatIface(_if, len+1)));
  1095 
  1096 	return pf;
  1097 }
  1098 
  1099 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
  1100 {
  1101 	char buffer[256];	/* assume no interface will go beyond this */
  1102 	size_t len = strlen(iface);
  1103 	int ret;			/* just in case something doesn't handle NULL properly */
  1104 
  1105 	if (len > sizeof(buffer) - 4)
  1106 	{
  1107 		return NULL;
  1108 	}
  1109 
  1110 	strcpy(buffer, iface);
  1111 
  1112 	if (min != -1)
  1113 	{
  1114 		char *ptr = &buffer[len - 1];
  1115 		int digits = 0;
  1116 		while (isdigit(*ptr) && digits <=3)
  1117 		{
  1118 			*ptr = '\0';
  1119 			digits++;
  1120 			ptr--;
  1121 		}
  1122 		if (digits != 3)
  1123 		{
  1124 			/* for now, assume this is an error */
  1125 			strcpy(buffer, iface);
  1126 		}
  1127 		else
  1128 		{
  1129 			char num[4];
  1130 			min = (min == 0) ? 1 : min;
  1131 			snprintf(num, sizeof(num), "%03d", min);
  1132 			strcat(buffer, num);
  1133 		}
  1134 	}
  1135 
  1136 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
  1137 }
  1138 
  1139 const char *MetamodSource::GetBaseDir()
  1140 {
  1141 	return mod_path.c_str();
  1142 }
  1143 
  1144 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
  1145 {
  1146 	va_list ap;
  1147 	va_start(ap, fmt);
  1148 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
  1149 	va_end(ap);
  1150 
  1151 	for (size_t i = 0; i < mylen; i++)
  1152 	{
  1153 		if (buffer[i] == ALT_SEP_CHAR)
  1154 		{
  1155 			buffer[i] = PATH_SEP_CHAR;
  1156 		}
  1157 	}
  1158 
  1159 	return mylen;
  1160 }
  1161 
  1162 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
  1163 {
  1164 	va_list ap;
  1165 	char buffer[2048];
  1166 
  1167 	va_start(ap, fmt);
  1168 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
  1169 	va_end(ap);
  1170 
  1171 	provider->ClientConsolePrint(client, buffer);
  1172 }
  1173 
  1174 void MetamodSource::EnableVSPListener()
  1175 {
  1176 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
  1177 		InitializeVSP();
  1178 
  1179 	vsp_load_requested = true;
  1180 }
  1181 
  1182 int MetamodSource::GetVSPVersion()
  1183 {
  1184 	return vsp_version;
  1185 }
  1186 
  1187 int MetamodSource::GetGameDLLVersion()
  1188 {
  1189 	return gamedll_version;
  1190 }
  1191 
  1192 bool MetamodSource::RemotePrintingAvailable()
  1193 {
  1194 	return provider->IsRemotePrintingAvailable();
  1195 }
  1196 
  1197 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
  1198 {
  1199 	if (id)
  1200 	{
  1201 		*id = 0;
  1202 	}
  1203 
  1204 	if (!iface)
  1205 	{
  1206 		return NULL;
  1207 	}
  1208 
  1209 	/* First check ours... we get first chance! */
  1210 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
  1211 	{
  1212 		if (ret)
  1213 		{
  1214 			*ret = IFACE_OK;
  1215 		}
  1216 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
  1217 	}
  1218 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
  1219 	{
  1220 		if (ret)
  1221 		{
  1222 			*ret = IFACE_OK;
  1223 		}
  1224 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
  1225 	}
  1226 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
  1227 	{
  1228 		if (ret)
  1229 		{
  1230 			*ret = IFACE_OK;
  1231 		}
  1232 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
  1233 	}
  1234 
  1235 	CPluginManager::CPlugin *pl;
  1236 	List<IMetamodListener *>::iterator event;
  1237 	IMetamodListener *api;
  1238 	void *value;
  1239 	
  1240 	int subret = 0;
  1241 	for (PluginIter iter = g_PluginMngr._begin();
  1242 		 iter != g_PluginMngr._end();
  1243 		 iter++)
  1244 	{
  1245 		pl = (*iter);
  1246 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
  1247 		{
  1248 			api = (*event);
  1249 			subret = IFACE_FAILED;
  1250 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
  1251 			{
  1252 				if (ret)
  1253 				{
  1254 					*ret = subret;
  1255 				}
  1256 				if (id)
  1257 				{
  1258 					*id = pl->m_Id;
  1259 				}
  1260 				return value;
  1261 			}
  1262 		}
  1263 	}
  1264 
  1265 	if (ret)
  1266 	{
  1267 		*ret = IFACE_FAILED;
  1268 	}
  1269 
  1270 	return NULL;
  1271 }
  1272 
  1273 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
  1274 {
  1275 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
  1276 
  1277 	pl->m_Events.push_back(pListener);
  1278 }
  1279 
  1280 const char *MetamodSource::GetGameBinaryPath()
  1281 {
  1282 	return full_bin_path.c_str();
  1283 }
  1284 
  1285 const char *MetamodSource::GetPluginsFile()
  1286 {
  1287 	return provider->GetConVarString(mm_pluginsfile);
  1288 }
  1289 
  1290 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
  1291 {
  1292 	return provider->GetConCommandBaseAccessor();
  1293 }
  1294 
  1295 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
  1296 {
  1297 	if (provider->IsConCommandBaseACommand(pCommand))
  1298 	{
  1299 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
  1300 	}
  1301 	else
  1302 	{
  1303 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
  1304 	}
  1305 
  1306 	return provider->RegisterConCommandBase(pCommand);
  1307 }
  1308 
  1309 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
  1310 {
  1311 	if (provider->IsConCommandBaseACommand(pCommand))
  1312 	{
  1313 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
  1314 	}
  1315 	else
  1316 	{
  1317 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
  1318 	}
  1319 
  1320 	CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
  1321 	UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
  1322 }
  1323 
  1324 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
  1325 {
  1326 	PluginIter iter;
  1327 	CPluginManager::CPlugin *pPlugin;
  1328 	List<IMetamodListener *>::iterator event;
  1329 	IMetamodListener *pML;
  1330 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
  1331 	{
  1332 		pPlugin = (*iter);
  1333 		if (pPlugin->m_Status < Pl_Paused)
  1334 		{
  1335 			continue;
  1336 		}
  1337 		/* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
  1338 		if (pPlugin->m_API->GetApiVersion() < 12)
  1339 		{
  1340 			continue;
  1341 		}
  1342 		for (event=pPlugin->m_Events.begin();
  1343 			event!=pPlugin->m_Events.end();
  1344 			event++)
  1345 		{
  1346 			pML = (*event);
  1347 			pML->OnUnlinkConCommandBase(id, pCommand);
  1348 		}
  1349 	}
  1350 
  1351 	return provider->UnregisterConCommandBase(pCommand);
  1352 }
  1353 
  1354 int MetamodSource::GetUserMessageCount()
  1355 {
  1356 	return provider->GetUserMessageCount();
  1357 }
  1358 
  1359 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
  1360 {
  1361 	return provider->FindUserMessage(name, size);
  1362 }
  1363 
  1364 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
  1365 {
  1366 	return provider->GetUserMessage(index, size);
  1367 }
  1368 
  1369 int MetamodSource::GetSourceEngineBuild()
  1370 {
  1371 	return engine_build;
  1372 }
  1373 
  1374 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
  1375 {
  1376 	ITER_EVENT(OnVSPListening, (callbacks));
  1377 }
  1378 
  1379 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
  1380 {
  1381 	if (pVersion)
  1382 	{
  1383 		*pVersion = vsp_version;
  1384 	}
  1385 
  1386 	return vsp_callbacks;
  1387 }
  1388 
  1389 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
  1390 {
  1391 	va_list ap;
  1392 	size_t result;
  1393 
  1394 	va_start(ap, format);
  1395 	result = FormatArgs(buffer, maxlength, format, ap);
  1396 	va_end(ap);
  1397 
  1398 	return result;
  1399 }
  1400 
  1401 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
  1402 {
  1403 	return UTIL_FormatArgs(buffer, maxlength, format, ap);
  1404 }
  1405 
  1406 bool MetamodSource::IsLoadedAsGameDLL()
  1407 {
  1408 	return is_gamedll_loaded;
  1409 }
  1410 
  1411 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
  1412 {
  1413 	gamedll_info.factory = serverFactory;
  1414 	gamedll_version = version;
  1415 }
  1416 
  1417 static void
  1418 ProcessVDF(const char *path)
  1419 {
  1420 	PluginId id;
  1421 	bool already;
  1422 	char alias[24], file[255], error[255];
  1423 
  1424 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1425 		return;
  1426 
  1427 	if (alias[0] != '\0')
  1428 		g_PluginMngr.SetAlias(alias, file);
  1429 
  1430 	id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
  1431 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1432 		mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1433 }
  1434 
  1435 static void
  1436 LookForVDFs(const char *dir)
  1437 {
  1438 	char path[MAX_PATH];
  1439 	int extidx;
  1440 
  1441 #if defined _MSC_VER
  1442 	HANDLE hFind;
  1443 	WIN32_FIND_DATA fd;
  1444 	char error[255];
  1445 
  1446 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
  1447 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1448 	{
  1449 		DWORD dw = GetLastError();
  1450 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1451 			NULL,
  1452 			dw,
  1453 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1454 			error,
  1455 			sizeof(error),
  1456 			NULL);
  1457 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1458 		return;
  1459 	}
  1460 
  1461 	do
  1462 	{
  1463 		if (strcmp(fd.cFileName, ".") == 0
  1464 			|| strcmp(fd.cFileName, "..") == 0)
  1465 		{
  1466 			continue;
  1467 		}
  1468 		extidx = strlen(fd.cFileName) - 4;
  1469 		if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
  1470 		{
  1471 			continue;
  1472 		}
  1473 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1474 		ProcessVDF(path);
  1475 	} while (FindNextFile(hFind, &fd));
  1476 
  1477 	FindClose(hFind);
  1478 #else
  1479 	DIR *pDir;
  1480 	struct dirent *pEnt;
  1481 
  1482 	if ((pDir = opendir(dir)) == NULL)
  1483 	{
  1484 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1485 		return;
  1486 	}
  1487 
  1488 	while ((pEnt = readdir(pDir)) != NULL)
  1489 	{
  1490 		if (strcmp(pEnt->d_name, ".") == 0
  1491 			|| strcmp(pEnt->d_name, "..") == 0)
  1492 		{
  1493 			continue;
  1494 		}
  1495 		extidx = strlen(pEnt->d_name) - 4;
  1496 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
  1497 		{
  1498 			continue;
  1499 		}
  1500 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1501 		ProcessVDF(path);
  1502 	}
  1503 
  1504 	closedir(pDir);
  1505 #endif
  1506 }
  1507 
  1508 bool
  1509 mm_IsVspBridged()
  1510 {
  1511 	return g_bIsVspBridged;
  1512 }
  1513 
  1514 bool
  1515 mm_IsVspLoadComplete()
  1516 {
  1517 	return were_plugins_loaded;
  1518 }
  1519