core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Tue May 22 20:50:48 2007 +0000 (2007-05-22)
changeset 833 732bedfcbe3e
parent 786 a04118454f26
child 848 32c29dd9c7ec
permissions -rw-r--r--
added ReplaceString and ReplaceStringEx (phew!)
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     5  * ===============================================================
     6  *
     7  * This file is not open source and may not be copied without explicit
     8  * written permission of AlliedModders LLC.  This file may not be redistributed 
     9  * in whole or significant part.
    10  * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    11  *
    12  * Version: $Id$
    13  */
    14 
    15 #include <stdio.h>
    16 #include "sourcemod.h"
    17 #include "sourcemm_api.h"
    18 #include "systems/LibrarySys.h"
    19 #include "vm/sp_vm_engine.h"
    20 #include <sh_string.h>
    21 #include "PluginSys.h"
    22 #include "ShareSys.h"
    23 #include "CoreConfig.h"
    24 #include "Logger.h"
    25 #include "ExtensionSys.h"
    26 #include "AdminCache.h"
    27 #include "sm_stringutil.h"
    28 #include "PlayerManager.h"
    29 #include "Translator.h"
    30 #include "ForwardSys.h"
    31 #include "TimerSys.h"
    32 #include "MenuStyle_Valve.h"
    33 #include "MenuStyle_Radio.h"
    34 
    35 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    36 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    37 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
    38 
    39 SourcePawnEngine g_SourcePawn;
    40 SourceModBase g_SourceMod;
    41 
    42 ILibrary *g_pJIT = NULL;
    43 SourceHook::String g_BaseDir;
    44 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
    45 IVirtualMachine *g_pVM;
    46 IdentityToken_t *g_pCoreIdent = NULL;
    47 float g_LastTime = 0.0f;
    48 float g_LastMenuTime = 0.0f;
    49 float g_LastAuthCheck = 0.0f;
    50 IForward *g_pOnGameFrame = NULL;
    51 IForward *g_pOnMapEnd = NULL;
    52 bool g_Loaded = false;
    53 int g_StillFrames = 0;
    54 float g_StillTime = 0.0f;
    55 
    56 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
    57 typedef unsigned int (*GETEXPORTCOUNT)();
    58 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
    59 typedef void (*NOTIFYSHUTDOWN)();
    60 
    61 void ShutdownJIT()
    62 {
    63 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    64 	if (notify)
    65 	{
    66 		notify();
    67 	}
    68 
    69 	g_pJIT->CloseLibrary();
    70 }
    71 
    72 SourceModBase::SourceModBase()
    73 {
    74 	m_IsMapLoading = false;
    75 	m_ExecPluginReload = false;
    76 	m_ExecOnMapEnd = false;
    77 	m_GotBasePath = false;
    78 }
    79 
    80 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key, 
    81 									  const char *value, 
    82 									  ConfigSource source, 
    83 									  char *error, 
    84 									  size_t maxlength)
    85 {
    86 	if (strcasecmp(key, "BasePath") == 0)
    87 	{
    88 		if (source == ConfigSource_Console)
    89 		{
    90 			UTIL_Format(error, maxlength, "Cannot be set at runtime");
    91 			return ConfigResult_Reject;
    92 		}
    93 
    94 		if (!m_GotBasePath)
    95 		{
    96 			g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
    97 			g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
    98 
    99 			m_GotBasePath = true;
   100 		}
   101 
   102 		return ConfigResult_Accept;
   103 	}
   104 
   105 	return ConfigResult_Ignore;
   106 }
   107 
   108 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
   109 {
   110 	const char *gamepath = g_SMAPI->GetBaseDir();
   111 
   112 	/* Store full path to game */
   113 	g_BaseDir.assign(gamepath);
   114 
   115 	/* Store name of game directory by itself */
   116 	size_t len = strlen(gamepath);
   117 	for (size_t i = len - 1; i >= 0; i--)
   118 	{
   119 		if (gamepath[i] == PLATFORM_SEP_CHAR)
   120 		{
   121 			strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
   122 			break;
   123 		}
   124 	}
   125 
   126 	/* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
   127 	g_CoreConfig.Initialize();
   128 
   129 	/* This shouldn't happen, but can't hurt to be safe */
   130 	if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
   131 	{
   132 		g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
   133 		g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
   134 		m_GotBasePath = true;
   135 	}
   136 
   137 	/* Attempt to load the JIT! */
   138 	char file[PLATFORM_MAX_PATH];
   139 	char myerror[255];
   140 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
   141 		GetSourceModPath(),
   142 		PLATFORM_LIB_EXT
   143 		);
   144 
   145 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
   146 	if (!g_pJIT)
   147 	{
   148 		if (error && maxlength)
   149 		{
   150 			snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
   151 				myerror,
   152 				PLATFORM_LIB_EXT);
   153 		}
   154 		return false;
   155 	}
   156 
   157 	int err;
   158 	GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
   159 	if (!jit_init)
   160 	{
   161 		ShutdownJIT();
   162 		if (error && maxlength)
   163 		{
   164 			snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
   165 		}
   166 		return false;
   167 	}
   168 
   169 	if ((err=jit_init(g_pSourcePawn)) != 0)
   170 	{
   171 		ShutdownJIT();
   172 		if (error && maxlength)
   173 		{
   174 			snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
   175 		}
   176 		return false;
   177 	}
   178 
   179 	GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
   180 	GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
   181 	if (!jit_get)
   182 	{
   183 		ShutdownJIT();
   184 		if (error && maxlength)
   185 		{
   186 			snprintf(error, maxlength, "JIT is missing a necessary export!");
   187 		}
   188 		return false;
   189 	}
   190 
   191 	unsigned int num = jit_getnum();
   192 	if (!num || ((g_pVM=jit_get(0)) == NULL))
   193 	{
   194 		ShutdownJIT();
   195 		if (error && maxlength)
   196 		{
   197 			snprintf(error, maxlength, "JIT did not export any virtual machines!");
   198 		}
   199 		return false;
   200 	}
   201 
   202 	unsigned int api = g_pVM->GetAPIVersion();
   203 	if (api != SOURCEPAWN_VM_API_VERSION)
   204 	{
   205 		ShutdownJIT();
   206 		if (error && maxlength)
   207 		{
   208 			snprintf(error, maxlength, "JIT is not a compatible version");
   209 		}
   210 		return false;
   211 	}
   212 
   213 	/* Hook this now so we can detect startup without calling StartSourceMod() */
   214 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   215 
   216 	/* Only load if we're not late */
   217 	if (!late)
   218 	{
   219 		StartSourceMod(false);
   220 	}
   221 
   222 	return true;
   223 }
   224 
   225 void SourceModBase::StartSourceMod(bool late)
   226 {
   227 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   228 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   229 
   230 	enginePatch = SH_GET_CALLCLASS(engine);
   231 	gamedllPatch = SH_GET_CALLCLASS(gamedll);
   232 
   233 	/* Notify! */
   234 	SMGlobalClass *pBase = SMGlobalClass::head;
   235 	while (pBase)
   236 	{
   237 		pBase->OnSourceModStartup(false);
   238 		pBase = pBase->m_pGlobalClassNext;
   239 	}
   240 
   241 	/* Make the global core identity */
   242 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   243 
   244 	/* Notify! */
   245 	pBase = SMGlobalClass::head;
   246 	while (pBase)
   247 	{
   248 		pBase->OnSourceModAllInitialized();
   249 		pBase = pBase->m_pGlobalClassNext;
   250 	}
   251 
   252 	/* Add us now... */
   253 	g_ShareSys.AddInterface(NULL, this);
   254 
   255 	/* We're loaded! */
   256 	g_Loaded = true;
   257 }
   258 
   259 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   260 {
   261 	/* If we're not loaded... */
   262 	if (!g_Loaded)
   263 	{
   264 		/* Do all global initialization now */
   265 		StartSourceMod(true);
   266 	}
   267 
   268 	m_IsMapLoading = true;
   269 	m_ExecPluginReload = true;
   270 	m_ExecOnMapEnd = true;
   271 	g_LastTime = 0.0f;
   272 	g_LastMenuTime = 0.0f;
   273 	g_LastAuthCheck = 0.0f;
   274 	g_SimTicks.ticking = true;
   275 	g_SimTicks.tickcount = 0;
   276 	g_StillTime = 0.0f;
   277 	g_StillFrames = 0;
   278 
   279 	/* Notify! */
   280 	SMGlobalClass *pBase = SMGlobalClass::head;
   281 	while (pBase)
   282 	{
   283 		pBase->OnSourceModLevelChange(pMapName);
   284 		pBase = pBase->m_pGlobalClassNext;
   285 	}
   286 
   287 	DoGlobalPluginLoads();
   288 
   289 	m_IsMapLoading = false;
   290 
   291 	/* Notify! */
   292 	pBase = SMGlobalClass::head;
   293 	while (pBase)
   294 	{
   295 		pBase->OnSourceModPluginsLoaded();
   296 		pBase = pBase->m_pGlobalClassNext;
   297 	}
   298 
   299 	if (!g_pOnGameFrame)
   300 	{
   301 		g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
   302 	}
   303 
   304 	if (!g_pOnMapEnd)
   305 	{
   306 		g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
   307 	}
   308 
   309 	RETURN_META_VALUE(MRES_IGNORED, true);
   310 }
   311 
   312 void StartTickSimulation()
   313 {
   314 	g_SimTicks.ticking = false;
   315 	g_SimTicks.tickcount = 0;
   316 	g_SimTicks.ticktime = gpGlobals->curtime;
   317 }
   318 
   319 void StopTickSimulation()
   320 {
   321 	g_SimTicks.ticking = true;
   322 	g_Timers.MapChange();
   323 	g_StillFrames = 0;
   324 	g_LastTime = gpGlobals->curtime;
   325 }
   326 
   327 void SimulateTick()
   328 {
   329 	g_SimTicks.tickcount++;
   330 	g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
   331 }
   332 
   333 void SourceModBase::GameFrame(bool simulating)
   334 {
   335 	/**
   336 	 * Note: This is all hardcoded rather than delegated to save
   337 	 * precious CPU cycles.
   338 	 */
   339 	float curtime = gpGlobals->curtime;
   340 	int framecount = gpGlobals->framecount;
   341 
   342 	/* Verify that we're still ticking */
   343 	if (g_SimTicks.ticking)
   344 	{
   345 		if (g_StillFrames == 0)
   346 		{
   347 			g_StillFrames = framecount;
   348 			g_StillTime = curtime;
   349 		} else {
   350 			/* Try to detect when we've stopped ticking.
   351 			 * We do this once 10 frames pass and there have been no ticks.
   352 			 */
   353 			if (g_StillTime == curtime)
   354 			{
   355 				if (framecount - g_StillFrames >= 5)
   356 				{
   357 					StartTickSimulation();
   358 					return;
   359 				}
   360 			} else {
   361 				/* We're definitely ticking we get here, 
   362 				 * but update everything as a precaution */
   363 				g_StillFrames = framecount;
   364 				g_StillTime = curtime;
   365 			}
   366 		}
   367 	} else {
   368 		/* We need to make sure we should still be simulating. */
   369 		if (g_StillTime != curtime)
   370 		{
   371 			/* Wow, we're ticking again! It's time to revert. */
   372 			StopTickSimulation();
   373 			return;
   374 		}
   375 		/* Nope, not ticking.  Simulate! */
   376 		SimulateTick();
   377 		curtime = g_SimTicks.ticktime;
   378 	}
   379 
   380 	if (curtime - g_LastTime >= 0.1f)
   381 	{
   382 		if (m_CheckingAuth
   383 			&& (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
   384 		{
   385 			g_LastAuthCheck = gpGlobals->curtime;
   386 			g_Players.RunAuthChecks();
   387 		}
   388 
   389 		g_Timers.RunFrame();
   390 		g_LastTime = curtime;
   391 	}
   392 
   393 	if (g_SimTicks.tickcount && (curtime - g_LastMenuTime >= 1.0f))
   394 	{
   395 		g_ValveMenuStyle.ProcessWatchList();
   396 		g_RadioMenuStyle.ProcessWatchList();
   397 		g_LastMenuTime = curtime;
   398 	}
   399 
   400 	if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
   401 	{
   402 		g_pOnGameFrame->Execute(NULL);
   403 	}
   404 }
   405 
   406 void SourceModBase::LevelShutdown()
   407 {
   408 	if (g_pOnMapEnd && m_ExecOnMapEnd)
   409 	{
   410 		g_pOnMapEnd->Execute(NULL);
   411 		m_ExecOnMapEnd = false;
   412 	}
   413 
   414 	if (m_ExecPluginReload)
   415 	{
   416 		g_PluginSys.ReloadOrUnloadPlugins();
   417 		m_ExecPluginReload = false;
   418 	}
   419 }
   420 
   421 bool SourceModBase::IsMapLoading() const
   422 {
   423 	return m_IsMapLoading;
   424 }
   425 
   426 void SourceModBase::DoGlobalPluginLoads()
   427 {
   428 	char config_path[PLATFORM_MAX_PATH];
   429 	char plugins_path[PLATFORM_MAX_PATH];
   430 
   431 	BuildPath(Path_SM, config_path, 
   432 		sizeof(config_path),
   433 		"configs/plugin_settings.cfg");
   434 	BuildPath(Path_SM, plugins_path,
   435 		sizeof(plugins_path),
   436 		"plugins");
   437 
   438 	/* Load any auto extensions */
   439 	g_Extensions.TryAutoload();
   440 
   441 	/* Run the first pass */
   442 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   443 
   444 	/* Mark any extensions as loaded */
   445 	g_Extensions.MarkAllLoaded();
   446 
   447 	/* No modules yet, it's safe to call this from here */
   448 	g_PluginSys.LoadAll_SecondPass();
   449 
   450 	/* Re-mark any extensions as loaded */
   451 	g_Extensions.MarkAllLoaded();
   452 }
   453 
   454 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
   455 {
   456 	char _buffer[PLATFORM_MAX_PATH];
   457 	va_list ap;
   458 
   459 	va_start(ap, format);
   460 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   461 	va_end(ap);
   462 
   463 	const char *base = NULL;
   464 	if (type == Path_Game)
   465 	{
   466 		base = GetGamePath();
   467 	} else if (type == Path_SM) {
   468 		base = GetSourceModPath();
   469 	} else if (type == Path_SM_Rel) {
   470 		base = m_SMRelDir;
   471 	}
   472 
   473 	if (base)
   474 	{
   475 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   476 	} else {
   477 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   478 	}
   479 }
   480 
   481 void SourceModBase::CloseSourceMod()
   482 {
   483 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   484 
   485 	if (g_Loaded)
   486 	{
   487 		if (g_pOnGameFrame)
   488 		{
   489 			g_Forwards.ReleaseForward(g_pOnGameFrame);
   490 		}
   491 
   492 		if (g_pOnMapEnd)
   493 		{
   494 			g_Forwards.ReleaseForward(g_pOnMapEnd);
   495 		}
   496 	
   497 		/* Notify! */
   498 		SMGlobalClass *pBase = SMGlobalClass::head;
   499 		while (pBase)
   500 		{
   501 			pBase->OnSourceModShutdown();
   502 			pBase = pBase->m_pGlobalClassNext;
   503 		}
   504 	
   505 		/* Delete all data packs */
   506 		CStack<CDataPack *>::iterator iter;
   507 		CDataPack *pd;
   508 		for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   509 		{
   510 			pd = (*iter);
   511 			delete pd;
   512 		}
   513 		m_freepacks.popall();
   514 	
   515 		/* Notify! */
   516 		pBase = SMGlobalClass::head;
   517 		while (pBase)
   518 		{
   519 			pBase->OnSourceModAllShutdown();
   520 			pBase = pBase->m_pGlobalClassNext;
   521 		}
   522 	
   523 		if (enginePatch)
   524 		{
   525 			SH_RELEASE_CALLCLASS(enginePatch);
   526 			enginePatch = NULL;
   527 		}
   528 	
   529 		if (gamedllPatch)
   530 		{
   531 			SH_RELEASE_CALLCLASS(gamedllPatch);
   532 			gamedllPatch = NULL;
   533 		}
   534 
   535 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   536 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   537 	}
   538 
   539 	/* Rest In Peace */
   540 	ShutdownJIT();
   541 }
   542 
   543 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   544 {
   545 	IExtensionInterface *pAPI = pExt->GetAPI();
   546 	const char *tag = pAPI->GetExtensionTag();
   547 	char buffer[2048];
   548 	va_list ap;
   549 
   550 	va_start(ap, format);
   551 	vsnprintf(buffer, sizeof(buffer), format, ap);
   552 	va_end(ap);
   553 
   554 	if (tag)
   555 	{
   556 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   557 	} else {
   558 		g_Logger.LogMessage("%s", buffer);
   559 	}
   560 }
   561 
   562 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   563 {
   564 	IExtensionInterface *pAPI = pExt->GetAPI();
   565 	const char *tag = pAPI->GetExtensionTag();
   566 	char buffer[2048];
   567 	va_list ap;
   568 
   569 	va_start(ap, format);
   570 	vsnprintf(buffer, sizeof(buffer), format, ap);
   571 	va_end(ap);
   572 
   573 	if (tag)
   574 	{
   575 		g_Logger.LogError("[%s] %s", tag, buffer);
   576 	} else {
   577 		g_Logger.LogError("%s", buffer);
   578 	}
   579 }
   580 
   581 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   582 {
   583 	char *fmt;
   584 
   585 	pContext->LocalToString(params[param], &fmt);
   586 
   587 	int lparam = ++param;
   588 
   589 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   590 }
   591 
   592 const char *SourceModBase::GetSourceModPath() const
   593 {
   594 	return m_SMBaseDir;
   595 }
   596 
   597 const char *SourceModBase::GetGamePath() const
   598 {
   599 	return g_BaseDir.c_str();
   600 }
   601 
   602 void SourceModBase::SetGlobalTarget(unsigned int index)
   603 {
   604 	m_target = index;
   605 }
   606 
   607 void SourceModBase::SetAuthChecking(bool set)
   608 {
   609 	m_CheckingAuth = set;
   610 }
   611 
   612 unsigned int SourceModBase::GetGlobalTarget() const
   613 {
   614 	return m_target;
   615 }
   616 
   617 IDataPack *SourceModBase::CreateDataPack()
   618 {
   619 	CDataPack *pack;
   620 	if (m_freepacks.empty())
   621 	{
   622 		pack = new CDataPack;
   623 	} else {
   624 		pack = m_freepacks.front();
   625 		m_freepacks.pop();
   626 		pack->Initialize();
   627 	}
   628 	return pack;
   629 }
   630 
   631 void SourceModBase::FreeDataPack(IDataPack *pack)
   632 {
   633 	m_freepacks.push(static_cast<CDataPack *>(pack));
   634 }
   635 
   636 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   637 {
   638 	//:TODO:
   639 	return 0;
   640 }
   641 
   642 const char *SourceModBase::GetGameFolderName() const
   643 {
   644 	return m_ModDir;
   645 }
   646 
   647 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
   648 {
   649 	return g_pSourcePawn;
   650 }
   651 
   652 IVirtualMachine *SourceModBase::GetScriptingVM()
   653 {
   654 	return g_pVM;
   655 }
   656 
   657 SMGlobalClass *SMGlobalClass::head = NULL;
   658 
   659 SMGlobalClass::SMGlobalClass()
   660 {
   661 	m_pGlobalClassNext = SMGlobalClass::head;
   662 	SMGlobalClass::head = this;
   663 }