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;
49 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
50 typedef unsigned int (*GETEXPORTCOUNT)();
51 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
52 typedef void (*NOTIFYSHUTDOWN)();
56 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
62 g_pJIT->CloseLibrary();
65 SourceModBase::SourceModBase()
67 m_IsMapLoading = false;
68 m_ExecPluginReload = false;
69 m_GotBasePath = false;
72 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
78 if (strcasecmp(key, "BasePath") == 0)
80 if (source == ConfigSource_Console)
82 UTIL_Format(error, maxlength, "Cannot be set at runtime");
83 return ConfigResult_Reject;
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);
94 return ConfigResult_Accept;
97 return ConfigResult_Ignore;
100 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
102 g_BaseDir.assign(g_SMAPI->GetBaseDir());
104 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
105 g_CoreConfig.Initialize();
107 /* This shouldn't happen, but can't hurt to be safe */
108 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
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;
115 /* Attempt to load the JIT! */
116 char file[PLATFORM_MAX_PATH];
118 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
123 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
126 if (error && err_max)
128 snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
136 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
140 if (error && err_max)
142 snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
147 if ((err=jit_init(g_pSourcePawn)) != 0)
150 if (error && err_max)
152 snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
157 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
158 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
162 if (error && err_max)
164 snprintf(error, err_max, "JIT is missing a necessary export!");
169 unsigned int num = jit_getnum();
170 if (!num || ((g_pVM=jit_get(0)) == NULL))
173 if (error && err_max)
175 snprintf(error, err_max, "JIT did not export any virtual machines!");
180 unsigned int api = g_pVM->GetAPIVersion();
181 if (api != SOURCEPAWN_VM_API_VERSION)
184 if (error && err_max)
186 snprintf(error, err_max, "JIT is not a compatible version");
191 StartSourceMod(late);
196 void SourceModBase::StartSourceMod(bool late)
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);
203 enginePatch = SH_GET_CALLCLASS(engine);
204 gamedllPatch = SH_GET_CALLCLASS(gamedll);
207 SMGlobalClass *pBase = SMGlobalClass::head;
210 pBase->OnSourceModStartup(false);
211 pBase = pBase->m_pGlobalClassNext;
214 /* Make the global core identity */
215 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
218 pBase = SMGlobalClass::head;
221 pBase->OnSourceModAllInitialized();
222 pBase = pBase->m_pGlobalClassNext;
226 g_ShareSys.AddInterface(NULL, this);
229 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
231 m_IsMapLoading = true;
232 m_ExecPluginReload = true;
234 g_LastAuthCheck = 0.0f;
236 g_Logger.MapChange(pMapName);
237 g_Timers.MapChange();
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);
244 DoGlobalPluginLoads();
246 m_IsMapLoading = false;
248 g_Admins.DumpAdminCache(AdminCache_Overrides, true);
249 g_Admins.DumpAdminCache(AdminCache_Groups, true);
253 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
256 RETURN_META_VALUE(MRES_IGNORED, true);
259 void SourceModBase::GameFrame(bool simulating)
262 * Note: This is all hardcoded rather than delegated to save
263 * precious CPU cycles.
265 float curtime = gpGlobals->curtime;
266 if (curtime - g_LastTime >= 0.1f)
269 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
271 g_LastAuthCheck = gpGlobals->curtime;
272 g_Players.RunAuthChecks();
276 g_LastTime = curtime;
279 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
281 g_pOnGameFrame->Execute(NULL);
285 void SourceModBase::LevelShutdown()
287 if (m_ExecPluginReload)
289 g_PluginSys.ReloadOrUnloadPlugins();
290 m_ExecPluginReload = false;
294 bool SourceModBase::IsMapLoading() const
296 return m_IsMapLoading;
299 void SourceModBase::DoGlobalPluginLoads()
301 char config_path[PLATFORM_MAX_PATH];
302 char plugins_path[PLATFORM_MAX_PATH];
304 BuildPath(Path_SM, config_path,
306 "configs/plugin_settings.cfg");
307 BuildPath(Path_SM, plugins_path,
308 sizeof(plugins_path),
311 /* Load any auto extensions */
312 g_Extensions.TryAutoload();
314 /* Run the first pass */
315 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
317 /* Mark any extensions as loaded */
318 g_Extensions.MarkAllLoaded();
320 /* No modules yet, it's safe to call this from here */
321 g_PluginSys.LoadAll_SecondPass();
323 /* Re-mark any extensions as loaded */
324 g_Extensions.MarkAllLoaded();
327 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
329 char _buffer[PLATFORM_MAX_PATH];
332 va_start(ap, format);
333 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
336 const char *base = NULL;
337 if (type == Path_Game)
340 } else if (type == Path_SM) {
341 base = GetSourceModPath();
342 } else if (type == Path_SM_Rel) {
348 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
350 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
354 void SourceModBase::CloseSourceMod()
358 g_Forwards.ReleaseForward(g_pOnGameFrame);
362 SMGlobalClass *pBase = SMGlobalClass::head;
365 pBase->OnSourceModShutdown();
366 pBase = pBase->m_pGlobalClassNext;
369 /* Delete all data packs */
370 CStack<CDataPack *>::iterator iter;
372 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
377 m_freepacks.popall();
380 pBase = SMGlobalClass::head;
383 pBase->OnSourceModAllShutdown();
384 pBase = pBase->m_pGlobalClassNext;
389 SH_RELEASE_CALLCLASS(enginePatch);
395 SH_RELEASE_CALLCLASS(gamedllPatch);
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);
407 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
409 IExtensionInterface *pAPI = pExt->GetAPI();
410 const char *tag = pAPI->GetExtensionTag();
414 va_start(ap, format);
415 vsnprintf(buffer, sizeof(buffer), format, ap);
420 g_Logger.LogMessage("[%s] %s", tag, buffer);
422 g_Logger.LogMessage("%s", buffer);
426 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
428 IExtensionInterface *pAPI = pExt->GetAPI();
429 const char *tag = pAPI->GetExtensionTag();
433 va_start(ap, format);
434 vsnprintf(buffer, sizeof(buffer), format, ap);
439 g_Logger.LogError("[%s] %s", tag, buffer);
441 g_Logger.LogError("%s", buffer);
445 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
449 pContext->LocalToString(params[param], &fmt);
451 int lparam = ++param;
453 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
456 const char *SourceModBase::GetSourceModPath() const
461 const char *SourceModBase::GetModPath() const
463 return g_BaseDir.c_str();
466 void SourceModBase::SetGlobalTarget(unsigned int index)
471 void SourceModBase::SetAuthChecking(bool set)
473 m_CheckingAuth = set;
476 unsigned int SourceModBase::GetGlobalTarget() const
481 IDataPack *SourceModBase::CreateDataPack()
484 if (m_freepacks.empty())
486 pack = new CDataPack;
488 pack = m_freepacks.front();
495 void SourceModBase::FreeDataPack(IDataPack *pack)
497 m_freepacks.push(static_cast<CDataPack *>(pack));
500 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
506 SMGlobalClass *SMGlobalClass::head = NULL;
508 SMGlobalClass::SMGlobalClass()
510 m_pGlobalClassNext = SMGlobalClass::head;
511 SMGlobalClass::head = this;