sourcemm/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Thu May 25 04:49:47 2006 +0000 (2006-05-25)
changeset 205 08964c08d894
parent 192 47649a1d49e3
child 215 e3b5d251a9dd
permissions -rw-r--r--
added alias ability
fixed gamedll version finding fall through
     1 /* ======== SourceMM ========
     2 * Copyright (C) 2004-2006 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 #include <interface.h>
    14 #include <eiface.h>
    15 #include "sourcemm.h"
    16 #include "concommands.h"
    17 #include "CSmmAPI.h"
    18 #include "CPlugin.h"
    19 #include "util.h"
    20 
    21 using namespace SourceMM;
    22 
    23 /**
    24  * @brief Implementation of main SourceMM GameDLL functionality
    25  * @file sourcemm.cpp
    26  */
    27 
    28 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
    29 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
    30 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    31 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    32 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    33 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    34 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    35 void DLLShutdown_handler();
    36 void LevelShutdown_handler();
    37 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
    38 
    39 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
    40 EngineInfo g_Engine;
    41 SourceHook::CSourceHookImpl g_SourceHook;
    42 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
    43 SourceHook::String g_ModPath;
    44 SourceHook::String g_BinPath;
    45 PluginId g_PLID = Pl_Console;		//Technically, SourceMM is the "Console" plugin... :p
    46 bool bInFirstLevel = true;
    47 bool gParsedGameInfo = false;
    48 SourceHook::List<GameDllInfo *> gamedll_list;
    49 SourceHook::CallClass<IServerGameDLL> *dllExec;
    50 
    51 void ClearGamedllList();
    52 
    53 //helper macro
    54 #define	IFACE_MACRO(orig,nam) \
    55 	CPluginManager::CPlugin *pl; \
    56 	SourceHook::List<IMetamodListener *>::iterator event; \
    57 	IMetamodListener *api; \
    58 	int mret = 0; \
    59 	void *val = NULL; \
    60 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    61 		pl = (*iter); \
    62 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    63 			api = (*event); \
    64 			mret = IFACE_FAILED; \
    65 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
    66 				if (ret) *ret = mret; \
    67 				return val; \
    68 			} \
    69 		} \
    70 	} \
    71 	return (orig)(iface, ret);
    72 
    73 #define ITER_EVENT(evn, args) \
    74 	CPluginManager::CPlugin *pl; \
    75 	SourceHook::List<IMetamodListener *>::iterator event; \
    76 	IMetamodListener *api; \
    77 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    78 		pl = (*iter); \
    79 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    80 			api = (*event); \
    81 			api->evn args; \
    82 		} \
    83 	}
    84 
    85 ///////////////////////////////////
    86 // Main code for HL2 Interaction //
    87 ///////////////////////////////////
    88 
    89 //Initialize everything here
    90 void InitMainStates()
    91 {
    92 	char full_path[260] = {0};
    93 	GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
    94 	g_BinPath.assign(full_path);
    95 
    96 	//Like metamod, reload plugins at the end of the map.
    97 	//This is so plugins can hook everything on load, BUT, new plugins will be reloaded
    98 	// if the server is shut down (silly, but rare case).
    99 	bInFirstLevel = true;
   100 
   101 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
   102 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
   103 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
   104 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
   105 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
   106 
   107 	if (g_GameDll.pGameClients)
   108 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
   109 	else
   110 	{
   111 		// If IServerGameClients isn't found, this really isn't a fatal error so...
   112 		LogMessage("[META] Warning: Could not find IServerGameClients!");
   113 		LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
   114 	}
   115 }
   116 
   117 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   118 {
   119 	g_Engine.engineFactory = engineFactory;
   120 	g_Engine.fileSystemFactory = filesystemFactory;
   121 	g_Engine.physicsFactory = physicsFactory;
   122 	g_Engine.pGlobals = pGlobals;
   123 
   124 	g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   125 	if (!g_Engine.engine)
   126 	{
   127 		Error("Could not find IVEngineServer! Metamod cannot load.");
   128 		return false;
   129 	}
   130 	g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
   131 	if (!g_Engine.icvar)
   132 	{
   133 		Error("Could not find ICvar! Metamod cannot load.");
   134 		return false;
   135 	}
   136 
   137 	g_Engine.loaded = true;
   138 
   139 	//Initialize our console hooks
   140 	ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   141 
   142 	if (!g_SmmAPI.CacheCmds())
   143 	{
   144 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   145 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   146 	}
   147 
   148 
   149 	const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
   150 	if (!pluginFile) 
   151 		pluginFile = GetPluginsFile();
   152 
   153 	char full_path[260];
   154 	g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), pluginFile);
   155 
   156 	LoadPluginsFromFile(full_path);
   157 
   158 	bInFirstLevel = true;
   159 
   160 	dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
   161 
   162 	RETURN_META_VALUE(MRES_IGNORED, true);
   163 }
   164 
   165 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   166 {
   167 	g_PluginMngr.SetAllLoaded();
   168 	RETURN_META_VALUE(MRES_IGNORED, true);
   169 }
   170 
   171 //This is where the magic happens
   172 SMM_API void *CreateInterface(const char *iface, int *ret)
   173 {
   174 	if (!gParsedGameInfo)
   175 	{
   176 		gParsedGameInfo = true;
   177 		char curpath[260] = {0};
   178 		char dllpath[260] = {0};
   179 		getcwd(curpath, sizeof(curpath)-1);
   180 		if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
   181 		{
   182 			Error("GetFileOfAddress() failed! Metamod cannot load.");
   183 			return NULL;
   184 		}
   185 		SourceHook::String s_dllpath(dllpath);
   186 		//begin the heuristics for searching for the mod path (these are quite ugly).
   187 		//for OS compatibility purposes, we're going to do case insensitivity on windows.
   188 		size_t path_len = strlen(curpath);
   189 		size_t dll_len = strlen(dllpath);
   190 
   191 		//strip the dll path off
   192 		//:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
   193 		for (size_t i=dll_len-1; i>0; i--)
   194 		{
   195 			if (dllpath[i] == '\\' || dllpath[i] == '/')
   196 			{
   197 				if (i == dll_len-1)
   198 					break;
   199 				//save path by stripping off file name and ending terminator
   200 				dllpath[i] = '\0';
   201 				dll_len = i;
   202 				break;
   203 			}
   204 		}
   205 
   206 		//strip absolute path terminators if any!
   207 		if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
   208 			curpath[--path_len] = '\0';
   209 
   210 		//if the base path doesn't fit into the module path, something is wrong!
   211 		// ex: c:\games\srcds
   212 		//     c:\gaben.dll
   213 		if (path_len > dll_len)
   214 		{
   215 			Error("Could not detect GameDLL path! Metamod cannot load[1].");
   216 			return NULL;
   217 		}
   218 
   219 		//we are now in such a position that the two dir names SHOULD MATCH!
   220 		typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
   221 		STRNCMP cmp = 
   222 #ifdef WIN32
   223 			strnicmp;
   224 #else
   225 			strncmp;
   226 #endif
   227 		//are they equal?
   228 		if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
   229 		{
   230 			//:TODO: In this case, we should read /proc/self/maps and find srcds!
   231 			Error("Could not detect GameDLL path! Metamod cannot load[2].");
   232 			return NULL;
   233 		}
   234 		//this will skip past the dir and its separator char
   235 		char *ptr = &(dllpath[path_len+1]);
   236 		path_len = strlen(ptr);
   237 		for (size_t i=0; i<path_len; i++)
   238 		{
   239 			if (ptr[i] == '/' || ptr[i] == '\\')
   240 			{
   241 				if (i == 0)
   242 				{
   243 					Error("Could not detect GameDLL path! Metamod cannot load[3].");
   244 					return NULL;
   245 				} else {
   246 					ptr[i] = '\0';
   247 					path_len = i+1;
   248 					break;
   249 				}
   250 			}
   251 		}
   252 		//WE NOW HAVE A GUESS AT THE MOD DIR.  OH MY GOD.
   253 		char temp_path[260];
   254 		snprintf(temp_path, sizeof(temp_path)-1, 
   255 			"%s%s%s", 
   256 			curpath, 
   257 			PATH_SEP_STR, 
   258 			ptr);
   259 
   260 		g_ModPath.assign(temp_path);
   261 
   262 		snprintf(temp_path, sizeof(temp_path)-1, 
   263 			"%s%s%s", 
   264 			g_ModPath.c_str(),
   265 			PATH_SEP_STR,
   266 			"gameinfo.txt");
   267 
   268 		FILE *fp = fopen(temp_path, "rt");
   269 		if (!fp)
   270 		{
   271 			Error("Unable to open gameinfo.txt!  Metamod cannot load.");
   272 			return NULL;
   273 		}
   274 		char buffer[255];
   275 		char key[128], val[128];
   276 		size_t len = 0;
   277 		const char *gameinfo = "|gameinfo_path|";
   278 		size_t gameinfo_len = strlen(gameinfo);
   279 		bool search = false;
   280 		bool gamebin = false;
   281 		const char *lptr;
   282 		while (!feof(fp))
   283 		{
   284 			buffer[0] = '\0';
   285 			fgets(buffer, sizeof(buffer)-1, fp);
   286 			len = strlen(buffer);
   287 			if (buffer[len-1] == '\n')
   288 				buffer[--len] = '\0';
   289 			UTIL_TrimComments(buffer);
   290 			UTIL_TrimLeft(buffer);
   291 			UTIL_TrimRight(buffer);
   292 			if (stricmp(buffer, "SearchPaths") == 0)
   293 				search = true;
   294 			if (!search)
   295 				continue;
   296 			UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
   297 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   298 			{
   299 				if (stricmp(key, "Game") == 0)
   300 					gamebin = false;
   301 				else
   302 					gamebin = true;
   303 
   304 				if (strncmp(val, gameinfo, gameinfo_len) == 0)
   305 				{
   306 					ptr = &(val[gameinfo_len]);
   307 					if (ptr[0] == '.')
   308 						ptr++;
   309 					lptr = g_ModPath.c_str();
   310 				} else {
   311 					lptr = curpath;
   312 					ptr = val;
   313 				}
   314 				size_t ptr_len = strlen(ptr);
   315 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   316 					ptr[--ptr_len] = '\0';
   317 				//no need to append "bin"
   318 				if (gamebin)
   319 				{
   320 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   321 				} else {
   322 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   323 				}
   324 				if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
   325 				{
   326 					FILE *fp = fopen(temp_path, "rb");
   327 					if (!fp)
   328 						continue;
   329 					//:TODO: Optimize this a bit!
   330 					SourceHook::List<GameDllInfo *>::iterator iter;
   331 					GameDllInfo *pCheck;
   332 					bool found = false;
   333 					for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   334 					{
   335 						pCheck = (*iter);
   336 						if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
   337 						{
   338 							if (UTIL_PathCmp(temp_path, buffer))
   339 							{
   340 								found = true;
   341 								break;
   342 							}
   343 						}
   344 					}
   345 					if (found)
   346 						continue;
   347 					fclose(fp);
   348 					HINSTANCE gamedll = dlmount(temp_path);
   349 					if (gamedll == NULL)
   350 						continue;
   351 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   352 					if (fn == NULL)
   353 					{
   354 						dlclose(gamedll);
   355 						continue;
   356 					}
   357 					GameDllInfo *pInfo = new GameDllInfo;
   358 					pInfo->factory = fn;
   359 					pInfo->lib = gamedll;
   360 					pInfo->loaded = true;
   361 					pInfo->pGameDLL = NULL;
   362 					pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   363 					gamedll_list.push_back(pInfo);
   364 				}
   365 			}
   366 		}
   367 		fclose(fp);
   368 	}
   369 
   370 	if (!g_GameDll.loaded)
   371 	{
   372 		const char *str = "ServerGameDLL";
   373 		size_t len = strlen(str);
   374 
   375 		if (strncmp(iface, str, len) == 0)
   376 		{
   377 			//This is the interface we want!  Right now we support versions 3 and 4.
   378 			int version = atoi(&(iface[len]));
   379 			int sizeTooBig = 0;	//rename this to sizeWrong in the future!
   380 			if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
   381 			{
   382 				//maybe this will get used in the future
   383 				sizeTooBig = version;
   384 				if (ret)
   385 					*ret = IFACE_FAILED;
   386 			}
   387 			SourceHook::List<GameDllInfo *>::iterator iter;
   388 			GameDllInfo *pInfo = NULL;
   389 			void *ptr;
   390 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   391 			{
   392 				pInfo = (*iter);
   393 				ptr = (pInfo->factory)(iface, ret);
   394 				if (ptr)
   395 				{
   396 					//this is our gamedll.  unload the others.
   397 					gamedll_list.erase(iter);
   398 					ClearGamedllList();
   399 					pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
   400 					g_GameDll = *pInfo;
   401 					delete pInfo;
   402 					break;
   403 				}
   404 			}
   405 			if (g_GameDll.loaded)
   406 			{
   407 				if (sizeTooBig)
   408 				{
   409 					Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!", sizeTooBig);
   410 					if (ret)
   411 						*ret = IFACE_FAILED;
   412 					return NULL;
   413 				} else {
   414 					InitMainStates();
   415 				}
   416 			} else {
   417 				sizeTooBig = 0;
   418 				if (ret)
   419 					*ret = IFACE_FAILED;
   420 				return NULL;
   421 			}
   422 		} else {
   423 			//wtf do we do...
   424 			//:TODO: .. something a bit more intelligent?
   425 			Error("Engine requested unknown interface before GameDLL was known!");
   426 			return NULL;
   427 		}
   428 	}
   429 
   430 	//if we got here, there's definitely a gamedll.
   431 	IFACE_MACRO(g_GameDll.factory, GameDLL);
   432 }
   433 
   434 void ClearGamedllList()
   435 {
   436 	SourceHook::List<GameDllInfo *>::iterator iter;
   437 
   438 	GameDllInfo *pInfo;
   439 	for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   440 	{
   441 		pInfo = (*iter);
   442 		dlclose(pInfo->lib);
   443 		delete pInfo;
   444 	}
   445 
   446 	gamedll_list.clear();
   447 }
   448 
   449 void DLLShutdown_handler()
   450 {
   451 	//Unload plugins
   452 	g_PluginMngr.UnloadAll();
   453 
   454 	// Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
   455 	g_SMConVarAccessor.MarkCommandsAsGameDLL();
   456 	g_SMConVarAccessor.UnregisterGameDLLCommands();
   457 
   458 	SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
   459 
   460 	SH_RELEASE_CALLCLASS(dllExec);
   461 	dllExec = NULL;
   462 
   463 	g_SourceHook.CompleteShutdown();
   464 
   465 	if (g_GameDll.lib && g_GameDll.loaded)
   466 		dlclose(g_GameDll.lib);
   467 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   468 
   469 	RETURN_META(MRES_SUPERCEDE);
   470 }
   471 
   472 int LoadPluginsFromFile(const char *_file)
   473 {
   474 	FILE *fp;
   475 	int total = 0, skipped=0;
   476 	PluginId id;
   477 	bool already;
   478 
   479 	fp = fopen(_file, "rt");
   480 	if (!fp)
   481 	{
   482 		LogMessage("[META] Could not open plugins file %s\n", _file);
   483 		return -1;
   484 	}
   485 
   486 	char buffer[255], error[255], full_path[128];
   487 	const char *ptr, *ext, *file;
   488 	size_t length;
   489 	while (!feof(fp))
   490 	{
   491 		buffer[0] = '\0';
   492 		fgets(buffer, sizeof(buffer)-1, fp);
   493 		length = strlen(buffer);
   494 		if (!length)
   495 			continue;
   496 		if (buffer[length-1] == '\n')
   497 			buffer[--length] = '\0';
   498 
   499 		UTIL_TrimLeft(buffer);
   500 		UTIL_TrimRight(buffer);
   501 
   502 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   503 			continue;
   504 		file = buffer;
   505 		if (buffer[0] == '"')
   506 		{
   507 			char *cptr = buffer;
   508 			file = ++cptr;
   509 
   510 			while (*cptr)
   511 			{
   512 				if (*cptr == '"')
   513 				{
   514 					*cptr = '\0';
   515 					break;
   516 				}
   517 				cptr++;
   518 			}
   519 		} else {
   520 			char *cptr = buffer;
   521 			while (*cptr)
   522 			{
   523 				if (isspace(*cptr))
   524 				{
   525 					char *optr = cptr;
   526 					while (*cptr && isspace(*cptr))
   527 						cptr++;
   528 					*optr = '\0';
   529 					UTIL_TrimRight(cptr);
   530 					if (*cptr && isalpha(*cptr))
   531 					{
   532 						g_PluginMngr.SetAlias(buffer, cptr);
   533 						file = cptr;
   534 					}
   535 					break;
   536 				}
   537 				cptr++;
   538 			}
   539 		}
   540 		if (!file[0])
   541 		{
   542 			continue;
   543 		}
   544 		//First find if it's an absolute path or not...
   545 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   546 		{
   547 			//If we're in an absolute path, ignore our normal heuristics
   548 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error)-1);
   549 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   550 			{
   551 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   552 			} else {
   553 				if (already)
   554 					skipped++;
   555 				else
   556 					total++;
   557 			}
   558 		} else {
   559 			//Attempt to find a file extension
   560 			ptr = UTIL_GetExtension(file);
   561 			//Add an extension if there's none there
   562 			if (!ptr)
   563 			{
   564 #if defined WIN32 || defined _WIN32
   565 				ext = ".dll";
   566 #else
   567 				ext = "_i486.so";
   568 #endif
   569 			} else {
   570 				ext = "";
   571 			}
   572 			//Format the new path
   573 			g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), file, ext);
   574 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
   575 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   576 			{
   577 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   578 			} else {
   579 				if (already)
   580 					skipped++;
   581 				else
   582 					total++;
   583 			}
   584 		}
   585 	}
   586 	fclose(fp);
   587 
   588 	if (skipped)
   589 	{
   590 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   591 	} else {
   592 		LogMessage("[META] Loaded %d plugins from file.", total);
   593 	}
   594 	
   595 	return total;
   596 }
   597 
   598 //Wrapper function.  This is called when the GameDLL thinks it's using
   599 // the engine's real engineFactory.
   600 void *EngineFactory(const char *iface, int *ret)
   601 {
   602 	IFACE_MACRO(g_Engine.engineFactory, Engine);
   603 }
   604 
   605 //Wrapper function.  This is called when the GameDLL thinks it's using
   606 // the engine's real physicsFactory.
   607 void *PhysicsFactory(const char *iface, int *ret)
   608 {
   609 	IFACE_MACRO(g_Engine.physicsFactory, Physics);
   610 }
   611 
   612 //Wrapper function.  This is called when the GameDLL thinks it's using
   613 // the engine's real fileSystemFactory.
   614 void *FileSystemFactory(const char *iface, int *ret)
   615 {
   616 	IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
   617 }
   618 
   619 void LogMessage(const char *msg, ...)
   620 {
   621 	va_list ap;
   622 	static char buffer[2048];
   623 
   624 	buffer[0] = '\0';
   625 
   626 	va_start(ap, msg);
   627 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   628 	strcat(buffer, "\n");
   629 	va_end(ap);
   630 
   631 	if (!g_Engine.engine)
   632 	{
   633 		fprintf(stdout, "%s", buffer);
   634 	} else {
   635 		g_Engine.engine->LogPrint(buffer);
   636 	}
   637 }
   638 
   639 void LevelShutdown_handler(void)
   640 {
   641 	if (!bInFirstLevel)
   642 	{
   643 		char full_path[255];
   644 		g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
   645 
   646 		LoadPluginsFromFile(full_path);
   647 	} else {
   648 		bInFirstLevel = false;
   649 	}
   650 
   651 	ITER_EVENT(OnLevelShutdown, ());
   652 
   653 	RETURN_META(MRES_IGNORED);
   654 }
   655 
   656 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   657 {
   658 	if (!g_SmmAPI.CacheSuccessful())
   659 	{
   660 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   661 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   662 	}
   663 
   664 #if (defined _DEBUG || defined DEBUG) && (defined OS_WIN32)
   665     SetUnhandledExceptionFilter(NULL);
   666 #endif
   667 
   668 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   669 
   670 	RETURN_META_VALUE(MRES_IGNORED, false);
   671 }
   672 
   673 #if defined __GNUC__ && (__GNUC__ == 3)
   674 void * ::operator new(size_t size) {
   675 	return(calloc(1, size)); 
   676 }
   677 
   678 void * ::operator new[](size_t size) {
   679 	return(calloc(1, size)); 
   680 }
   681 
   682 void ::operator delete(void * ptr) {
   683 	if(ptr)
   684 		free(ptr);
   685 }
   686 
   687 void ::operator delete[](void * ptr) {
   688 	if(ptr)
   689 		free(ptr);
   690 }
   691 #endif