sourcemm/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Sat Apr 07 04:31:23 2007 +0000 (2007-04-07)
changeset 315 3af514e12267
parent 314 7666e83ef566
child 318 d601b515c839
permissions -rw-r--r--
whoops, fixed a versioning bug
     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 const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
    62 const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
    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 	/* We check these separately because we can't reply
   231 	 * unless our interface version really matches.
   232 	 */
   233 	if ((strcmp(iface, VSPIFACE_002) == 0)
   234 		|| strcmp(iface, VSPIFACE_001) == 0)
   235 	{
   236 		if (ret)
   237 		{
   238 			*ret = IFACE_OK;
   239 		}
   240 		return &g_VspListener;
   241 	}
   242 
   243 	if (!gParsedGameInfo)
   244 	{
   245 		gParsedGameInfo = true;
   246 		const char *gameDir = NULL;
   247 		char gamePath[PATH_SIZE];
   248 		char smmPath[PATH_SIZE];
   249 
   250 		/* Get path to SourceMM DLL */
   251 		if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
   252 		{
   253 			Error("GetFileOfAddress() failed! Metamod cannot load.\n");
   254 			return NULL;
   255 		}
   256 
   257 		g_SmmPath.assign(smmPath);
   258 
   259 		/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   260 		gameDir = CommandLine()->ParmValue("-game", "hl2");
   261 
   262 		/* Get absolute path */
   263 		abspath(gamePath, gameDir);
   264 		g_ModPath.assign(gamePath);
   265 
   266 		char tempPath[PATH_SIZE];
   267 
   268 		/* Path to gameinfo.txt */
   269 		g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
   270 
   271 		FILE *fp = fopen(tempPath, "rt");
   272 
   273 		if (!fp)
   274 		{
   275 			Error("Unable to open gameinfo.txt!  Metamod cannot load.\n");
   276 			return NULL;
   277 		}
   278 
   279 		char buffer[255];
   280 		char key[128], val[128];
   281 		size_t len = 0;
   282 		bool search = false;
   283 		bool gamebin = false;
   284 		char *ptr;
   285 		const char *lptr;
   286 		char curPath[PATH_SIZE];
   287 
   288 		getcwd(curPath, PATH_SIZE);
   289 
   290 		while (!feof(fp))
   291 		{
   292 			buffer[0] = '\0';
   293 			fgets(buffer, sizeof(buffer), fp);
   294 			len = strlen(buffer);
   295 			if (buffer[len-1] == '\n')
   296 				buffer[--len] = '\0';
   297 			UTIL_TrimComments(buffer);
   298 			UTIL_TrimLeft(buffer);
   299 			UTIL_TrimRight(buffer);
   300 			if (stricmp(buffer, "SearchPaths") == 0)
   301 				search = true;
   302 			if (!search)
   303 				continue;
   304 			UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   305 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   306 			{
   307 				if (stricmp(key, "Game") == 0)
   308 					gamebin = false;
   309 				else
   310 					gamebin = true;
   311 
   312 				if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
   313 				{
   314 					ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
   315 					if (ptr[0] == '.')
   316 						ptr++;
   317 					lptr = g_ModPath.c_str();
   318 				} else {
   319 					ptr = val;
   320 					lptr = curPath;
   321 				}
   322 
   323 				size_t ptr_len = strlen(ptr);
   324 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   325 					ptr[--ptr_len] = '\0';
   326 
   327 				/* No need to append "bin" if key is GameBin */
   328 				if (gamebin)
   329 				{
   330 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   331 				} else if (!ptr[0]) {
   332 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
   333 				} else {
   334 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   335 				}
   336 
   337 				/* If not path to SourceMM... */
   338 				if (!UTIL_PathCmp(smmPath, tempPath))
   339 				{
   340 					FILE *fp = fopen(tempPath, "rb");
   341 					if (!fp)
   342 						continue;
   343 					//:TODO: Optimize this a bit!
   344 					SourceHook::List<GameDllInfo *>::iterator iter;
   345 					GameDllInfo *pCheck;
   346 					bool found = false;
   347 					for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   348 					{
   349 						pCheck = (*iter);
   350 						if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
   351 						{
   352 							if (UTIL_PathCmp(tempPath, buffer))
   353 							{
   354 								found = true;
   355 								break;
   356 							}
   357 						}
   358 					}
   359 					if (found)
   360 						continue;
   361 					fclose(fp);
   362 					HINSTANCE gamedll = dlmount(tempPath);
   363 					if (gamedll == NULL)
   364 						continue;
   365 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   366 					if (fn == NULL)
   367 					{
   368 						dlclose(gamedll);
   369 						continue;
   370 					}
   371 					GameDllInfo *pInfo = new GameDllInfo;
   372 					pInfo->factory = fn;
   373 					pInfo->lib = gamedll;
   374 					pInfo->loaded = true;
   375 					pInfo->pGameDLL = NULL;
   376 					pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   377 					gamedll_list.push_back(pInfo);
   378 					break;
   379 				}
   380 			}
   381 		}
   382 		fclose(fp);
   383 	}
   384 
   385 	if (!g_GameDll.loaded)
   386 	{
   387 		const char *str = "ServerGameDLL";
   388 		size_t len = strlen(str);
   389 
   390 		if (strncmp(iface, str, len) == 0)
   391 		{
   392 			/* This is the interface we want!  Right now we support versions 3 through 8 */
   393 			g_GameDllVersion = atoi(&(iface[len]));
   394 			int sizeTooBig = 0;	//rename this to sizeWrong in the future!
   395 			if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
   396 			{
   397 				/* Maybe this will get used in the future */
   398 				sizeTooBig = g_GameDllVersion;
   399 				if (ret)
   400 				{
   401 					*ret = IFACE_FAILED;
   402 				}
   403 			}
   404 			SourceHook::List<GameDllInfo *>::iterator iter;
   405 			GameDllInfo *pInfo = NULL;
   406 			void *ptr;
   407 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   408 			{
   409 				pInfo = (*iter);
   410 				ptr = (pInfo->factory)(iface, ret);
   411 				if (ptr)
   412 				{
   413 					/* This is our GameDLL. Unload the others. */
   414 					gamedll_list.erase(iter);
   415 					ClearGamedllList();
   416 					pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
   417 					g_GameDll = *pInfo;
   418 					delete pInfo;
   419 					break;
   420 				}
   421 			}
   422 			if (g_GameDll.loaded)
   423 			{
   424 				if (sizeTooBig)
   425 				{
   426 					Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
   427 					if (ret)
   428 					{
   429 						*ret = IFACE_FAILED;
   430 					}
   431 					return NULL;
   432 				} else {
   433 					InitMainStates();
   434 				}
   435 			} else {
   436 				sizeTooBig = 0;
   437 				if (ret)
   438 					*ret = IFACE_FAILED;
   439 				return NULL;
   440 			}
   441 		} else {
   442 			/* wtf do we do... */
   443 			/* :TODO: .. something a bit more intelligent? */
   444 			Error("Engine requested unknown interface before GameDLL was known!\n");
   445 			return NULL;
   446 		}
   447 	}
   448 
   449 	/* If we got here, there's definitely a GameDLL */
   450 	IFACE_MACRO(g_GameDll.factory, GameDLL);
   451 }
   452 
   453 void ClearGamedllList()
   454 {
   455 	SourceHook::List<GameDllInfo *>::iterator iter;
   456 
   457 	GameDllInfo *pInfo;
   458 	for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   459 	{
   460 		pInfo = (*iter);
   461 		dlclose(pInfo->lib);
   462 		delete pInfo;
   463 	}
   464 
   465 	gamedll_list.clear();
   466 }
   467 
   468 void DLLShutdown_handler()
   469 {
   470 	/* Unload plugins */
   471 	g_PluginMngr.UnloadAll();
   472 
   473 	/* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
   474 	g_SMConVarAccessor.MarkCommandsAsGameDLL();
   475 	g_SMConVarAccessor.UnregisterGameDLLCommands();
   476 
   477 	SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
   478 
   479 	SH_RELEASE_CALLCLASS(g_GameDllPatch);
   480 	g_GameDllPatch = NULL;
   481 
   482 	g_SourceHook.CompleteShutdown();
   483 
   484 	if (g_GameDll.lib && g_GameDll.loaded)
   485 		dlclose(g_GameDll.lib);
   486 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   487 
   488 	RETURN_META(MRES_SUPERCEDE);
   489 }
   490 
   491 int LoadPluginsFromFile(const char *_file)
   492 {
   493 	FILE *fp;
   494 	int total = 0, skipped=0;
   495 	PluginId id;
   496 	bool already;
   497 
   498 	fp = fopen(_file, "rt");
   499 	if (!fp)
   500 	{
   501 		LogMessage("[META] Could not open plugins file %s\n", _file);
   502 		return -1;
   503 	}
   504 
   505 	char buffer[255], error[255], full_path[255];
   506 	const char *ptr, *ext, *file;
   507 	size_t length;
   508 	while (!feof(fp))
   509 	{
   510 		buffer[0] = '\0';
   511 		fgets(buffer, sizeof(buffer), fp);
   512 		length = strlen(buffer);
   513 		if (!length)
   514 			continue;
   515 		if (buffer[length-1] == '\n')
   516 			buffer[--length] = '\0';
   517 
   518 		UTIL_TrimLeft(buffer);
   519 		UTIL_TrimRight(buffer);
   520 
   521 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   522 			continue;
   523 		file = buffer;
   524 		if (buffer[0] == '"')
   525 		{
   526 			char *cptr = buffer;
   527 			file = ++cptr;
   528 
   529 			while (*cptr)
   530 			{
   531 				if (*cptr == '"')
   532 				{
   533 					*cptr = '\0';
   534 					break;
   535 				}
   536 				cptr++;
   537 			}
   538 		} else {
   539 			char *cptr = buffer;
   540 			while (*cptr)
   541 			{
   542 				if (isspace(*cptr))
   543 				{
   544 					char *optr = cptr;
   545 					while (*cptr && isspace(*cptr))
   546 						cptr++;
   547 					*optr = '\0';
   548 					UTIL_TrimRight(cptr);
   549 					if (*cptr && isalpha(*cptr))
   550 					{
   551 						g_PluginMngr.SetAlias(buffer, cptr);
   552 						file = cptr;
   553 					}
   554 					break;
   555 				}
   556 				cptr++;
   557 			}
   558 		}
   559 		if (!file[0])
   560 		{
   561 			continue;
   562 		}
   563 		/* First find if it's an absolute path or not... */
   564 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   565 		{
   566 			/* If we're in an absolute path, ignore our normal heuristics */
   567 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   568 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   569 			{
   570 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   571 			} else {
   572 				if (already)
   573 					skipped++;
   574 				else
   575 					total++;
   576 			}
   577 		} else {
   578 			/* Attempt to find a file extension */
   579 			ptr = UTIL_GetExtension(file);
   580 			/* Add an extension if there's none there */
   581 			if (!ptr)
   582 			{
   583 #if defined WIN32 || defined _WIN32
   584 				ext = ".dll";
   585 #else
   586 				ext = "_i486.so";
   587 #endif
   588 			} else {
   589 				ext = "";
   590 			}
   591 			/* Format the new path */
   592 			g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
   593 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   594 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   595 			{
   596 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   597 			} else {
   598 				if (already)
   599 					skipped++;
   600 				else
   601 					total++;
   602 			}
   603 		}
   604 	}
   605 	fclose(fp);
   606 
   607 	if (skipped)
   608 	{
   609 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   610 	} else {
   611 		LogMessage("[META] Loaded %d plugins from file.", total);
   612 	}
   613 	
   614 	return total;
   615 }
   616 
   617 /* Wrapper function.  This is called when the GameDLL thinks it's using
   618  * the engine's real engineFactory.
   619  */
   620 void *EngineFactory(const char *iface, int *ret)
   621 {
   622 	IFACE_MACRO(g_Engine.engineFactory, Engine);
   623 }
   624 
   625 /* Wrapper function.  This is called when the GameDLL thinks it's using
   626  * the engine's real physicsFactory.
   627  */
   628 void *PhysicsFactory(const char *iface, int *ret)
   629 {
   630 	IFACE_MACRO(g_Engine.physicsFactory, Physics);
   631 }
   632 
   633 /* Wrapper function.  This is called when the GameDLL thinks it's using
   634  * the engine's real fileSystemFactory.
   635  */
   636 void *FileSystemFactory(const char *iface, int *ret)
   637 {
   638 	IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
   639 }
   640 
   641 void LogMessage(const char *msg, ...)
   642 {
   643 	va_list ap;
   644 	static char buffer[2048];
   645 
   646 	va_start(ap, msg);
   647 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   648 	va_end(ap);
   649 
   650 	buffer[len++] = '\n';
   651 	buffer[len] = '\0';
   652 
   653 	if (!g_Engine.engine)
   654 	{
   655 		fprintf(stdout, "%s", buffer);
   656 	} else {
   657 		g_Engine.engine->LogPrint(buffer);
   658 	}
   659 }
   660 
   661 void LevelShutdown_handler(void)
   662 {
   663 	if (!bInFirstLevel)
   664 	{
   665 		char full_path[255];
   666 		g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
   667 
   668 		LoadPluginsFromFile(full_path);
   669 	} else {
   670 		bInFirstLevel = false;
   671 	}
   672 
   673 	ITER_EVENT(OnLevelShutdown, ());
   674 
   675 	RETURN_META(MRES_IGNORED);
   676 }
   677 
   678 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   679 {
   680 	if (!g_SmmAPI.CmdCacheSuccessful())
   681 	{
   682 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   683 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   684 	}
   685 
   686 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   687 
   688 	RETURN_META_VALUE(MRES_IGNORED, false);
   689 }
   690 
   691 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
   692 void * operator new(size_t size) {
   693 	return(calloc(1, size)); 
   694 }
   695 
   696 void * operator new[](size_t size) {
   697 	return(calloc(1, size)); 
   698 }
   699 
   700 void operator delete(void * ptr) {
   701 	if(ptr)
   702 		free(ptr);
   703 }
   704 
   705 void operator delete[](void * ptr) {
   706 	if(ptr)
   707 		free(ptr);
   708 }
   709 #endif