core/metamod.cpp
author David Anderson <dvander@alliedmods.net>
Mon Nov 24 00:11:54 2008 -0600 (2008-11-24)
changeset 594 10748cb1c7f5
parent 592 a38d1ebe28d6
child 599 5b906351da4d
permissions -rw-r--r--
Fixed up some cruft.
     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 
   232 	if (ret)
   233 		*ret = (ptr != NULL) ? IFACE_OK : IFACE_FAILED;
   234 
   235 	return ptr;
   236 }
   237 
   238 int
   239 mm_LoadPluginsFromFile(const char *_file)
   240 {
   241 	FILE *fp;
   242 	int total = 0, skipped=0;
   243 	PluginId id;
   244 	bool already;
   245 
   246 	fp = fopen(_file, "rt");
   247 	if (!fp)
   248 	{
   249 		mm_LogMessage("[META] Could not open plugins file %s\n", _file);
   250 		return -1;
   251 	}
   252 
   253 	char buffer[255], error[255], full_path[255];
   254 	const char *ptr, *ext, *file;
   255 	size_t length;
   256 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   257 	{
   258 		UTIL_TrimLeft(buffer);
   259 		UTIL_TrimRight(buffer);
   260 
   261 		length = strlen(buffer);
   262 		if (!length)
   263 		{
   264 			continue;
   265 		}
   266 
   267 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   268 		{
   269 			continue;
   270 		}
   271 
   272 		file = buffer;
   273 		if (buffer[0] == '"')
   274 		{
   275 			char *cptr = buffer;
   276 			file = ++cptr;
   277 
   278 			while (*cptr)
   279 			{
   280 				if (*cptr == '"')
   281 				{
   282 					*cptr = '\0';
   283 					break;
   284 				}
   285 				cptr++;
   286 			}
   287 		}
   288 		else
   289 		{
   290 			char *cptr = buffer;
   291 			while (*cptr)
   292 			{
   293 				if (isspace(*cptr))
   294 				{
   295 					char *optr = cptr;
   296 					while (*cptr && isspace(*cptr))
   297 					{
   298 						cptr++;
   299 					}
   300 					*optr = '\0';
   301 					UTIL_TrimRight(cptr);
   302 					if (*cptr && isalpha(*cptr))
   303 					{
   304 						g_PluginMngr.SetAlias(buffer, cptr);
   305 						file = cptr;
   306 					}
   307 					break;
   308 				}
   309 				cptr++;
   310 			}
   311 		}
   312 		if (!file[0])
   313 		{
   314 			continue;
   315 		}
   316 		/* First find if it's an absolute path or not... */
   317 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   318 		{
   319 			/* If we're in an absolute path, ignore our normal heuristics */
   320 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   321 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   322 			{
   323 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   324 			}
   325 			else
   326 			{
   327 				if (already)
   328 					skipped++;
   329 				else
   330 					total++;
   331 			}
   332 		}
   333 		else
   334 		{
   335 			/* Attempt to find a file extension */
   336 			ptr = UTIL_GetExtension(file);
   337 			/* Add an extension if there's none there */
   338 			if (!ptr)
   339 			{
   340 #if defined WIN32 || defined _WIN32
   341 				ext = ".dll";
   342 #else
   343 				ext = "_i486.so";
   344 #endif
   345 			}
   346 			else
   347 			{
   348 				ext = "";
   349 			}
   350 			/* Format the new path */
   351 			g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
   352 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   353 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   354 			{
   355 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   356 			}
   357 			else
   358 			{
   359 				if (already)
   360 					skipped++;
   361 				else
   362 					total++;
   363 			}
   364 		}
   365 	}
   366 	fclose(fp);
   367 
   368 	if (skipped)
   369 		mm_LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   370 	else
   371 		mm_LogMessage("[META] Loaded %d plugins from file.", total);
   372 	
   373 	return total;
   374 }
   375 
   376 void InitializeVSP()
   377 {
   378 	if (g_bIsVspBridged)
   379 		return;
   380 
   381 	size_t len;
   382 	char engine_file[PATH_SIZE];
   383 	char engine_path[PATH_SIZE];
   384 	char rel_path[PATH_SIZE * 2];
   385 
   386 	GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
   387 
   388 	/* Chop off the "engine" file part */
   389 	len = strlen(engine_file);
   390 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   391 	{
   392 		if (engine_file[i] == '/' || engine_file[i] == '\\')
   393 		{
   394 			engine_file[i] = '\0';
   395 			break;
   396 		}
   397 	}
   398 	abspath(engine_path, engine_file);
   399 
   400 	const char *usepath = metamod_path.c_str();
   401 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
   402 	{
   403 		usepath = rel_path;
   404 	}
   405 
   406 	char command[PATH_SIZE * 2];
   407 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   408 	provider->ServerCommand(command);
   409 }
   410 
   411 /* Wrapper function.  This is called when the GameDLL thinks it's using
   412  * the engine's real engineFactory.
   413  */
   414 static void *
   415 EngineFactory(const char *iface, int *ret)
   416 {
   417 	IFACE_MACRO(engine_factory, Engine);
   418 }
   419 
   420 /* Wrapper function.  This is called when the GameDLL thinks it's using
   421  * the engine's real physicsFactory.
   422  */
   423 static void *
   424 PhysicsFactory(const char *iface, int *ret)
   425 {
   426 	IFACE_MACRO(physics_factory, Physics);
   427 }
   428 
   429 /* Wrapper function.  This is called when the GameDLL thinks it's using
   430  * the engine's real fileSystemFactory.
   431  */
   432 static void *
   433 FileSystemFactory(const char *iface, int *ret)
   434 {
   435 	IFACE_MACRO(filesystem_factory, FileSystem);
   436 }
   437 
   438 void
   439 mm_LogMessage(const char *msg, ...)
   440 {
   441 	va_list ap;
   442 	static char buffer[2048];
   443 
   444 	va_start(ap, msg);
   445 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   446 	va_end(ap);
   447 
   448 	buffer[len++] = '\n';
   449 	buffer[len] = '\0';
   450 
   451 	if (!provider->LogMessage(buffer))
   452 	{
   453 		fprintf(stdout, "%s", buffer);
   454 	}
   455 }
   456 
   457 static void
   458 DoInitialPluginLoads()
   459 {
   460 	const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
   461 	const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
   462 	if (!pluginFile) 
   463 	{
   464 		pluginFile = provider->GetConVarString(mm_pluginsfile);
   465 		if (pluginFile == NULL)
   466 		{
   467 			pluginFile = "addons/metamod/metaplugins.ini";
   468 		}
   469 	}
   470 	if (!mmBaseDir)
   471 	{
   472 		mmBaseDir = provider->GetConVarString(mm_basedir);
   473 		if (mmBaseDir == NULL)
   474 		{
   475 			mmBaseDir = "addons/metamod";
   476 		}
   477 	}
   478 
   479 	char full_path[260];
   480 
   481 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
   482 	mm_LoadPluginsFromFile(full_path);
   483 
   484 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
   485 	LookForVDFs(full_path);
   486 }
   487 
   488 void
   489 mm_StartupMetamod(bool is_vsp_load)
   490 {
   491 	char buffer[255];
   492 
   493 	UTIL_Format(buffer,
   494 		sizeof(buffer),
   495 		"%s%s",
   496 		SVN_FULL_VERSION,
   497 		is_vsp_load ? "V" : "");
   498 
   499 	metamod_version = provider->CreateConVar("metamod_version", 
   500 		SVN_FULL_VERSION, 
   501 		"Metamod:Source Version",
   502 		ConVarFlag_Notify|ConVarFlag_SpOnly);
   503 
   504 	provider->SetConVarString(metamod_version, buffer);
   505 
   506 	mm_pluginsfile = provider->CreateConVar("mm_pluginsfile", 
   507 #if defined WIN32 || defined _WIN32
   508 		"addons\\metamod\\metaplugins.ini", 
   509 #else
   510 		"addons/metamod/metaplugins.ini",
   511 #endif
   512 		"Metamod:Source Plugins File",
   513 		ConVarFlag_SpOnly);
   514 
   515 	mm_basedir = provider->CreateConVar("mm_basedir",
   516 #if defined __linux__
   517 		"addons/metamod",
   518 #else
   519 		"addons\\metamod",
   520 #endif
   521 		"Metamod:Source Base Folder",
   522 		ConVarFlag_SpOnly);
   523 	
   524 	g_bIsVspBridged = is_vsp_load;
   525 
   526 	if (!is_vsp_load)
   527 	{
   528 		DoInitialPluginLoads();
   529 		in_first_level = true;
   530 	}
   531 }
   532 
   533 void
   534 mm_InitializeGlobals(CreateInterfaceFn engineFactory, 
   535 					 CreateInterfaceFn physicsFactory,
   536 					 CreateInterfaceFn filesystemFactory,
   537 					 CGlobalVars *pGlobals)
   538 {
   539 	engine_factory = engineFactory;
   540 	physics_factory = physicsFactory;
   541 	filesystem_factory = filesystemFactory;
   542 	gpGlobals = pGlobals;
   543 	provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
   544 }
   545 
   546 static bool
   547 Handler_GameInit()
   548 {
   549 	if (is_game_init)
   550 		return true;
   551 
   552 	if (vsp_load_requested)
   553 		InitializeVSP();
   554 
   555 	if (g_bIsVspBridged && !were_plugins_loaded)
   556 	{
   557 		DoInitialPluginLoads();
   558 		g_PluginMngr.SetAllLoaded();
   559 		were_plugins_loaded = true;
   560 	}
   561 
   562 	is_game_init = true;
   563 
   564 	RETURN_META_VALUE(MRES_IGNORED, true);
   565 }
   566 
   567 void
   568 mm_UnloadMetamod()
   569 {
   570 	/* Unload plugins */
   571 	g_PluginMngr.UnloadAll();
   572 
   573 	provider->Notify_DLLShutdown_Pre();
   574 
   575 	g_SourceHook.CompleteShutdown();
   576 }
   577 
   578 static void
   579 Handler_LevelShutdown(void)
   580 {
   581 	if (g_bIsVspBridged && !were_plugins_loaded)
   582 	{
   583 		g_PluginMngr.SetAllLoaded();
   584 		DoInitialPluginLoads();
   585 		were_plugins_loaded = true;
   586 		in_first_level = true;
   587 	}
   588 
   589 	if (!in_first_level)
   590 	{
   591 		char full_path[255];
   592 
   593 		g_Metamod.PathFormat(full_path, 
   594 			sizeof(full_path), 
   595 			"%s/%s", 
   596 			mod_path.c_str(),
   597 			provider->GetConVarString(mm_pluginsfile));
   598 		mm_LoadPluginsFromFile(full_path);
   599 
   600 		g_Metamod.PathFormat(full_path,
   601 			sizeof(full_path),
   602 			"%s/%s",
   603 			mod_path.c_str(),
   604 			provider->GetConVarString(mm_basedir));
   605 		LookForVDFs(full_path);
   606 	}
   607 	else
   608 	{
   609 		in_first_level = false;
   610 	}
   611 
   612 	ITER_EVENT(OnLevelShutdown, ());
   613 
   614 	RETURN_META(MRES_IGNORED);
   615 }
   616 
   617 static bool
   618 Handler_LevelInit(char const *pMapName,
   619 				  char const *pMapEntities,
   620 				  char const *pOldLevel,
   621 				  char const *pLandmarkName,
   622 				  bool loadGame,
   623 				  bool background)
   624 {
   625 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   626 
   627 	RETURN_META_VALUE(MRES_IGNORED, false);
   628 }
   629 
   630 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
   631 {
   632 	va_list ap;
   633 	char buffer[2048];
   634 	
   635 	va_start(ap, msg);
   636 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
   637 	va_end(ap);
   638 
   639 	mm_LogMessage("[%s] %s", pl->GetLogTag(), buffer);
   640 }
   641 
   642 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
   643 {
   644 	if (syn)
   645 		return EngineFactory;
   646 	return engine_factory;
   647 }
   648 
   649 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
   650 {
   651 	if (syn)
   652 		return PhysicsFactory;
   653 	return physics_factory;
   654 }
   655 
   656 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
   657 {
   658 	if (syn)
   659 		return FileSystemFactory;
   660 	return filesystem_factory;
   661 }
   662 
   663 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
   664 {
   665 	if (syn)
   666 		return ServerFactory;
   667 	return gamedll_info.factory;
   668 }
   669 
   670 CGlobalVars *MetamodSource::GetCGlobals()
   671 {
   672 	return gpGlobals;
   673 }
   674 
   675 void MetamodSource::SetLastMetaReturn(META_RES res)
   676 {
   677 	last_meta_res = res;
   678 }
   679 
   680 META_RES MetamodSource::GetLastMetaReturn()
   681 {
   682 	return last_meta_res;
   683 }
   684 
   685 void MetamodSource::ConPrint(const char *str)
   686 {
   687 	provider->ConsolePrint(str);
   688 }
   689 
   690 void MetamodSource::ConPrintf(const char *fmt, ...)
   691 {
   692 	va_list ap;
   693 	char buffer[2048];
   694 
   695 	va_start(ap, fmt);
   696 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   697 	va_end(ap);
   698 
   699 	provider->ConsolePrint(buffer);
   700 }
   701 
   702 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   703 {
   704 	major = METAMOD_API_MAJOR;
   705 	minor = METAMOD_API_MINOR;
   706 	plvers = METAMOD_PLAPI_VERSION;
   707 	plmin = PLAPI_MIN_VERSION;
   708 }
   709 
   710 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
   711 {
   712 	shvers = SH_IFACE_VERSION;
   713 	shimpl = SH_IMPL_VERSION;
   714 }
   715 
   716 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
   717 {
   718 	int length = (int)strlen(iface);
   719 	int i;
   720 	int num = 0;
   721 
   722 	for (i = length - 1; i >= 0; i--)
   723 	{
   724 		if (!isdigit(iface[i]))
   725 		{
   726 			if (i != length - 1)
   727 			{
   728 				num = 1;
   729 			}
   730 			break;
   731 		}
   732 	}
   733 
   734 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   735 	{
   736 		return -1;
   737 	}
   738 
   739 	if (i != length - 1)
   740 	{
   741 		num = atoi(&(iface[++i]));
   742 	}
   743 
   744 	num++;
   745 
   746 	snprintf(&(iface[i]), 4, "%03d", num);
   747 
   748 	return num;
   749 }
   750 
   751 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   752 {
   753 	char _if[256];	/* assume no interface goes beyond this */
   754 	size_t len = strlen(iface);
   755 	int num = 0;
   756 	void *pf = NULL;
   757 
   758 	if (max > 999)
   759 	{
   760 		max = 999;
   761 	}
   762 
   763 	if (len + 4 > sizeof(_if))
   764 	{
   765 		if (ret)
   766 		{
   767 			*ret = IFACE_FAILED;
   768 		}
   769 		return NULL;
   770 	}
   771 
   772 	strcpy(_if, iface);
   773 
   774 	do
   775 	{
   776 		if ((pf = (fn)(_if, ret)) != NULL)
   777 		{
   778 			break;
   779 		}
   780 		if (num > max)
   781 		{
   782 			break;
   783 		}
   784 	} while ((num = FormatIface(_if, len+1)));
   785 
   786 	return pf;
   787 }
   788 
   789 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   790 {
   791 	char buffer[256];	/* assume no interface will go beyond this */
   792 	size_t len = strlen(iface);
   793 	int ret;			/* just in case something doesn't handle NULL properly */
   794 
   795 	if (len > sizeof(buffer) - 4)
   796 	{
   797 		return NULL;
   798 	}
   799 
   800 	strcpy(buffer, iface);
   801 
   802 	if (min != -1)
   803 	{
   804 		char *ptr = &buffer[len - 1];
   805 		int digits = 0;
   806 		while (isdigit(*ptr) && digits <=3)
   807 		{
   808 			*ptr = '\0';
   809 			digits++;
   810 			ptr--;
   811 		}
   812 		if (digits != 3)
   813 		{
   814 			/* for now, assume this is an error */
   815 			strcpy(buffer, iface);
   816 		}
   817 		else
   818 		{
   819 			char num[4];
   820 			min = (min == 0) ? 1 : min;
   821 			snprintf(num, sizeof(num), "%03d", min);
   822 			strcat(buffer, num);
   823 		}
   824 	}
   825 
   826 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   827 }
   828 
   829 const char *MetamodSource::GetBaseDir()
   830 {
   831 	return mod_path.c_str();
   832 }
   833 
   834 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   835 {
   836 	va_list ap;
   837 	va_start(ap, fmt);
   838 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   839 	va_end(ap);
   840 
   841 	for (size_t i = 0; i < mylen; i++)
   842 	{
   843 		if (buffer[i] == ALT_SEP_CHAR)
   844 		{
   845 			buffer[i] = PATH_SEP_CHAR;
   846 		}
   847 	}
   848 
   849 	return mylen;
   850 }
   851 
   852 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
   853 {
   854 	va_list ap;
   855 	char buffer[2048];
   856 
   857 	va_start(ap, fmt);
   858 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   859 	va_end(ap);
   860 
   861 	provider->ClientConsolePrint(client, buffer);
   862 }
   863 
   864 void MetamodSource::EnableVSPListener()
   865 {
   866 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
   867 		InitializeVSP();
   868 
   869 	vsp_load_requested = true;
   870 }
   871 
   872 int MetamodSource::GetVSPVersion()
   873 {
   874 	return vsp_version;
   875 }
   876 
   877 int MetamodSource::GetGameDLLVersion()
   878 {
   879 	return gamedll_version;
   880 }
   881 
   882 bool MetamodSource::RemotePrintingAvailable()
   883 {
   884 	return provider->IsRemotePrintingAvailable();
   885 }
   886 
   887 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
   888 {
   889 	if (id)
   890 	{
   891 		*id = 0;
   892 	}
   893 
   894 	if (!iface)
   895 	{
   896 		return NULL;
   897 	}
   898 
   899 	/* First check ours... we get first chance! */
   900 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   901 	{
   902 		if (ret)
   903 		{
   904 			*ret = IFACE_OK;
   905 		}
   906 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   907 	}
   908 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
   909 	{
   910 		if (ret)
   911 		{
   912 			*ret = IFACE_OK;
   913 		}
   914 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   915 	}
   916 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
   917 	{
   918 		if (ret)
   919 		{
   920 			*ret = IFACE_OK;
   921 		}
   922 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
   923 	}
   924 
   925 	CPluginManager::CPlugin *pl;
   926 	List<IMetamodListener *>::iterator event;
   927 	IMetamodListener *api;
   928 	void *value;
   929 	
   930 	int subret = 0;
   931 	for (PluginIter iter = g_PluginMngr._begin();
   932 		 iter != g_PluginMngr._end();
   933 		 iter++)
   934 	{
   935 		pl = (*iter);
   936 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
   937 		{
   938 			api = (*event);
   939 			subret = IFACE_FAILED;
   940 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
   941 			{
   942 				if (ret)
   943 				{
   944 					*ret = subret;
   945 				}
   946 				if (id)
   947 				{
   948 					*id = pl->m_Id;
   949 				}
   950 				return value;
   951 			}
   952 		}
   953 	}
   954 
   955 	if (ret)
   956 	{
   957 		*ret = IFACE_FAILED;
   958 	}
   959 
   960 	return NULL;
   961 }
   962 
   963 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   964 {
   965 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   966 
   967 	pl->m_Events.push_back(pListener);
   968 }
   969 
   970 const char *MetamodSource::GetGameBinaryPath()
   971 {
   972 	return full_bin_path.c_str();
   973 }
   974 
   975 const char *MetamodSource::GetPluginsFile()
   976 {
   977 	return provider->GetConVarString(mm_pluginsfile);
   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 void
  1113 ProcessVDF(const char *path)
  1114 {
  1115 	PluginId id;
  1116 	bool already;
  1117 	char alias[24], file[255], error[255];
  1118 
  1119 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1120 		return;
  1121 
  1122 	if (alias[0] != '\0')
  1123 		g_PluginMngr.SetAlias(alias, file);
  1124 
  1125 	id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
  1126 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1127 		mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1128 }
  1129 
  1130 static void
  1131 LookForVDFs(const char *dir)
  1132 {
  1133 	char path[MAX_PATH];
  1134 	char relpath[MAX_PATH * 2];
  1135 
  1136 #if defined _MSC_VER
  1137 	HANDLE hFind;
  1138 	WIN32_FIND_DATA fd;
  1139 	char error[255];
  1140 
  1141 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
  1142 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1143 	{
  1144 		DWORD dw = GetLastError();
  1145 		if (dw == ERROR_FILE_NOT_FOUND)
  1146 			return;
  1147 
  1148 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1149 			NULL,
  1150 			dw,
  1151 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1152 			error,
  1153 			sizeof(error),
  1154 			NULL);
  1155 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1156 		return;
  1157 	}
  1158 
  1159 	do
  1160 	{
  1161 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1162 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1163 		ProcessVDF(relpath);
  1164 	} while (FindNextFile(hFind, &fd));
  1165 
  1166 	FindClose(hFind);
  1167 #else
  1168 	DIR *pDir;
  1169 	struct dirent *pEnt;
  1170 	int extidx;
  1171 
  1172 	if ((pDir = opendir(dir)) == NULL)
  1173 	{
  1174 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1175 		return;
  1176 	}
  1177 
  1178 	while ((pEnt = readdir(pDir)) != NULL)
  1179 	{
  1180 		if (strcmp(pEnt->d_name, ".") == 0
  1181 			|| strcmp(pEnt->d_name, "..") == 0)
  1182 		{
  1183 			continue;
  1184 		}
  1185 		extidx = strlen(pEnt->d_name) - 4;
  1186 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
  1187 		{
  1188 			continue;
  1189 		}
  1190 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1191 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1192 		ProcessVDF(relpath);
  1193 	}
  1194 
  1195 	closedir(pDir);
  1196 #endif
  1197 }
  1198 
  1199 bool
  1200 mm_IsVspBridged()
  1201 {
  1202 	return g_bIsVspBridged;
  1203 }
  1204 
  1205 bool
  1206 mm_IsVspLoadComplete()
  1207 {
  1208 	return were_plugins_loaded;
  1209 }
  1210