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