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