core/metamod.cpp
author David Anderson <dvander@alliedmods.net>
Sun Nov 23 23:54:03 2008 -0600 (2008-11-23)
changeset 592 a38d1ebe28d6
parent 591 65250cbdb827
child 594 10748cb1c7f5
permissions -rw-r--r--
Fixed core VSP listening when bridged as a VSP.
     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_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 
    52 static void
    53 Handler_LevelShutdown();
    54 
    55 static bool
    56 Handler_LevelInit(char const *pMapName,
    57 				  char const *pMapEntities,
    58 				  char const *pOldLevel,
    59 				  char const *pLandmarkName,
    60 				  bool loadGame,
    61 				  bool background);
    62 
    63 static bool
    64 Handler_GameInit();
    65 
    66 static void
    67 InitializeVSP();
    68 
    69 static void
    70 LookForVDFs(const char *dir);
    71 
    72 struct game_dll_t
    73 {
    74 	CreateInterfaceFn factory;
    75 };
    76 
    77 static String mod_path;
    78 static String metamod_path;
    79 static String full_bin_path;
    80 static int vsp_version = 0;
    81 static int gamedll_version = 0;
    82 static int engine_build = SOURCE_ENGINE_UNKNOWN;
    83 static List<game_dll_t *> gamedll_list;
    84 static bool is_gamedll_loaded = false;
    85 static bool in_first_level = true;
    86 static bool is_game_init = false;
    87 static bool vsp_load_requested = false;
    88 static bool vsp_loaded = false;
    89 static game_dll_t gamedll_info;
    90 static ConVar *metamod_version = NULL;
    91 static ConVar *mm_pluginsfile = NULL;
    92 static ConVar *mm_basedir = NULL;
    93 static CreateInterfaceFn engine_factory = NULL;
    94 static CreateInterfaceFn physics_factory = NULL;
    95 static CreateInterfaceFn filesystem_factory = NULL;
    96 static CGlobalVars *gpGlobals = NULL;
    97 static CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
    98 static META_RES last_meta_res;
    99 static IServerPluginCallbacks *vsp_callbacks = NULL;
   100 static bool were_plugins_loaded = false;
   101 static bool g_bIsVspBridged = false;
   102 
   103 MetamodSource g_Metamod;
   104 PluginId g_PLID = Pl_Console;
   105 CSourceHookImpl g_SourceHook;
   106 ISourceHook *g_SHPtr = &g_SourceHook;
   107 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
   108 
   109 /* Helper Macro */
   110 #define	IFACE_MACRO(orig,nam) \
   111 	CPluginManager::CPlugin *pl; \
   112 	SourceHook::List<IMetamodListener *>::iterator event; \
   113 	IMetamodListener *api; \
   114 	int mret = 0; \
   115 	void *val = NULL; \
   116 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   117 		pl = (*iter); \
   118 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   119 			api = (*event); \
   120 			mret = IFACE_FAILED; \
   121 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
   122 				if (ret) *ret = mret; \
   123 				return val; \
   124 			} \
   125 		} \
   126 	} \
   127 	return (orig)(iface, ret);
   128 
   129 #define ITER_EVENT(evn, args) \
   130 	CPluginManager::CPlugin *pl; \
   131 	SourceHook::List<IMetamodListener *>::iterator event; \
   132 	IMetamodListener *api; \
   133 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   134 		pl = (*iter); \
   135 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   136 			api = (*event); \
   137 			api->evn args; \
   138 		} \
   139 	}
   140 
   141 /* Initialize everything here */
   142 void
   143 mm_InitializeForLoad()
   144 {
   145 	char full_path[PATH_SIZE] = {0};
   146 	GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
   147 	full_bin_path.assign(full_path);
   148 
   149 	/* Like Metamod, reload plugins at the end of the map.
   150 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   151 	 * if the server is shut down (silly, but rare case).
   152 	 */
   153 	in_first_level = true;
   154 
   155 	SourceHook::MemFuncInfo info;
   156 
   157 	if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
   158 	{
   159 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
   160 	}
   161 	SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   162 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
   163 
   164 	if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
   165 	{
   166 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
   167 	}
   168 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   169 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
   170 
   171 	if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
   172 	{
   173 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
   174 	}
   175 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
   176 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
   177 }
   178 
   179 bool
   180 mm_DetectGameInformation()
   181 {
   182 	char mm_path[PATH_SIZE];
   183 	char game_path[PATH_SIZE];
   184 
   185 	/* Get path to SourceMM DLL */
   186 	if (!GetFileOfAddress((void *)mm_InitializeForLoad, mm_path, sizeof(mm_path)))
   187 	{
   188 		return false;
   189 	}
   190 
   191 	metamod_path.assign(mm_path);
   192 
   193 	/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   194 	const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
   195 
   196 	/* Get absolute path */
   197 	abspath(game_path, game_dir);
   198 	mod_path.assign(game_path);
   199 
   200 	engine_build = provider->DetermineSourceEngine(game_dir);;
   201 
   202 	return true;
   203 }
   204 
   205 void *
   206 ServerFactory(const char *iface, int *ret)
   207 {
   208 	IFACE_MACRO(gamedll_info.factory, GameDLL);
   209 }
   210 
   211 SMM_API void *
   212 CreateInterface(const char *iface, int *ret)
   213 {
   214 	void *ptr = NULL;
   215 
   216 	if (!mm_IsVspBridged() && strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
   217 	{
   218 		if (vsp_callbacks != NULL)
   219 		{
   220 			if (ret != NULL)
   221 				*ret = IFACE_FAILED;
   222 			return NULL;
   223 		}
   224 
   225 		vsp_version = atoi(&iface[22]);
   226 		ptr = provider->GetVSPCallbacks(vsp_version);
   227 
   228 		if (ptr == NULL)
   229 			vsp_version = 0;
   230 
   231 		return ptr;
   232 	}
   233 
   234 	if (ret)
   235 		*ret = (ptr != NULL) ? IFACE_OK : IFACE_FAILED;
   236 
   237 	return ptr;
   238 }
   239 
   240 int
   241 mm_LoadPluginsFromFile(const char *_file)
   242 {
   243 	FILE *fp;
   244 	int total = 0, skipped=0;
   245 	PluginId id;
   246 	bool already;
   247 
   248 	fp = fopen(_file, "rt");
   249 	if (!fp)
   250 	{
   251 		mm_LogMessage("[META] Could not open plugins file %s\n", _file);
   252 		return -1;
   253 	}
   254 
   255 	char buffer[255], error[255], full_path[255];
   256 	const char *ptr, *ext, *file;
   257 	size_t length;
   258 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   259 	{
   260 		UTIL_TrimLeft(buffer);
   261 		UTIL_TrimRight(buffer);
   262 
   263 		length = strlen(buffer);
   264 		if (!length)
   265 		{
   266 			continue;
   267 		}
   268 
   269 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   270 		{
   271 			continue;
   272 		}
   273 
   274 		file = buffer;
   275 		if (buffer[0] == '"')
   276 		{
   277 			char *cptr = buffer;
   278 			file = ++cptr;
   279 
   280 			while (*cptr)
   281 			{
   282 				if (*cptr == '"')
   283 				{
   284 					*cptr = '\0';
   285 					break;
   286 				}
   287 				cptr++;
   288 			}
   289 		}
   290 		else
   291 		{
   292 			char *cptr = buffer;
   293 			while (*cptr)
   294 			{
   295 				if (isspace(*cptr))
   296 				{
   297 					char *optr = cptr;
   298 					while (*cptr && isspace(*cptr))
   299 					{
   300 						cptr++;
   301 					}
   302 					*optr = '\0';
   303 					UTIL_TrimRight(cptr);
   304 					if (*cptr && isalpha(*cptr))
   305 					{
   306 						g_PluginMngr.SetAlias(buffer, cptr);
   307 						file = cptr;
   308 					}
   309 					break;
   310 				}
   311 				cptr++;
   312 			}
   313 		}
   314 		if (!file[0])
   315 		{
   316 			continue;
   317 		}
   318 		/* First find if it's an absolute path or not... */
   319 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   320 		{
   321 			/* If we're in an absolute path, ignore our normal heuristics */
   322 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   323 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   324 			{
   325 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   326 			}
   327 			else
   328 			{
   329 				if (already)
   330 					skipped++;
   331 				else
   332 					total++;
   333 			}
   334 		}
   335 		else
   336 		{
   337 			/* Attempt to find a file extension */
   338 			ptr = UTIL_GetExtension(file);
   339 			/* Add an extension if there's none there */
   340 			if (!ptr)
   341 			{
   342 #if defined WIN32 || defined _WIN32
   343 				ext = ".dll";
   344 #else
   345 				ext = "_i486.so";
   346 #endif
   347 			}
   348 			else
   349 			{
   350 				ext = "";
   351 			}
   352 			/* Format the new path */
   353 			g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
   354 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   355 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   356 			{
   357 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   358 			}
   359 			else
   360 			{
   361 				if (already)
   362 					skipped++;
   363 				else
   364 					total++;
   365 			}
   366 		}
   367 	}
   368 	fclose(fp);
   369 
   370 	if (skipped)
   371 		mm_LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   372 	else
   373 		mm_LogMessage("[META] Loaded %d plugins from file.", total);
   374 	
   375 	return total;
   376 }
   377 
   378 void InitializeVSP()
   379 {
   380 	if (g_bIsVspBridged)
   381 		return;
   382 
   383 	size_t len;
   384 	char engine_file[PATH_SIZE];
   385 	char engine_path[PATH_SIZE];
   386 	char rel_path[PATH_SIZE * 2];
   387 
   388 	GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
   389 
   390 	/* Chop off the "engine" file part */
   391 	len = strlen(engine_file);
   392 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   393 	{
   394 		if (engine_file[i] == '/' || engine_file[i] == '\\')
   395 		{
   396 			engine_file[i] = '\0';
   397 			break;
   398 		}
   399 	}
   400 	abspath(engine_path, engine_file);
   401 
   402 	const char *usepath = metamod_path.c_str();
   403 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
   404 	{
   405 		usepath = rel_path;
   406 	}
   407 
   408 	char command[PATH_SIZE * 2];
   409 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   410 	provider->ServerCommand(command);
   411 }
   412 
   413 /* Wrapper function.  This is called when the GameDLL thinks it's using
   414  * the engine's real engineFactory.
   415  */
   416 static void *
   417 EngineFactory(const char *iface, int *ret)
   418 {
   419 	IFACE_MACRO(engine_factory, Engine);
   420 }
   421 
   422 /* Wrapper function.  This is called when the GameDLL thinks it's using
   423  * the engine's real physicsFactory.
   424  */
   425 static void *
   426 PhysicsFactory(const char *iface, int *ret)
   427 {
   428 	IFACE_MACRO(physics_factory, Physics);
   429 }
   430 
   431 /* Wrapper function.  This is called when the GameDLL thinks it's using
   432  * the engine's real fileSystemFactory.
   433  */
   434 static void *
   435 FileSystemFactory(const char *iface, int *ret)
   436 {
   437 	IFACE_MACRO(filesystem_factory, FileSystem);
   438 }
   439 
   440 void
   441 mm_LogMessage(const char *msg, ...)
   442 {
   443 	va_list ap;
   444 	static char buffer[2048];
   445 
   446 	va_start(ap, msg);
   447 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   448 	va_end(ap);
   449 
   450 	buffer[len++] = '\n';
   451 	buffer[len] = '\0';
   452 
   453 	if (!provider->LogMessage(buffer))
   454 	{
   455 		fprintf(stdout, "%s", buffer);
   456 	}
   457 }
   458 
   459 static void
   460 DoInitialPluginLoads()
   461 {
   462 	const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
   463 	const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
   464 	if (!pluginFile) 
   465 	{
   466 		pluginFile = provider->GetConVarString(mm_pluginsfile);
   467 		if (pluginFile == NULL)
   468 		{
   469 			pluginFile = "addons/metamod/metaplugins.ini";
   470 		}
   471 	}
   472 	if (!mmBaseDir)
   473 	{
   474 		mmBaseDir = provider->GetConVarString(mm_basedir);
   475 		if (mmBaseDir == NULL)
   476 		{
   477 			mmBaseDir = "addons/metamod";
   478 		}
   479 	}
   480 
   481 	char full_path[260];
   482 
   483 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
   484 	mm_LoadPluginsFromFile(full_path);
   485 
   486 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
   487 	LookForVDFs(full_path);
   488 }
   489 
   490 void
   491 mm_StartupMetamod(bool is_vsp_load)
   492 {
   493 	char buffer[255];
   494 
   495 	UTIL_Format(buffer,
   496 		sizeof(buffer),
   497 		"%s%s",
   498 		SVN_FULL_VERSION,
   499 		is_vsp_load ? "V" : "");
   500 
   501 	metamod_version = provider->CreateConVar("metamod_version", 
   502 		SVN_FULL_VERSION, 
   503 		"Metamod:Source Version",
   504 		ConVarFlag_Notify|ConVarFlag_SpOnly);
   505 
   506 	provider->SetConVarString(metamod_version, buffer);
   507 
   508 	mm_pluginsfile = provider->CreateConVar("mm_pluginsfile", 
   509 #if defined WIN32 || defined _WIN32
   510 		"addons\\metamod\\metaplugins.ini", 
   511 #else
   512 		"addons/metamod/metaplugins.ini",
   513 #endif
   514 		"Metamod:Source Plugins File",
   515 		ConVarFlag_SpOnly);
   516 
   517 	mm_basedir = provider->CreateConVar("mm_basedir",
   518 #if defined __linux__
   519 		"addons/metamod",
   520 #else
   521 		"addons\\metamod",
   522 #endif
   523 		"Metamod:Source Base Folder",
   524 		ConVarFlag_SpOnly);
   525 	
   526 	g_bIsVspBridged = is_vsp_load;
   527 
   528 	if (!is_vsp_load)
   529 	{
   530 		DoInitialPluginLoads();
   531 		in_first_level = true;
   532 	}
   533 }
   534 
   535 void
   536 mm_InitializeGlobals(CreateInterfaceFn engineFactory, 
   537 					 CreateInterfaceFn physicsFactory,
   538 					 CreateInterfaceFn filesystemFactory,
   539 					 CGlobalVars *pGlobals)
   540 {
   541 	engine_factory = engineFactory;
   542 	physics_factory = physicsFactory;
   543 	filesystem_factory = filesystemFactory;
   544 	gpGlobals = pGlobals;
   545 	provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
   546 }
   547 
   548 static bool
   549 Handler_GameInit()
   550 {
   551 	if (is_game_init)
   552 		return true;
   553 
   554 	if (vsp_load_requested)
   555 		InitializeVSP();
   556 
   557 	if (g_bIsVspBridged && !were_plugins_loaded)
   558 	{
   559 		DoInitialPluginLoads();
   560 		g_PluginMngr.SetAllLoaded();
   561 		were_plugins_loaded = true;
   562 	}
   563 
   564 	is_game_init = true;
   565 
   566 	RETURN_META_VALUE(MRES_IGNORED, true);
   567 }
   568 
   569 void
   570 mm_UnloadMetamod()
   571 {
   572 	/* Unload plugins */
   573 	g_PluginMngr.UnloadAll();
   574 
   575 	provider->Notify_DLLShutdown_Pre();
   576 
   577 	g_SourceHook.CompleteShutdown();
   578 }
   579 
   580 static void
   581 Handler_LevelShutdown(void)
   582 {
   583 	if (g_bIsVspBridged && !were_plugins_loaded)
   584 	{
   585 		g_PluginMngr.SetAllLoaded();
   586 		DoInitialPluginLoads();
   587 		were_plugins_loaded = true;
   588 		in_first_level = true;
   589 	}
   590 
   591 	if (!in_first_level)
   592 	{
   593 		char full_path[255];
   594 
   595 		g_Metamod.PathFormat(full_path, 
   596 			sizeof(full_path), 
   597 			"%s/%s", 
   598 			mod_path.c_str(),
   599 			provider->GetConVarString(mm_pluginsfile));
   600 		mm_LoadPluginsFromFile(full_path);
   601 
   602 		g_Metamod.PathFormat(full_path,
   603 			sizeof(full_path),
   604 			"%s/%s",
   605 			mod_path.c_str(),
   606 			provider->GetConVarString(mm_basedir));
   607 		LookForVDFs(full_path);
   608 	}
   609 	else
   610 	{
   611 		in_first_level = false;
   612 	}
   613 
   614 	ITER_EVENT(OnLevelShutdown, ());
   615 
   616 	RETURN_META(MRES_IGNORED);
   617 }
   618 
   619 static bool
   620 Handler_LevelInit(char const *pMapName,
   621 				  char const *pMapEntities,
   622 				  char const *pOldLevel,
   623 				  char const *pLandmarkName,
   624 				  bool loadGame,
   625 				  bool background)
   626 {
   627 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   628 
   629 	RETURN_META_VALUE(MRES_IGNORED, false);
   630 }
   631 
   632 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
   633 {
   634 	va_list ap;
   635 	char buffer[2048];
   636 	
   637 	va_start(ap, msg);
   638 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
   639 	va_end(ap);
   640 
   641 	mm_LogMessage("[%s] %s", pl->GetLogTag(), buffer);
   642 }
   643 
   644 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
   645 {
   646 	if (syn)
   647 		return EngineFactory;
   648 	return engine_factory;
   649 }
   650 
   651 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
   652 {
   653 	if (syn)
   654 		return PhysicsFactory;
   655 	return physics_factory;
   656 }
   657 
   658 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
   659 {
   660 	if (syn)
   661 		return FileSystemFactory;
   662 	return filesystem_factory;
   663 }
   664 
   665 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
   666 {
   667 	if (syn)
   668 		return ServerFactory;
   669 	return gamedll_info.factory;
   670 }
   671 
   672 CGlobalVars *MetamodSource::GetCGlobals()
   673 {
   674 	return gpGlobals;
   675 }
   676 
   677 void MetamodSource::SetLastMetaReturn(META_RES res)
   678 {
   679 	last_meta_res = res;
   680 }
   681 
   682 META_RES MetamodSource::GetLastMetaReturn()
   683 {
   684 	return last_meta_res;
   685 }
   686 
   687 void MetamodSource::ConPrint(const char *str)
   688 {
   689 	provider->ConsolePrint(str);
   690 }
   691 
   692 void MetamodSource::ConPrintf(const char *fmt, ...)
   693 {
   694 	va_list ap;
   695 	char buffer[2048];
   696 
   697 	va_start(ap, fmt);
   698 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   699 	va_end(ap);
   700 
   701 	provider->ConsolePrint(buffer);
   702 }
   703 
   704 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   705 {
   706 	major = METAMOD_API_MAJOR;
   707 	minor = METAMOD_API_MINOR;
   708 	plvers = METAMOD_PLAPI_VERSION;
   709 	plmin = PLAPI_MIN_VERSION;
   710 }
   711 
   712 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
   713 {
   714 	shvers = SH_IFACE_VERSION;
   715 	shimpl = SH_IMPL_VERSION;
   716 }
   717 
   718 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
   719 {
   720 	int length = (int)strlen(iface);
   721 	int i;
   722 	int num = 0;
   723 
   724 	for (i = length - 1; i >= 0; i--)
   725 	{
   726 		if (!isdigit(iface[i]))
   727 		{
   728 			if (i != length - 1)
   729 			{
   730 				num = 1;
   731 			}
   732 			break;
   733 		}
   734 	}
   735 
   736 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   737 	{
   738 		return -1;
   739 	}
   740 
   741 	if (i != length - 1)
   742 	{
   743 		num = atoi(&(iface[++i]));
   744 	}
   745 
   746 	num++;
   747 
   748 	snprintf(&(iface[i]), 4, "%03d", num);
   749 
   750 	return num;
   751 }
   752 
   753 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   754 {
   755 	char _if[256];	/* assume no interface goes beyond this */
   756 	size_t len = strlen(iface);
   757 	int num = 0;
   758 	void *pf = NULL;
   759 
   760 	if (max > 999)
   761 	{
   762 		max = 999;
   763 	}
   764 
   765 	if (len + 4 > sizeof(_if))
   766 	{
   767 		if (ret)
   768 		{
   769 			*ret = IFACE_FAILED;
   770 		}
   771 		return NULL;
   772 	}
   773 
   774 	strcpy(_if, iface);
   775 
   776 	do
   777 	{
   778 		if ((pf = (fn)(_if, ret)) != NULL)
   779 		{
   780 			break;
   781 		}
   782 		if (num > max)
   783 		{
   784 			break;
   785 		}
   786 	} while ((num = FormatIface(_if, len+1)));
   787 
   788 	return pf;
   789 }
   790 
   791 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   792 {
   793 	char buffer[256];	/* assume no interface will go beyond this */
   794 	size_t len = strlen(iface);
   795 	int ret;			/* just in case something doesn't handle NULL properly */
   796 
   797 	if (len > sizeof(buffer) - 4)
   798 	{
   799 		return NULL;
   800 	}
   801 
   802 	strcpy(buffer, iface);
   803 
   804 	if (min != -1)
   805 	{
   806 		char *ptr = &buffer[len - 1];
   807 		int digits = 0;
   808 		while (isdigit(*ptr) && digits <=3)
   809 		{
   810 			*ptr = '\0';
   811 			digits++;
   812 			ptr--;
   813 		}
   814 		if (digits != 3)
   815 		{
   816 			/* for now, assume this is an error */
   817 			strcpy(buffer, iface);
   818 		}
   819 		else
   820 		{
   821 			char num[4];
   822 			min = (min == 0) ? 1 : min;
   823 			snprintf(num, sizeof(num), "%03d", min);
   824 			strcat(buffer, num);
   825 		}
   826 	}
   827 
   828 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   829 }
   830 
   831 const char *MetamodSource::GetBaseDir()
   832 {
   833 	return mod_path.c_str();
   834 }
   835 
   836 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   837 {
   838 	va_list ap;
   839 	va_start(ap, fmt);
   840 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   841 	va_end(ap);
   842 
   843 	for (size_t i = 0; i < mylen; i++)
   844 	{
   845 		if (buffer[i] == ALT_SEP_CHAR)
   846 		{
   847 			buffer[i] = PATH_SEP_CHAR;
   848 		}
   849 	}
   850 
   851 	return mylen;
   852 }
   853 
   854 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
   855 {
   856 	va_list ap;
   857 	char buffer[2048];
   858 
   859 	va_start(ap, fmt);
   860 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   861 	va_end(ap);
   862 
   863 	provider->ClientConsolePrint(client, buffer);
   864 }
   865 
   866 void MetamodSource::EnableVSPListener()
   867 {
   868 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
   869 		InitializeVSP();
   870 
   871 	vsp_load_requested = true;
   872 }
   873 
   874 int MetamodSource::GetVSPVersion()
   875 {
   876 	return vsp_version;
   877 }
   878 
   879 int MetamodSource::GetGameDLLVersion()
   880 {
   881 	return gamedll_version;
   882 }
   883 
   884 bool MetamodSource::RemotePrintingAvailable()
   885 {
   886 	return provider->IsRemotePrintingAvailable();
   887 }
   888 
   889 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
   890 {
   891 	if (id)
   892 	{
   893 		*id = 0;
   894 	}
   895 
   896 	if (!iface)
   897 	{
   898 		return NULL;
   899 	}
   900 
   901 	/* First check ours... we get first chance! */
   902 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   903 	{
   904 		if (ret)
   905 		{
   906 			*ret = IFACE_OK;
   907 		}
   908 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   909 	}
   910 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
   911 	{
   912 		if (ret)
   913 		{
   914 			*ret = IFACE_OK;
   915 		}
   916 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   917 	}
   918 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
   919 	{
   920 		if (ret)
   921 		{
   922 			*ret = IFACE_OK;
   923 		}
   924 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
   925 	}
   926 
   927 	CPluginManager::CPlugin *pl;
   928 	List<IMetamodListener *>::iterator event;
   929 	IMetamodListener *api;
   930 	void *value;
   931 	
   932 	int subret = 0;
   933 	for (PluginIter iter = g_PluginMngr._begin();
   934 		 iter != g_PluginMngr._end();
   935 		 iter++)
   936 	{
   937 		pl = (*iter);
   938 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
   939 		{
   940 			api = (*event);
   941 			subret = IFACE_FAILED;
   942 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
   943 			{
   944 				if (ret)
   945 				{
   946 					*ret = subret;
   947 				}
   948 				if (id)
   949 				{
   950 					*id = pl->m_Id;
   951 				}
   952 				return value;
   953 			}
   954 		}
   955 	}
   956 
   957 	if (ret)
   958 	{
   959 		*ret = IFACE_FAILED;
   960 	}
   961 
   962 	return NULL;
   963 }
   964 
   965 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   966 {
   967 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   968 
   969 	pl->m_Events.push_back(pListener);
   970 }
   971 
   972 const char *MetamodSource::GetGameBinaryPath()
   973 {
   974 	return full_bin_path.c_str();
   975 }
   976 
   977 const char *MetamodSource::GetPluginsFile()
   978 {
   979 	return provider->GetConVarString(mm_pluginsfile);
   980 }
   981 
   982 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
   983 {
   984 	return provider->GetConCommandBaseAccessor();
   985 }
   986 
   987 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   988 {
   989 	if (provider->IsConCommandBaseACommand(pCommand))
   990 	{
   991 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   992 	}
   993 	else
   994 	{
   995 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   996 	}
   997 
   998 	return provider->RegisterConCommandBase(pCommand);
   999 }
  1000 
  1001 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
  1002 {
  1003 	if (provider->IsConCommandBaseACommand(pCommand))
  1004 	{
  1005 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
  1006 	}
  1007 	else
  1008 	{
  1009 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
  1010 	}
  1011 
  1012 	CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
  1013 	UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
  1014 }
  1015 
  1016 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
  1017 {
  1018 	PluginIter iter;
  1019 	CPluginManager::CPlugin *pPlugin;
  1020 	List<IMetamodListener *>::iterator event;
  1021 	IMetamodListener *pML;
  1022 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
  1023 	{
  1024 		pPlugin = (*iter);
  1025 		if (pPlugin->m_Status < Pl_Paused)
  1026 		{
  1027 			continue;
  1028 		}
  1029 		/* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
  1030 		if (pPlugin->m_API->GetApiVersion() < 12)
  1031 		{
  1032 			continue;
  1033 		}
  1034 		for (event=pPlugin->m_Events.begin();
  1035 			event!=pPlugin->m_Events.end();
  1036 			event++)
  1037 		{
  1038 			pML = (*event);
  1039 			pML->OnUnlinkConCommandBase(id, pCommand);
  1040 		}
  1041 	}
  1042 
  1043 	return provider->UnregisterConCommandBase(pCommand);
  1044 }
  1045 
  1046 int MetamodSource::GetUserMessageCount()
  1047 {
  1048 	return provider->GetUserMessageCount();
  1049 }
  1050 
  1051 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
  1052 {
  1053 	return provider->FindUserMessage(name, size);
  1054 }
  1055 
  1056 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
  1057 {
  1058 	return provider->GetUserMessage(index, size);
  1059 }
  1060 
  1061 int MetamodSource::GetSourceEngineBuild()
  1062 {
  1063 	return engine_build;
  1064 }
  1065 
  1066 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks, int version)
  1067 {
  1068 	if (version != -1)
  1069 		vsp_version = version;
  1070 	
  1071 	vsp_callbacks = callbacks;
  1072 	ITER_EVENT(OnVSPListening, (callbacks));
  1073 }
  1074 
  1075 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
  1076 {
  1077 	if (pVersion)
  1078 	{
  1079 		*pVersion = vsp_version;
  1080 	}
  1081 
  1082 	return vsp_callbacks;
  1083 }
  1084 
  1085 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
  1086 {
  1087 	va_list ap;
  1088 	size_t result;
  1089 
  1090 	va_start(ap, format);
  1091 	result = FormatArgs(buffer, maxlength, format, ap);
  1092 	va_end(ap);
  1093 
  1094 	return result;
  1095 }
  1096 
  1097 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
  1098 {
  1099 	return UTIL_FormatArgs(buffer, maxlength, format, ap);
  1100 }
  1101 
  1102 bool MetamodSource::IsLoadedAsGameDLL()
  1103 {
  1104 	return is_gamedll_loaded;
  1105 }
  1106 
  1107 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version, bool loaded)
  1108 {
  1109 	gamedll_info.factory = serverFactory;
  1110 	gamedll_version = version;
  1111 	is_gamedll_loaded = loaded;
  1112 }
  1113 
  1114 static void
  1115 ProcessVDF(const char *path)
  1116 {
  1117 	PluginId id;
  1118 	bool already;
  1119 	char alias[24], file[255], error[255];
  1120 
  1121 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1122 		return;
  1123 
  1124 	if (alias[0] != '\0')
  1125 		g_PluginMngr.SetAlias(alias, file);
  1126 
  1127 	id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
  1128 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1129 		mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1130 }
  1131 
  1132 static void
  1133 LookForVDFs(const char *dir)
  1134 {
  1135 	char path[MAX_PATH];
  1136 	char relpath[MAX_PATH * 2];
  1137 
  1138 #if defined _MSC_VER
  1139 	HANDLE hFind;
  1140 	WIN32_FIND_DATA fd;
  1141 	char error[255];
  1142 
  1143 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
  1144 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1145 	{
  1146 		DWORD dw = GetLastError();
  1147 		if (dw == ERROR_FILE_NOT_FOUND)
  1148 			return;
  1149 
  1150 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1151 			NULL,
  1152 			dw,
  1153 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1154 			error,
  1155 			sizeof(error),
  1156 			NULL);
  1157 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1158 		return;
  1159 	}
  1160 
  1161 	do
  1162 	{
  1163 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1164 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1165 		ProcessVDF(relpath);
  1166 	} while (FindNextFile(hFind, &fd));
  1167 
  1168 	FindClose(hFind);
  1169 #else
  1170 	DIR *pDir;
  1171 	struct dirent *pEnt;
  1172 	int extidx;
  1173 
  1174 	if ((pDir = opendir(dir)) == NULL)
  1175 	{
  1176 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1177 		return;
  1178 	}
  1179 
  1180 	while ((pEnt = readdir(pDir)) != NULL)
  1181 	{
  1182 		if (strcmp(pEnt->d_name, ".") == 0
  1183 			|| strcmp(pEnt->d_name, "..") == 0)
  1184 		{
  1185 			continue;
  1186 		}
  1187 		extidx = strlen(pEnt->d_name) - 4;
  1188 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
  1189 		{
  1190 			continue;
  1191 		}
  1192 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1193 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1194 		ProcessVDF(relpath);
  1195 	}
  1196 
  1197 	closedir(pDir);
  1198 #endif
  1199 }
  1200 
  1201 bool
  1202 mm_IsVspBridged()
  1203 {
  1204 	return g_bIsVspBridged;
  1205 }
  1206 
  1207 bool
  1208 mm_IsVspLoadComplete()
  1209 {
  1210 	return were_plugins_loaded;
  1211 }
  1212