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