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