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