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