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