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 bool g_Loaded = false;
50 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
51 typedef unsigned int (*GETEXPORTCOUNT)();
52 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
53 typedef void (*NOTIFYSHUTDOWN)();
57 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
63 g_pJIT->CloseLibrary();
66 SourceModBase::SourceModBase()
68 m_IsMapLoading = false;
69 m_ExecPluginReload = false;
70 m_GotBasePath = false;
73 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
79 if (strcasecmp(key, "BasePath") == 0)
81 if (source == ConfigSource_Console)
83 UTIL_Format(error, maxlength, "Cannot be set at runtime");
84 return ConfigResult_Reject;
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);
95 return ConfigResult_Accept;
98 return ConfigResult_Ignore;
101 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
103 g_BaseDir.assign(g_SMAPI->GetBaseDir());
105 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
106 g_CoreConfig.Initialize();
108 /* This shouldn't happen, but can't hurt to be safe */
109 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
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;
116 /* Attempt to load the JIT! */
117 char file[PLATFORM_MAX_PATH];
119 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
124 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
127 if (error && err_max)
129 snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
137 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
141 if (error && err_max)
143 snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
148 if ((err=jit_init(g_pSourcePawn)) != 0)
151 if (error && err_max)
153 snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
158 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
159 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
163 if (error && err_max)
165 snprintf(error, err_max, "JIT is missing a necessary export!");
170 unsigned int num = jit_getnum();
171 if (!num || ((g_pVM=jit_get(0)) == NULL))
174 if (error && err_max)
176 snprintf(error, err_max, "JIT did not export any virtual machines!");
181 unsigned int api = g_pVM->GetAPIVersion();
182 if (api != SOURCEPAWN_VM_API_VERSION)
185 if (error && err_max)
187 snprintf(error, err_max, "JIT is not a compatible version");
192 /* Hook this now so we can detect startup without calling StartSourceMod() */
193 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
195 /* Only load if we're not late */
198 StartSourceMod(false);
204 void SourceModBase::StartSourceMod(bool late)
206 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
207 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
209 enginePatch = SH_GET_CALLCLASS(engine);
210 gamedllPatch = SH_GET_CALLCLASS(gamedll);
213 SMGlobalClass *pBase = SMGlobalClass::head;
216 pBase->OnSourceModStartup(false);
217 pBase = pBase->m_pGlobalClassNext;
220 /* Make the global core identity */
221 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
224 pBase = SMGlobalClass::head;
227 pBase->OnSourceModAllInitialized();
228 pBase = pBase->m_pGlobalClassNext;
232 g_ShareSys.AddInterface(NULL, this);
238 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
240 /* If we're not loaded... */
243 /* Do all global initialization now */
244 StartSourceMod(true);
247 m_IsMapLoading = true;
248 m_ExecPluginReload = true;
250 g_LastAuthCheck = 0.0f;
253 SMGlobalClass *pBase = SMGlobalClass::head;
256 pBase->OnSourceModLevelChange(pMapName);
257 pBase = pBase->m_pGlobalClassNext;
260 DoGlobalPluginLoads();
262 m_IsMapLoading = false;
265 pBase = SMGlobalClass::head;
268 pBase->OnSourceModPluginsLoaded();
269 pBase = pBase->m_pGlobalClassNext;
274 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
277 RETURN_META_VALUE(MRES_IGNORED, true);
280 void SourceModBase::GameFrame(bool simulating)
283 * Note: This is all hardcoded rather than delegated to save
284 * precious CPU cycles.
286 float curtime = gpGlobals->curtime;
287 if (curtime - g_LastTime >= 0.1f)
290 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
292 g_LastAuthCheck = gpGlobals->curtime;
293 g_Players.RunAuthChecks();
297 g_LastTime = curtime;
300 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
302 g_pOnGameFrame->Execute(NULL);
306 void SourceModBase::LevelShutdown()
308 if (m_ExecPluginReload)
310 g_PluginSys.ReloadOrUnloadPlugins();
311 m_ExecPluginReload = false;
315 bool SourceModBase::IsMapLoading() const
317 return m_IsMapLoading;
320 void SourceModBase::DoGlobalPluginLoads()
322 char config_path[PLATFORM_MAX_PATH];
323 char plugins_path[PLATFORM_MAX_PATH];
325 BuildPath(Path_SM, config_path,
327 "configs/plugin_settings.cfg");
328 BuildPath(Path_SM, plugins_path,
329 sizeof(plugins_path),
332 /* Load any auto extensions */
333 g_Extensions.TryAutoload();
335 /* Run the first pass */
336 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
338 /* Mark any extensions as loaded */
339 g_Extensions.MarkAllLoaded();
341 /* No modules yet, it's safe to call this from here */
342 g_PluginSys.LoadAll_SecondPass();
344 /* Re-mark any extensions as loaded */
345 g_Extensions.MarkAllLoaded();
348 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
350 char _buffer[PLATFORM_MAX_PATH];
353 va_start(ap, format);
354 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
357 const char *base = NULL;
358 if (type == Path_Game)
361 } else if (type == Path_SM) {
362 base = GetSourceModPath();
363 } else if (type == Path_SM_Rel) {
369 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
371 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
375 void SourceModBase::CloseSourceMod()
377 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
383 g_Forwards.ReleaseForward(g_pOnGameFrame);
387 SMGlobalClass *pBase = SMGlobalClass::head;
390 pBase->OnSourceModShutdown();
391 pBase = pBase->m_pGlobalClassNext;
394 /* Delete all data packs */
395 CStack<CDataPack *>::iterator iter;
397 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
402 m_freepacks.popall();
405 pBase = SMGlobalClass::head;
408 pBase->OnSourceModAllShutdown();
409 pBase = pBase->m_pGlobalClassNext;
414 SH_RELEASE_CALLCLASS(enginePatch);
420 SH_RELEASE_CALLCLASS(gamedllPatch);
424 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
425 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
432 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
434 IExtensionInterface *pAPI = pExt->GetAPI();
435 const char *tag = pAPI->GetExtensionTag();
439 va_start(ap, format);
440 vsnprintf(buffer, sizeof(buffer), format, ap);
445 g_Logger.LogMessage("[%s] %s", tag, buffer);
447 g_Logger.LogMessage("%s", buffer);
451 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
453 IExtensionInterface *pAPI = pExt->GetAPI();
454 const char *tag = pAPI->GetExtensionTag();
458 va_start(ap, format);
459 vsnprintf(buffer, sizeof(buffer), format, ap);
464 g_Logger.LogError("[%s] %s", tag, buffer);
466 g_Logger.LogError("%s", buffer);
470 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
474 pContext->LocalToString(params[param], &fmt);
476 int lparam = ++param;
478 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
481 const char *SourceModBase::GetSourceModPath() const
486 const char *SourceModBase::GetModPath() const
488 return g_BaseDir.c_str();
491 void SourceModBase::SetGlobalTarget(unsigned int index)
496 void SourceModBase::SetAuthChecking(bool set)
498 m_CheckingAuth = set;
501 unsigned int SourceModBase::GetGlobalTarget() const
506 IDataPack *SourceModBase::CreateDataPack()
509 if (m_freepacks.empty())
511 pack = new CDataPack;
513 pack = m_freepacks.front();
520 void SourceModBase::FreeDataPack(IDataPack *pack)
522 m_freepacks.push(static_cast<CDataPack *>(pack));
525 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
531 SMGlobalClass *SMGlobalClass::head = NULL;
533 SMGlobalClass::SMGlobalClass()
535 m_pGlobalClassNext = SMGlobalClass::head;
536 SMGlobalClass::head = this;