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