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"
32 #include "MenuStyle_Valve.h"
33 #include "MenuStyle_Radio.h"
35 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
36 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
37 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
39 SourcePawnEngine g_SourcePawn;
40 SourceModBase g_SourceMod;
42 ILibrary *g_pJIT = NULL;
43 SourceHook::String g_BaseDir;
44 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
45 IVirtualMachine *g_pVM;
46 IdentityToken_t *g_pCoreIdent = NULL;
47 float g_LastTime = 0.0f;
48 float g_LastMenuTime = 0.0f;
49 float g_LastAuthCheck = 0.0f;
50 IForward *g_pOnGameFrame = NULL;
51 IForward *g_pOnMapEnd = NULL;
52 bool g_Loaded = false;
53 int g_StillFrames = 0;
54 float g_StillTime = 0.0f;
56 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
57 typedef unsigned int (*GETEXPORTCOUNT)();
58 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
59 typedef void (*NOTIFYSHUTDOWN)();
63 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
69 g_pJIT->CloseLibrary();
72 SourceModBase::SourceModBase()
74 m_IsMapLoading = false;
75 m_ExecPluginReload = false;
76 m_ExecOnMapEnd = false;
77 m_GotBasePath = false;
80 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
86 if (strcasecmp(key, "BasePath") == 0)
88 if (source == ConfigSource_Console)
90 UTIL_Format(error, maxlength, "Cannot be set at runtime");
91 return ConfigResult_Reject;
96 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
97 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
102 return ConfigResult_Accept;
105 return ConfigResult_Ignore;
108 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
110 const char *gamepath = g_SMAPI->GetBaseDir();
112 /* Store full path to game */
113 g_BaseDir.assign(gamepath);
115 /* Store name of game directory by itself */
116 size_t len = strlen(gamepath);
117 for (size_t i = len - 1; i >= 0; i--)
119 if (gamepath[i] == PLATFORM_SEP_CHAR)
121 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
126 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
127 g_CoreConfig.Initialize();
129 /* This shouldn't happen, but can't hurt to be safe */
130 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
132 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
133 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
134 m_GotBasePath = true;
137 /* Attempt to load the JIT! */
138 char file[PLATFORM_MAX_PATH];
140 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
145 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
148 if (error && maxlength)
150 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
158 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
162 if (error && maxlength)
164 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
169 if ((err=jit_init(g_pSourcePawn)) != 0)
172 if (error && maxlength)
174 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
179 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
180 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
184 if (error && maxlength)
186 snprintf(error, maxlength, "JIT is missing a necessary export!");
191 unsigned int num = jit_getnum();
192 if (!num || ((g_pVM=jit_get(0)) == NULL))
195 if (error && maxlength)
197 snprintf(error, maxlength, "JIT did not export any virtual machines!");
202 unsigned int api = g_pVM->GetAPIVersion();
203 if (api != SOURCEPAWN_VM_API_VERSION)
206 if (error && maxlength)
208 snprintf(error, maxlength, "JIT is not a compatible version");
213 /* Hook this now so we can detect startup without calling StartSourceMod() */
214 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
216 /* Only load if we're not late */
219 StartSourceMod(false);
225 void SourceModBase::StartSourceMod(bool late)
227 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
228 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
230 enginePatch = SH_GET_CALLCLASS(engine);
231 gamedllPatch = SH_GET_CALLCLASS(gamedll);
234 SMGlobalClass *pBase = SMGlobalClass::head;
237 pBase->OnSourceModStartup(false);
238 pBase = pBase->m_pGlobalClassNext;
241 /* Make the global core identity */
242 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
245 pBase = SMGlobalClass::head;
248 pBase->OnSourceModAllInitialized();
249 pBase = pBase->m_pGlobalClassNext;
253 g_ShareSys.AddInterface(NULL, this);
259 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
261 /* If we're not loaded... */
264 /* Do all global initialization now */
265 StartSourceMod(true);
268 m_IsMapLoading = true;
269 m_ExecPluginReload = true;
270 m_ExecOnMapEnd = true;
272 g_LastMenuTime = 0.0f;
273 g_LastAuthCheck = 0.0f;
274 g_SimTicks.ticking = true;
275 g_SimTicks.tickcount = 0;
280 SMGlobalClass *pBase = SMGlobalClass::head;
283 pBase->OnSourceModLevelChange(pMapName);
284 pBase = pBase->m_pGlobalClassNext;
287 DoGlobalPluginLoads();
289 m_IsMapLoading = false;
292 pBase = SMGlobalClass::head;
295 pBase->OnSourceModPluginsLoaded();
296 pBase = pBase->m_pGlobalClassNext;
301 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
306 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
309 RETURN_META_VALUE(MRES_IGNORED, true);
312 void StartTickSimulation()
314 g_SimTicks.ticking = false;
315 g_SimTicks.tickcount = 0;
316 g_SimTicks.ticktime = gpGlobals->curtime;
319 void StopTickSimulation()
321 g_SimTicks.ticking = true;
322 g_Timers.MapChange();
324 g_LastTime = gpGlobals->curtime;
329 g_SimTicks.tickcount++;
330 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
333 void SourceModBase::GameFrame(bool simulating)
336 * Note: This is all hardcoded rather than delegated to save
337 * precious CPU cycles.
339 float curtime = gpGlobals->curtime;
340 int framecount = gpGlobals->framecount;
342 /* Verify that we're still ticking */
343 if (g_SimTicks.ticking)
345 if (g_StillFrames == 0)
347 g_StillFrames = framecount;
348 g_StillTime = curtime;
350 /* Try to detect when we've stopped ticking.
351 * We do this once 10 frames pass and there have been no ticks.
353 if (g_StillTime == curtime)
355 if (framecount - g_StillFrames >= 5)
357 StartTickSimulation();
361 /* We're definitely ticking we get here,
362 * but update everything as a precaution */
363 g_StillFrames = framecount;
364 g_StillTime = curtime;
368 /* We need to make sure we should still be simulating. */
369 if (g_StillTime != curtime)
371 /* Wow, we're ticking again! It's time to revert. */
372 StopTickSimulation();
375 /* Nope, not ticking. Simulate! */
377 curtime = g_SimTicks.ticktime;
380 if (curtime - g_LastTime >= 0.1f)
383 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
385 g_LastAuthCheck = gpGlobals->curtime;
386 g_Players.RunAuthChecks();
390 g_LastTime = curtime;
393 if (g_SimTicks.tickcount && (curtime - g_LastMenuTime >= 1.0f))
395 g_ValveMenuStyle.ProcessWatchList();
396 g_RadioMenuStyle.ProcessWatchList();
397 g_LastMenuTime = curtime;
400 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
402 g_pOnGameFrame->Execute(NULL);
406 void SourceModBase::LevelShutdown()
408 if (g_pOnMapEnd && m_ExecOnMapEnd)
410 g_pOnMapEnd->Execute(NULL);
411 m_ExecOnMapEnd = false;
414 g_OnMapStarted = false;
416 if (m_ExecPluginReload)
418 g_PluginSys.ReloadOrUnloadPlugins();
419 m_ExecPluginReload = false;
423 bool SourceModBase::IsMapLoading() const
425 return m_IsMapLoading;
428 void SourceModBase::DoGlobalPluginLoads()
430 char config_path[PLATFORM_MAX_PATH];
431 char plugins_path[PLATFORM_MAX_PATH];
433 BuildPath(Path_SM, config_path,
435 "configs/plugin_settings.cfg");
436 BuildPath(Path_SM, plugins_path,
437 sizeof(plugins_path),
440 /* Load any auto extensions */
441 g_Extensions.TryAutoload();
443 /* Run the first pass */
444 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
446 /* Mark any extensions as loaded */
447 g_Extensions.MarkAllLoaded();
449 /* No modules yet, it's safe to call this from here */
450 g_PluginSys.LoadAll_SecondPass();
452 /* Re-mark any extensions as loaded */
453 g_Extensions.MarkAllLoaded();
456 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
458 char _buffer[PLATFORM_MAX_PATH];
461 va_start(ap, format);
462 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
465 const char *base = NULL;
466 if (type == Path_Game)
468 base = GetGamePath();
469 } else if (type == Path_SM) {
470 base = GetSourceModPath();
471 } else if (type == Path_SM_Rel) {
477 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
479 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
483 void SourceModBase::CloseSourceMod()
485 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
491 g_Forwards.ReleaseForward(g_pOnGameFrame);
496 g_Forwards.ReleaseForward(g_pOnMapEnd);
500 SMGlobalClass *pBase = SMGlobalClass::head;
503 pBase->OnSourceModShutdown();
504 pBase = pBase->m_pGlobalClassNext;
507 /* Delete all data packs */
508 CStack<CDataPack *>::iterator iter;
510 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
515 m_freepacks.popall();
518 pBase = SMGlobalClass::head;
521 pBase->OnSourceModAllShutdown();
522 pBase = pBase->m_pGlobalClassNext;
527 SH_RELEASE_CALLCLASS(enginePatch);
533 SH_RELEASE_CALLCLASS(gamedllPatch);
537 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
538 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
545 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
547 IExtensionInterface *pAPI = pExt->GetAPI();
548 const char *tag = pAPI->GetExtensionTag();
552 va_start(ap, format);
553 vsnprintf(buffer, sizeof(buffer), format, ap);
558 g_Logger.LogMessage("[%s] %s", tag, buffer);
560 g_Logger.LogMessage("%s", buffer);
564 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
566 IExtensionInterface *pAPI = pExt->GetAPI();
567 const char *tag = pAPI->GetExtensionTag();
571 va_start(ap, format);
572 vsnprintf(buffer, sizeof(buffer), format, ap);
577 g_Logger.LogError("[%s] %s", tag, buffer);
579 g_Logger.LogError("%s", buffer);
583 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
587 pContext->LocalToString(params[param], &fmt);
589 int lparam = ++param;
591 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
594 const char *SourceModBase::GetSourceModPath() const
599 const char *SourceModBase::GetGamePath() const
601 return g_BaseDir.c_str();
604 void SourceModBase::SetGlobalTarget(unsigned int index)
609 void SourceModBase::SetAuthChecking(bool set)
611 m_CheckingAuth = set;
614 unsigned int SourceModBase::GetGlobalTarget() const
619 IDataPack *SourceModBase::CreateDataPack()
622 if (m_freepacks.empty())
624 pack = new CDataPack;
626 pack = m_freepacks.front();
633 void SourceModBase::FreeDataPack(IDataPack *pack)
635 m_freepacks.push(static_cast<CDataPack *>(pack));
638 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
644 const char *SourceModBase::GetGameFolderName() const
649 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
651 return g_pSourcePawn;
654 IVirtualMachine *SourceModBase::GetScriptingVM()
659 void SourceModBase::AllPluginsLoaded()
661 SMGlobalClass *base = SMGlobalClass::head;
664 base->OnSourceModGameInitialized();
665 base = base->m_pGlobalClassNext;
669 SMGlobalClass *SMGlobalClass::head = NULL;
671 SMGlobalClass::SMGlobalClass()
673 m_pGlobalClassNext = SMGlobalClass::head;
674 SMGlobalClass::head = this;