core-legacy/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Tue Nov 24 07:19:57 2009 -0600 (2009-11-24)
changeset 684 8015336442cb
parent 683 b507295429f9
child 689 4065ba5e9155
permissions -rw-r--r--
Fixed SourceHook v5 includes in core to be usable on Mac OS X (bug 3514, r=ds).
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2009 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 "iplayerinfo.h"
    22 #include <filesystem.h>
    23 
    24 using namespace SourceMM;
    25 
    26 /**
    27  * @brief Implementation of main SourceMM GameDLL functionality
    28  * @file sourcemm.cpp
    29  */
    30 
    31 #undef CommandLine
    32 DLL_IMPORT ICommandLine *CommandLine();
    33 
    34 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    35 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    36 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    37 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
    38 
    39 void LevelShutdown_handler();
    40 bool LevelInit_handler(char const *pMapName,
    41 					   char const *pMapEntities,
    42 					   char const *pOldLevel,
    43 					   char const *pLandmarkName,
    44 					   bool loadGame,
    45 					   bool background);
    46 bool GameInit_handler();
    47 int LoadPlugins(const char *filepath, const char *vdfpath);
    48 int LoadVDFPluginsFromDir(const char *dir, int &skipped);
    49 bool KVLoadFromFile(KeyValues *kv,
    50 					IBaseFileSystem *filesystem,
    51 					const char *resourceName,
    52 					const char *pathID = NULL);
    53 
    54 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
    55 EngineInfo g_Engine;
    56 SourceHook::CSourceHookImpl g_SourceHook;
    57 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
    58 SourceHook::String g_ModPath;
    59 SourceHook::String g_MetamodPath;
    60 PluginId g_PLID = Pl_Console;			/* Technically, SourceMM is the "Console" plugin... :p */
    61 static bool bInFirstLevel = true;
    62 bool g_bGameInit = false;
    63 int g_GameDllVersion = 0;
    64 static const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
    65 static const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
    66 static const char GAMEINFO_PATH[] = "|gameinfo_path|";
    67 IFileSystem *baseFs = NULL;
    68 bool g_bLevelChanged = false;
    69 IServerPluginCallbacks *g_pRealVspCallbacks = NULL;
    70 unsigned int g_vsp_version = 0;
    71 
    72 #define ITER_EVENT(evn, args) \
    73 	CPluginManager::CPlugin *pl; \
    74 	SourceHook::List<CPluginEventHandler>::iterator event; \
    75 	IMetamodListener *api; \
    76 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    77 		pl = (*iter); \
    78 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    79 			api = (*event).event; \
    80 			api->evn args; \
    81 		} \
    82 	}
    83 
    84 ///////////////////////////////////
    85 // Main code for HL2 Interaction //
    86 ///////////////////////////////////
    87 
    88 /* Initialize everything here */
    89 void InitMainStates()
    90 {
    91 	/* Like Metamod, reload plugins at the end of the map.
    92 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
    93 	 * if the server is shut down (silly, but rare case).
    94 	 */
    95 	bInFirstLevel = true;
    96 
    97 	char smm_path[PATH_SIZE];
    98 	const char *game_dir = CommandLine()->ParmValue("-game", "hl2");
    99 	abspath(smm_path, game_dir);
   100 	g_ModPath.assign(smm_path);
   101 
   102 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
   103 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
   104 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
   105 }
   106 
   107 void DoInitialPluginLoads()
   108 {
   109 	const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
   110 	const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
   111 
   112 	if (!pluginFile) 
   113 	{
   114 		pluginFile = GetPluginsFile();
   115 	}
   116 	if (!mmBaseDir)
   117 	{
   118 		mmBaseDir = GetMetamodBaseDir();
   119 	}
   120 
   121 	char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   122 
   123 	g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), pluginFile);
   124 	g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), mmBaseDir);
   125 	LoadPlugins(filepath, vdfpath);
   126 }
   127 
   128 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
   129 {
   130 	g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   131 
   132 	if (!g_Engine.engine)
   133 	{
   134 		Error("Could not find IVEngineServer! Metamod cannot load.");
   135 		return false;
   136 	}
   137 	g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
   138 	if (!g_Engine.icvar)
   139 	{
   140 		Error("Could not find ICvar! Metamod cannot load.");
   141 		return false;
   142 	}
   143 
   144 	g_Engine.loaded = true;
   145 
   146 	/* The Ship is the only game known at this time that uses the pre-Episode One engine */
   147 	g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
   148 
   149 	ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   150 
   151 	if (g_GameDll.pGameClients)
   152 	{
   153 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
   154 	}
   155 	else
   156 	{
   157 		/* If IServerGameClients isn't found, this really isn't a fatal error so... */
   158 		LogMessage("[META] Warning: Could not find IServerGameClients!");
   159 		LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
   160 	}
   161 
   162 	if (!g_SmmAPI.CacheCmds())
   163 	{
   164 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   165 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   166 	}
   167 
   168 	if (!g_SmmAPI.CacheUserMessages())
   169 	{
   170 		/* Don't know of a mod that has stripped out user messages completely, 
   171 		 * but perhaps should do something different here?
   172 		 */
   173 		LogMessage("[META] Warning: Failed to get list of user messages.");
   174 		LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
   175 	}
   176 
   177 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   178 	if (baseFs == NULL)
   179 	{
   180 		LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
   181 	}
   182 
   183 	if (!g_SMConVarAccessor.InitConCommandBaseList())
   184 	{
   185 		/* This is very unlikely considering it's old engine */
   186 		LogMessage("[META] Warning: Failed to find ConCommandBase list!");
   187 		LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
   188 	}
   189 
   190 	if (!bWaitForGameInit)
   191 	{
   192 		DoInitialPluginLoads();
   193 		bInFirstLevel = true;
   194 	}
   195 
   196 	return true;
   197 }
   198 
   199 void LoadAsGameDLL(const gamedll_bridge_info *info)
   200 {
   201 	g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
   202 	g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
   203 	g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
   204 	g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
   205 	g_GameDll.loaded = true;
   206 	g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
   207 	g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
   208 	g_GameDllVersion = info->dllVersion;
   209 	g_MetamodPath.assign(info->vsp_listener_path);
   210 
   211 	InitMainStates();
   212 
   213 	StartupMetamod(g_Engine.engineFactory, false);
   214 }
   215 
   216 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
   217 {
   218 	g_Engine.engineFactory = ifaceFactory;
   219 	g_Engine.fileSystemFactory = ifaceFactory;
   220 	g_Engine.physicsFactory = ifaceFactory;
   221 
   222 	IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
   223 	if (playerInfoManager == NULL)
   224 	{
   225 		Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
   226 		return false;
   227 	}
   228 
   229 	g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
   230 
   231 	/* Now find the server */
   232 	g_GameDll.factory = serverFactory;
   233 
   234 	char gamedll_iface[] = "ServerGameDLL000";
   235 	for (unsigned int i = 3; i <= 50; i++)
   236 	{
   237 		gamedll_iface[15] = '0' + i;
   238 		g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
   239 		if (g_GameDll.pGameDLL != NULL)
   240 		{
   241 			g_GameDllVersion = i;
   242 			break;
   243 		}
   244 	}
   245 
   246 	if (g_GameDll.pGameDLL == NULL)
   247 	{
   248 		Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
   249 		return false;
   250 	}
   251 
   252 	char gameclients_iface[] = "ServerGameClients000";
   253 	for (unsigned int i = 3; i <= 4; i++)
   254 	{
   255 		gameclients_iface[19] = '0' + i;
   256 		g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
   257 		if (g_GameDll.pGameClients != NULL)
   258 		{
   259 			break;
   260 		}
   261 	}
   262 
   263 	InitMainStates();
   264 
   265 	if (!StartupMetamod(ifaceFactory, true))
   266 	{
   267 		return false;
   268 	}
   269 
   270 	return true;
   271 }
   272 
   273 bool GameInit_handler()
   274 {
   275 	if (g_bGameInit)
   276 		RETURN_META_VALUE(MRES_IGNORED, true);
   277 
   278 	if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
   279 		g_SmmAPI.LoadAsVSP();
   280 
   281 	if (g_bIsBridgedAsVsp)
   282 	{
   283 		DoInitialPluginLoads();
   284 		g_PluginMngr.SetAllLoaded();
   285 	}
   286 
   287 	g_bGameInit = true;
   288 
   289 	RETURN_META_VALUE(MRES_IGNORED, true);
   290 }
   291 
   292 void UnloadMetamod(bool shutting_down)
   293 {
   294 	/* Unload plugins */
   295 	g_PluginMngr.UnloadAll();
   296 
   297 	if (shutting_down)
   298 	{
   299 		/* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
   300 		g_SMConVarAccessor.MarkCommandsAsGameDLL();
   301 		g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
   302 	}
   303 
   304 	g_SourceHook.CompleteShutdown();
   305 }
   306 
   307 bool LoadFromVDF(const char *file, bool &skipped)
   308 {
   309 	PluginId id;
   310 	bool already, kvfileLoaded;
   311 	KeyValues *pValues;
   312 	const char *plugin_file, *alias;
   313 	char full_path[256], error[256];
   314 	
   315 	pValues = new KeyValues("Metamod Plugin");
   316 
   317 	if (g_Engine.original)
   318 	{
   319 		/* The Ship must use a special version of this function */
   320 		kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
   321 	}
   322 	else
   323 	{
   324 		kvfileLoaded = pValues->LoadFromFile(baseFs, file);
   325 	}
   326 
   327 	if (!kvfileLoaded)
   328 	{
   329 		pValues->deleteThis();
   330 		skipped = false;
   331 		return false;
   332 	}
   333 
   334 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   335 	{
   336 		pValues->deleteThis();
   337 		skipped = false;
   338 		return false;
   339 	}
   340 
   341 	if ((alias = pValues->GetString("alias", NULL)) != NULL)
   342 	{
   343 		g_PluginMngr.SetAlias(alias, plugin_file);
   344 	}
   345 
   346 	/* Attempt to find a file extension */
   347 	if (UTIL_GetExtension(plugin_file) == NULL)
   348 	{
   349 		g_SmmAPI.PathFormat(full_path, 
   350 			sizeof(full_path), 
   351 			"%s/%s%s", 
   352 			g_ModPath.c_str(), 
   353 			plugin_file, 
   354 #if defined WIN32 || defined _WIN32
   355 			".dll"
   356 #else
   357 			"_i486.so"
   358 #endif
   359 			);
   360 	}
   361 	else
   362 	{
   363 		g_SmmAPI.PathFormat(full_path,
   364 			sizeof(full_path),
   365 			"%s/%s", 
   366 			g_ModPath.c_str(),
   367 			plugin_file);
   368 	}
   369 
   370 	id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   371 	skipped = already;
   372 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   373 	{
   374 		LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
   375 		return false;
   376 	}
   377 
   378 	pValues->deleteThis();
   379 	return true;
   380 }
   381 
   382 int LoadVDFPluginsFromDir(const char *dir, int &skipped)
   383 {
   384 	bool success, skip;
   385 	int total = 0;
   386 	char path[MAX_PATH];
   387 
   388 	skipped = 0;
   389 
   390 #if defined _MSC_VER
   391 	HANDLE hFind;
   392 	WIN32_FIND_DATA fd;
   393 	char error[255];
   394 
   395 	g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
   396 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
   397 	{
   398 		DWORD dw = GetLastError();
   399 		if (dw == ERROR_FILE_NOT_FOUND)
   400 			return 0;
   401 
   402 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   403 			NULL,
   404 			dw,
   405 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   406 			error,
   407 			sizeof(error),
   408 			NULL);
   409 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
   410 		return 0;
   411 	}
   412 
   413 	do
   414 	{
   415 		g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
   416 		success = LoadFromVDF(path, skip);
   417 		if (skip)
   418 			skipped++;
   419 		else if (success)
   420 			total++;
   421 	} while (FindNextFile(hFind, &fd));
   422 
   423 	FindClose(hFind);
   424 #else
   425 	DIR *pDir;
   426 	struct dirent *pEnt;
   427 	int extidx;
   428 
   429 	if ((pDir = opendir(dir)) == NULL)
   430 	{
   431 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
   432 		return 0;
   433 	}
   434 
   435 	while ((pEnt = readdir(pDir)) != NULL)
   436 	{
   437 		if (strcmp(pEnt->d_name, ".") == 0
   438 			|| strcmp(pEnt->d_name, "..") == 0)
   439 		{
   440 			continue;
   441 		}
   442 		extidx = strlen(pEnt->d_name) - 4;
   443 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
   444 		{
   445 			continue;
   446 		}
   447 		g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
   448 		success = LoadFromVDF(path, skip);
   449 		if (skip)
   450 			skipped++;
   451 		else if (success)
   452 			total++;
   453 	}
   454 
   455 	closedir(pDir);
   456 #endif
   457 
   458 	return total;
   459 }
   460 
   461 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
   462 {
   463 	Assert(filesystem);
   464 #ifdef _MSC_VER
   465 	Assert(_heapchk() == _HEAPOK);
   466 #endif
   467 
   468 	FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
   469 	if (!f)
   470 		return false;
   471 
   472 	// load file into a null-terminated buffer
   473 	int fileSize = filesystem->Size(f);
   474 	char *buffer = (char *)MemAllocScratch(fileSize + 1);
   475 	
   476 	Assert(buffer);
   477 	
   478 	filesystem->Read(buffer, fileSize, f); // read into local buffer
   479 
   480 	buffer[fileSize] = 0; // null terminate file as EOF
   481 
   482 	filesystem->Close( f );	// close file after reading
   483 
   484 	bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
   485 
   486 	MemFreeScratch();
   487 
   488 	return retOK;
   489 }
   490 
   491 int LoadPluginsFromFile(const char *filepath, int &skipped)
   492 {
   493 	FILE *fp;
   494 	int total = 0;
   495 	PluginId id;
   496 	bool already;
   497 
   498 	skipped = 0;
   499 
   500 	fp = fopen(filepath, "rt");
   501 	if (!fp)
   502 	{
   503 		return 0;
   504 	}
   505 
   506 	char buffer[255], error[255], full_path[PATH_SIZE];
   507 	const char *ptr, *ext, *file;
   508 	size_t length;
   509 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   510 	{
   511 		UTIL_TrimLeft(buffer);
   512 		UTIL_TrimRight(buffer);
   513 
   514 		length = strlen(buffer);
   515 		if (!length)
   516 		{
   517 			continue;
   518 		}
   519 
   520 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   521 		{
   522 			continue;
   523 		}
   524 
   525 		file = buffer;
   526 		if (buffer[0] == '"')
   527 		{
   528 			char *cptr = buffer;
   529 			file = ++cptr;
   530 
   531 			while (*cptr)
   532 			{
   533 				if (*cptr == '"')
   534 				{
   535 					*cptr = '\0';
   536 					break;
   537 				}
   538 				cptr++;
   539 			}
   540 		}
   541 		else
   542 		{
   543 			char *cptr = buffer;
   544 			while (*cptr)
   545 			{
   546 				if (isspace(*cptr))
   547 				{
   548 					char *optr = cptr;
   549 					while (*cptr && isspace(*cptr))
   550 					{
   551 						cptr++;
   552 					}
   553 					*optr = '\0';
   554 					UTIL_TrimRight(cptr);
   555 					if (*cptr && isalpha(*cptr))
   556 					{
   557 						g_PluginMngr.SetAlias(buffer, cptr);
   558 						file = cptr;
   559 					}
   560 					break;
   561 				}
   562 				cptr++;
   563 			}
   564 		}
   565 		if (!file[0])
   566 		{
   567 			continue;
   568 		}
   569 		/* First find if it's an absolute path or not... */
   570 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   571 		{
   572 			/* If we're in an absolute path, ignore our normal heuristics */
   573 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   574 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   575 			{
   576 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   577 			}
   578 			else
   579 			{
   580 				if (already)
   581 				{
   582 					skipped++;
   583 				}
   584 				else
   585 				{
   586 					total++;
   587 				}
   588 			}
   589 		}
   590 		else
   591 		{
   592 			/* Attempt to find a file extension */
   593 			ptr = UTIL_GetExtension(file);
   594 			/* Add an extension if there's none there */
   595 			if (!ptr)
   596 			{
   597 #if defined WIN32 || defined _WIN32
   598 				ext = ".dll";
   599 #else
   600 				ext = "_i486.so";
   601 #endif
   602 			}
   603 			else
   604 			{
   605 				ext = "";
   606 			}
   607 			/* Format the new path */
   608 			g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
   609 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   610 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   611 			{
   612 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   613 			}
   614 			else
   615 			{
   616 				if (already)
   617 				{
   618 					skipped++;
   619 				}
   620 				else
   621 				{
   622 					total++;
   623 				}
   624 			}
   625 		}
   626 	}
   627 	fclose(fp);
   628 
   629 	return total;
   630 }
   631 
   632 int LoadPlugins(const char *filepath, const char *vdfpath)
   633 {
   634 	int total, skipped, fskipped, vskipped;
   635 	const char *s = "";
   636 
   637 	total = LoadPluginsFromFile(filepath, fskipped);
   638 	total += LoadVDFPluginsFromDir(vdfpath, vskipped);
   639 	skipped = fskipped + vskipped;
   640 
   641 	if (total == 0 || total > 1)
   642 		s = "s";
   643 
   644 	if (skipped)
   645 		LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
   646 	else
   647 		LogMessage("[META] Loaded %d plugin%s.", total, s);
   648 
   649 	return total;
   650 }
   651 
   652 void LogMessage(const char *msg, ...)
   653 {
   654 	va_list ap;
   655 	static char buffer[2048];
   656 
   657 	va_start(ap, msg);
   658 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   659 	va_end(ap);
   660 
   661 	buffer[len++] = '\n';
   662 	buffer[len] = '\0';
   663 
   664 	if (!g_Engine.engine)
   665 	{
   666 		fprintf(stdout, "%s", buffer);
   667 	} else {
   668 		g_Engine.engine->LogPrint(buffer);
   669 	}
   670 }
   671 
   672 void LevelShutdown_handler(void)
   673 {
   674 	if (!bInFirstLevel)
   675 	{
   676 		char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   677 
   678 		g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
   679 		g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
   680 		LoadPlugins(filepath, vdfpath);
   681 	}
   682 	else
   683 	{
   684 		bInFirstLevel = false;
   685 	}
   686 
   687 	g_bLevelChanged = true;
   688 
   689 	ITER_EVENT(OnLevelShutdown, ());
   690 
   691 	RETURN_META(MRES_IGNORED);
   692 }
   693 
   694 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   695 {
   696 	if (!g_SmmAPI.CmdCacheSuccessful())
   697 	{
   698 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   699 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   700 	}
   701 
   702 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   703 
   704 	RETURN_META_VALUE(MRES_IGNORED, false);
   705 }
   706 
   707 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
   708 void * operator new(size_t size) {
   709 	return(calloc(1, size)); 
   710 }
   711 
   712 void * operator new[](size_t size) {
   713 	return(calloc(1, size)); 
   714 }
   715 
   716 void operator delete(void * ptr) {
   717 	if(ptr)
   718 		free(ptr);
   719 }
   720 
   721 void operator delete[](void * ptr) {
   722 	if(ptr)
   723 		free(ptr);
   724 }
   725 #endif