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