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