core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Thu Apr 12 20:18:24 2007 +0000 (2007-04-12)
changeset 688 0b99367c7a5a
parent 673 fc1d50579d06
child 696 d5cc8d0fa899
permissions -rw-r--r--
fixed amb193
     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 
    33 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    34 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    35 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
    36 
    37 SourcePawnEngine g_SourcePawn;
    38 SourceModBase g_SourceMod;
    39 
    40 ILibrary *g_pJIT = NULL;
    41 SourceHook::String g_BaseDir;
    42 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
    43 IVirtualMachine *g_pVM;
    44 IdentityToken_t *g_pCoreIdent = NULL;
    45 float g_LastTime = 0.0f;
    46 float g_LastAuthCheck = 0.0f;
    47 IForward *g_pOnGameFrame = NULL;
    48 bool g_Loaded = false;
    49 
    50 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
    51 typedef unsigned int (*GETEXPORTCOUNT)();
    52 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
    53 typedef void (*NOTIFYSHUTDOWN)();
    54 
    55 void ShutdownJIT()
    56 {
    57 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    58 	if (notify)
    59 	{
    60 		notify();
    61 	}
    62 
    63 	g_pJIT->CloseLibrary();
    64 }
    65 
    66 SourceModBase::SourceModBase()
    67 {
    68 	m_IsMapLoading = false;
    69 	m_ExecPluginReload = false;
    70 	m_GotBasePath = false;
    71 }
    72 
    73 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key, 
    74 									  const char *value, 
    75 									  ConfigSource source, 
    76 									  char *error, 
    77 									  size_t maxlength)
    78 {
    79 	if (strcasecmp(key, "BasePath") == 0)
    80 	{
    81 		if (source == ConfigSource_Console)
    82 		{
    83 			UTIL_Format(error, maxlength, "Cannot be set at runtime");
    84 			return ConfigResult_Reject;
    85 		}
    86 
    87 		if (!m_GotBasePath)
    88 		{
    89 			g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
    90 			g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
    91 
    92 			m_GotBasePath = true;
    93 		}
    94 
    95 		return ConfigResult_Accept;
    96 	}
    97 
    98 	return ConfigResult_Ignore;
    99 }
   100 
   101 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
   102 {
   103 	g_BaseDir.assign(g_SMAPI->GetBaseDir());
   104 
   105 	/* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
   106 	g_CoreConfig.Initialize();
   107 
   108 	/* This shouldn't happen, but can't hurt to be safe */
   109 	if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
   110 	{
   111 		g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
   112 		g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
   113 		m_GotBasePath = true;
   114 	}
   115 
   116 	/* Attempt to load the JIT! */
   117 	char file[PLATFORM_MAX_PATH];
   118 	char myerror[255];
   119 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
   120 		GetSourceModPath(),
   121 		PLATFORM_LIB_EXT
   122 		);
   123 
   124 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
   125 	if (!g_pJIT)
   126 	{
   127 		if (error && err_max)
   128 		{
   129 			snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
   130 				myerror,
   131 				PLATFORM_LIB_EXT);
   132 		}
   133 		return false;
   134 	}
   135 
   136 	int err;
   137 	GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
   138 	if (!jit_init)
   139 	{
   140 		ShutdownJIT();
   141 		if (error && err_max)
   142 		{
   143 			snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
   144 		}
   145 		return false;
   146 	}
   147 
   148 	if ((err=jit_init(g_pSourcePawn)) != 0)
   149 	{
   150 		ShutdownJIT();
   151 		if (error && err_max)
   152 		{
   153 			snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
   154 		}
   155 		return false;
   156 	}
   157 
   158 	GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
   159 	GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
   160 	if (!jit_get)
   161 	{
   162 		ShutdownJIT();
   163 		if (error && err_max)
   164 		{
   165 			snprintf(error, err_max, "JIT is missing a necessary export!");
   166 		}
   167 		return false;
   168 	}
   169 
   170 	unsigned int num = jit_getnum();
   171 	if (!num || ((g_pVM=jit_get(0)) == NULL))
   172 	{
   173 		ShutdownJIT();
   174 		if (error && err_max)
   175 		{
   176 			snprintf(error, err_max, "JIT did not export any virtual machines!");
   177 		}
   178 		return false;
   179 	}
   180 
   181 	unsigned int api = g_pVM->GetAPIVersion();
   182 	if (api != SOURCEPAWN_VM_API_VERSION)
   183 	{
   184 		ShutdownJIT();
   185 		if (error && err_max)
   186 		{
   187 			snprintf(error, err_max, "JIT is not a compatible version");
   188 		}
   189 		return false;
   190 	}
   191 
   192 	/* Hook this now so we can detect startup without calling StartSourceMod() */
   193 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   194 
   195 	/* Only load if we're not late */
   196 	if (!late)
   197 	{
   198 		StartSourceMod(false);
   199 	}
   200 
   201 	return true;
   202 }
   203 
   204 void SourceModBase::StartSourceMod(bool late)
   205 {
   206 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   207 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   208 
   209 	enginePatch = SH_GET_CALLCLASS(engine);
   210 	gamedllPatch = SH_GET_CALLCLASS(gamedll);
   211 
   212 	/* Notify! */
   213 	SMGlobalClass *pBase = SMGlobalClass::head;
   214 	while (pBase)
   215 	{
   216 		pBase->OnSourceModStartup(false);
   217 		pBase = pBase->m_pGlobalClassNext;
   218 	}
   219 
   220 	/* Make the global core identity */
   221 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   222 
   223 	/* Notify! */
   224 	pBase = SMGlobalClass::head;
   225 	while (pBase)
   226 	{
   227 		pBase->OnSourceModAllInitialized();
   228 		pBase = pBase->m_pGlobalClassNext;
   229 	}
   230 
   231 	/* Add us now... */
   232 	g_ShareSys.AddInterface(NULL, this);
   233 
   234 	/* We're loaded! */
   235 	g_Loaded = true;
   236 }
   237 
   238 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   239 {
   240 	/* If we're not loaded... */
   241 	if (!g_Loaded)
   242 	{
   243 		/* Do all global initialization now */
   244 		StartSourceMod(true);
   245 	}
   246 
   247 	m_IsMapLoading = true;
   248 	m_ExecPluginReload = true;
   249 	g_LastTime = 0.0f;
   250 	g_LastAuthCheck = 0.0f;
   251 
   252 	/* Notify! */
   253 	SMGlobalClass *pBase = SMGlobalClass::head;
   254 	while (pBase)
   255 	{
   256 		pBase->OnSourceModLevelChange(pMapName);
   257 		pBase = pBase->m_pGlobalClassNext;
   258 	}
   259 
   260 	DoGlobalPluginLoads();
   261 
   262 	m_IsMapLoading = false;
   263 
   264 	/* Notify! */
   265 	pBase = SMGlobalClass::head;
   266 	while (pBase)
   267 	{
   268 		pBase->OnSourceModPluginsLoaded();
   269 		pBase = pBase->m_pGlobalClassNext;
   270 	}
   271 
   272 	if (!g_pOnGameFrame)
   273 	{
   274 		g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
   275 	}
   276 
   277 	RETURN_META_VALUE(MRES_IGNORED, true);
   278 }
   279 
   280 void SourceModBase::GameFrame(bool simulating)
   281 {
   282 	/**
   283 	 * Note: This is all hardcoded rather than delegated to save
   284 	 * precious CPU cycles.
   285 	 */
   286 	float curtime = gpGlobals->curtime;
   287 	if (curtime - g_LastTime >= 0.1f)
   288 	{
   289 		if (m_CheckingAuth
   290 			&& (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
   291 		{
   292 			g_LastAuthCheck = gpGlobals->curtime;
   293 			g_Players.RunAuthChecks();
   294 		}
   295 
   296 		g_Timers.RunFrame();
   297 		g_LastTime = curtime;
   298 	}
   299 
   300 	if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
   301 	{
   302 		g_pOnGameFrame->Execute(NULL);
   303 	}
   304 }
   305 
   306 void SourceModBase::LevelShutdown()
   307 {
   308 	if (m_ExecPluginReload)
   309 	{
   310 		g_PluginSys.ReloadOrUnloadPlugins();
   311 		m_ExecPluginReload = false;
   312 	}
   313 }
   314 
   315 bool SourceModBase::IsMapLoading() const
   316 {
   317 	return m_IsMapLoading;
   318 }
   319 
   320 void SourceModBase::DoGlobalPluginLoads()
   321 {
   322 	char config_path[PLATFORM_MAX_PATH];
   323 	char plugins_path[PLATFORM_MAX_PATH];
   324 
   325 	BuildPath(Path_SM, config_path, 
   326 		sizeof(config_path),
   327 		"configs/plugin_settings.cfg");
   328 	BuildPath(Path_SM, plugins_path,
   329 		sizeof(plugins_path),
   330 		"plugins");
   331 
   332 	/* Load any auto extensions */
   333 	g_Extensions.TryAutoload();
   334 
   335 	/* Run the first pass */
   336 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   337 
   338 	/* Mark any extensions as loaded */
   339 	g_Extensions.MarkAllLoaded();
   340 
   341 	/* No modules yet, it's safe to call this from here */
   342 	g_PluginSys.LoadAll_SecondPass();
   343 
   344 	/* Re-mark any extensions as loaded */
   345 	g_Extensions.MarkAllLoaded();
   346 }
   347 
   348 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
   349 {
   350 	char _buffer[PLATFORM_MAX_PATH];
   351 	va_list ap;
   352 
   353 	va_start(ap, format);
   354 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   355 	va_end(ap);
   356 
   357 	const char *base = NULL;
   358 	if (type == Path_Game)
   359 	{
   360 		base = GetModPath();
   361 	} else if (type == Path_SM) {
   362 		base = GetSourceModPath();
   363 	} else if (type == Path_SM_Rel) {
   364 		base = m_SMRelDir;
   365 	}
   366 
   367 	if (base)
   368 	{
   369 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   370 	} else {
   371 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   372 	}
   373 }
   374 
   375 void SourceModBase::CloseSourceMod()
   376 {
   377 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   378 
   379 	if (g_Loaded)
   380 	{
   381 		if (g_pOnGameFrame)
   382 		{
   383 			g_Forwards.ReleaseForward(g_pOnGameFrame);
   384 		}
   385 	
   386 		/* Notify! */
   387 		SMGlobalClass *pBase = SMGlobalClass::head;
   388 		while (pBase)
   389 		{
   390 			pBase->OnSourceModShutdown();
   391 			pBase = pBase->m_pGlobalClassNext;
   392 		}
   393 	
   394 		/* Delete all data packs */
   395 		CStack<CDataPack *>::iterator iter;
   396 		CDataPack *pd;
   397 		for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   398 		{
   399 			pd = (*iter);
   400 			delete pd;
   401 		}
   402 		m_freepacks.popall();
   403 	
   404 		/* Notify! */
   405 		pBase = SMGlobalClass::head;
   406 		while (pBase)
   407 		{
   408 			pBase->OnSourceModAllShutdown();
   409 			pBase = pBase->m_pGlobalClassNext;
   410 		}
   411 	
   412 		if (enginePatch)
   413 		{
   414 			SH_RELEASE_CALLCLASS(enginePatch);
   415 			enginePatch = NULL;
   416 		}
   417 	
   418 		if (gamedllPatch)
   419 		{
   420 			SH_RELEASE_CALLCLASS(gamedllPatch);
   421 			gamedllPatch = NULL;
   422 		}
   423 
   424 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   425 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   426 	}
   427 
   428 	/* Rest In Peace */
   429 	ShutdownJIT();
   430 }
   431 
   432 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   433 {
   434 	IExtensionInterface *pAPI = pExt->GetAPI();
   435 	const char *tag = pAPI->GetExtensionTag();
   436 	char buffer[2048];
   437 	va_list ap;
   438 
   439 	va_start(ap, format);
   440 	vsnprintf(buffer, sizeof(buffer), format, ap);
   441 	va_end(ap);
   442 
   443 	if (tag)
   444 	{
   445 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   446 	} else {
   447 		g_Logger.LogMessage("%s", buffer);
   448 	}
   449 }
   450 
   451 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   452 {
   453 	IExtensionInterface *pAPI = pExt->GetAPI();
   454 	const char *tag = pAPI->GetExtensionTag();
   455 	char buffer[2048];
   456 	va_list ap;
   457 
   458 	va_start(ap, format);
   459 	vsnprintf(buffer, sizeof(buffer), format, ap);
   460 	va_end(ap);
   461 
   462 	if (tag)
   463 	{
   464 		g_Logger.LogError("[%s] %s", tag, buffer);
   465 	} else {
   466 		g_Logger.LogError("%s", buffer);
   467 	}
   468 }
   469 
   470 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   471 {
   472 	char *fmt;
   473 
   474 	pContext->LocalToString(params[param], &fmt);
   475 
   476 	int lparam = ++param;
   477 
   478 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   479 }
   480 
   481 const char *SourceModBase::GetSourceModPath() const
   482 {
   483 	return m_SMBaseDir;
   484 }
   485 
   486 const char *SourceModBase::GetModPath() const
   487 {
   488 	return g_BaseDir.c_str();
   489 }
   490 
   491 void SourceModBase::SetGlobalTarget(unsigned int index)
   492 {
   493 	m_target = index;
   494 }
   495 
   496 void SourceModBase::SetAuthChecking(bool set)
   497 {
   498 	m_CheckingAuth = set;
   499 }
   500 
   501 unsigned int SourceModBase::GetGlobalTarget() const
   502 {
   503 	return m_target;
   504 }
   505 
   506 IDataPack *SourceModBase::CreateDataPack()
   507 {
   508 	CDataPack *pack;
   509 	if (m_freepacks.empty())
   510 	{
   511 		pack = new CDataPack;
   512 	} else {
   513 		pack = m_freepacks.front();
   514 		m_freepacks.pop();
   515 		pack->Initialize();
   516 	}
   517 	return pack;
   518 }
   519 
   520 void SourceModBase::FreeDataPack(IDataPack *pack)
   521 {
   522 	m_freepacks.push(static_cast<CDataPack *>(pack));
   523 }
   524 
   525 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   526 {
   527 	//:TODO:
   528 	return 0;
   529 }
   530 
   531 SMGlobalClass *SMGlobalClass::head = NULL;
   532 
   533 SMGlobalClass::SMGlobalClass()
   534 {
   535 	m_pGlobalClassNext = SMGlobalClass::head;
   536 	SMGlobalClass::head = this;
   537 }