3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
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
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"
23 #include "CoreConfig.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"
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);
37 SourcePawnEngine g_SourcePawn;
38 SourceModBase g_SourceMod;
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 IForward *g_pOnMapEnd = NULL;
49 bool g_Loaded = false;
51 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
52 typedef unsigned int (*GETEXPORTCOUNT)();
53 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
54 typedef void (*NOTIFYSHUTDOWN)();
58 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
64 g_pJIT->CloseLibrary();
67 SourceModBase::SourceModBase()
69 m_IsMapLoading = false;
70 m_ExecPluginReload = false;
71 m_GotBasePath = false;
74 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
80 if (strcasecmp(key, "BasePath") == 0)
82 if (source == ConfigSource_Console)
84 UTIL_Format(error, maxlength, "Cannot be set at runtime");
85 return ConfigResult_Reject;
90 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
91 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
96 return ConfigResult_Accept;
99 return ConfigResult_Ignore;
102 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
104 const char *gamepath = g_SMAPI->GetBaseDir();
106 /* Store full path to game */
107 g_BaseDir.assign(gamepath);
109 /* Store name of game directory by itself */
110 size_t len = strlen(gamepath);
111 for (size_t i = len - 1; i >= 0; i--)
113 if (gamepath[i] == PLATFORM_SEP_CHAR)
115 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
120 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
121 g_CoreConfig.Initialize();
123 /* This shouldn't happen, but can't hurt to be safe */
124 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
126 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
127 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
128 m_GotBasePath = true;
131 /* Attempt to load the JIT! */
132 char file[PLATFORM_MAX_PATH];
134 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
139 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
142 if (error && err_max)
144 snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
152 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
156 if (error && err_max)
158 snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
163 if ((err=jit_init(g_pSourcePawn)) != 0)
166 if (error && err_max)
168 snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
173 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
174 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
178 if (error && err_max)
180 snprintf(error, err_max, "JIT is missing a necessary export!");
185 unsigned int num = jit_getnum();
186 if (!num || ((g_pVM=jit_get(0)) == NULL))
189 if (error && err_max)
191 snprintf(error, err_max, "JIT did not export any virtual machines!");
196 unsigned int api = g_pVM->GetAPIVersion();
197 if (api != SOURCEPAWN_VM_API_VERSION)
200 if (error && err_max)
202 snprintf(error, err_max, "JIT is not a compatible version");
207 /* Hook this now so we can detect startup without calling StartSourceMod() */
208 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
210 /* Only load if we're not late */
213 StartSourceMod(false);
219 void SourceModBase::StartSourceMod(bool late)
221 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
222 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
224 enginePatch = SH_GET_CALLCLASS(engine);
225 gamedllPatch = SH_GET_CALLCLASS(gamedll);
228 SMGlobalClass *pBase = SMGlobalClass::head;
231 pBase->OnSourceModStartup(false);
232 pBase = pBase->m_pGlobalClassNext;
235 /* Make the global core identity */
236 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
239 pBase = SMGlobalClass::head;
242 pBase->OnSourceModAllInitialized();
243 pBase = pBase->m_pGlobalClassNext;
247 g_ShareSys.AddInterface(NULL, this);
253 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
255 /* If we're not loaded... */
258 /* Do all global initialization now */
259 StartSourceMod(true);
262 m_IsMapLoading = true;
263 m_ExecPluginReload = true;
265 g_LastAuthCheck = 0.0f;
268 SMGlobalClass *pBase = SMGlobalClass::head;
271 pBase->OnSourceModLevelChange(pMapName);
272 pBase = pBase->m_pGlobalClassNext;
275 DoGlobalPluginLoads();
277 m_IsMapLoading = false;
280 pBase = SMGlobalClass::head;
283 pBase->OnSourceModPluginsLoaded();
284 pBase = pBase->m_pGlobalClassNext;
289 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
294 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
297 RETURN_META_VALUE(MRES_IGNORED, true);
300 void SourceModBase::GameFrame(bool simulating)
303 * Note: This is all hardcoded rather than delegated to save
304 * precious CPU cycles.
306 float curtime = gpGlobals->curtime;
307 if (curtime - g_LastTime >= 0.1f)
310 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
312 g_LastAuthCheck = gpGlobals->curtime;
313 g_Players.RunAuthChecks();
317 g_LastTime = curtime;
320 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
322 g_pOnGameFrame->Execute(NULL);
326 void SourceModBase::LevelShutdown()
330 g_pOnMapEnd->Execute(NULL);
333 if (m_ExecPluginReload)
335 g_PluginSys.ReloadOrUnloadPlugins();
336 m_ExecPluginReload = false;
340 bool SourceModBase::IsMapLoading() const
342 return m_IsMapLoading;
345 void SourceModBase::DoGlobalPluginLoads()
347 char config_path[PLATFORM_MAX_PATH];
348 char plugins_path[PLATFORM_MAX_PATH];
350 BuildPath(Path_SM, config_path,
352 "configs/plugin_settings.cfg");
353 BuildPath(Path_SM, plugins_path,
354 sizeof(plugins_path),
357 /* Load any auto extensions */
358 g_Extensions.TryAutoload();
360 /* Run the first pass */
361 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
363 /* Mark any extensions as loaded */
364 g_Extensions.MarkAllLoaded();
366 /* No modules yet, it's safe to call this from here */
367 g_PluginSys.LoadAll_SecondPass();
369 /* Re-mark any extensions as loaded */
370 g_Extensions.MarkAllLoaded();
373 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
375 char _buffer[PLATFORM_MAX_PATH];
378 va_start(ap, format);
379 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
382 const char *base = NULL;
383 if (type == Path_Game)
386 } else if (type == Path_SM) {
387 base = GetSourceModPath();
388 } else if (type == Path_SM_Rel) {
394 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
396 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
400 void SourceModBase::CloseSourceMod()
402 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
408 g_Forwards.ReleaseForward(g_pOnGameFrame);
413 g_Forwards.ReleaseForward(g_pOnMapEnd);
417 SMGlobalClass *pBase = SMGlobalClass::head;
420 pBase->OnSourceModShutdown();
421 pBase = pBase->m_pGlobalClassNext;
424 /* Delete all data packs */
425 CStack<CDataPack *>::iterator iter;
427 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
432 m_freepacks.popall();
435 pBase = SMGlobalClass::head;
438 pBase->OnSourceModAllShutdown();
439 pBase = pBase->m_pGlobalClassNext;
444 SH_RELEASE_CALLCLASS(enginePatch);
450 SH_RELEASE_CALLCLASS(gamedllPatch);
454 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
455 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
462 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
464 IExtensionInterface *pAPI = pExt->GetAPI();
465 const char *tag = pAPI->GetExtensionTag();
469 va_start(ap, format);
470 vsnprintf(buffer, sizeof(buffer), format, ap);
475 g_Logger.LogMessage("[%s] %s", tag, buffer);
477 g_Logger.LogMessage("%s", buffer);
481 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
483 IExtensionInterface *pAPI = pExt->GetAPI();
484 const char *tag = pAPI->GetExtensionTag();
488 va_start(ap, format);
489 vsnprintf(buffer, sizeof(buffer), format, ap);
494 g_Logger.LogError("[%s] %s", tag, buffer);
496 g_Logger.LogError("%s", buffer);
500 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
504 pContext->LocalToString(params[param], &fmt);
506 int lparam = ++param;
508 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
511 const char *SourceModBase::GetSourceModPath() const
516 const char *SourceModBase::GetModPath() const
518 return g_BaseDir.c_str();
521 void SourceModBase::SetGlobalTarget(unsigned int index)
526 void SourceModBase::SetAuthChecking(bool set)
528 m_CheckingAuth = set;
531 unsigned int SourceModBase::GetGlobalTarget() const
536 IDataPack *SourceModBase::CreateDataPack()
539 if (m_freepacks.empty())
541 pack = new CDataPack;
543 pack = m_freepacks.front();
550 void SourceModBase::FreeDataPack(IDataPack *pack)
552 m_freepacks.push(static_cast<CDataPack *>(pack));
555 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
561 const char *SourceModBase::GetModFolderName() const
566 SMGlobalClass *SMGlobalClass::head = NULL;
568 SMGlobalClass::SMGlobalClass()
570 m_pGlobalClassNext = SMGlobalClass::head;
571 SMGlobalClass::head = this;