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"
36 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
37 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
38 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
39 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
41 SourcePawnEngine g_SourcePawn;
42 SourceModBase g_SourceMod;
44 ILibrary *g_pJIT = NULL;
45 SourceHook::String g_BaseDir;
46 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
47 IVirtualMachine *g_pVM;
48 IdentityToken_t *g_pCoreIdent = NULL;
49 float g_LastTime = 0.0f;
50 float g_LastMenuTime = 0.0f;
51 float g_LastAuthCheck = 0.0f;
52 IForward *g_pOnGameFrame = NULL;
53 IForward *g_pOnMapEnd = NULL;
54 bool g_Loaded = false;
55 int g_StillFrames = 0;
56 float g_StillTime = 0.0f;
58 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
59 typedef int (*GIVEENGINEPOINTER2)(ISourcePawnEngine *, unsigned int api_version);
60 typedef unsigned int (*GETEXPORTCOUNT)();
61 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
62 typedef void (*NOTIFYSHUTDOWN)();
66 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
72 g_pJIT->CloseLibrary();
75 SourceModBase::SourceModBase()
77 m_IsMapLoading = false;
78 m_ExecPluginReload = false;
79 m_ExecOnMapEnd = false;
80 m_GotBasePath = false;
83 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
89 if (strcasecmp(key, "BasePath") == 0)
91 if (source == ConfigSource_Console)
93 UTIL_Format(error, maxlength, "Cannot be set at runtime");
94 return ConfigResult_Reject;
99 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
100 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
102 m_GotBasePath = true;
105 return ConfigResult_Accept;
108 return ConfigResult_Ignore;
111 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
113 const char *gamepath = g_SMAPI->GetBaseDir();
115 /* Store full path to game */
116 g_BaseDir.assign(gamepath);
118 /* Store name of game directory by itself */
119 size_t len = strlen(gamepath);
120 for (size_t i = len - 1; i >= 0; i--)
122 if (gamepath[i] == PLATFORM_SEP_CHAR)
124 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
129 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
130 g_CoreConfig.Initialize();
132 /* This shouldn't happen, but can't hurt to be safe */
133 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
135 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
136 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
137 m_GotBasePath = true;
140 /* Attempt to load the JIT! */
141 char file[PLATFORM_MAX_PATH];
143 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
148 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
151 if (error && maxlength)
153 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
162 GIVEENGINEPOINTER2 jit_init2 = (GIVEENGINEPOINTER2)g_pJIT->GetSymbolAddress("GiveEnginePointer2");
165 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
169 if (error && maxlength)
171 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
176 if ((err=jit_init(g_pSourcePawn)) != 0)
179 if (error && maxlength)
181 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
186 /* On version bumps, we should check for older versions as well, if the new version fails.
187 * We can then check the exports to see if any VM versions will be sufficient.
189 if ((err=jit_init2(g_pSourcePawn, SOURCEPAWN_ENGINE_API_VERSION)) != SP_ERROR_NONE)
192 if (error && maxlength)
194 snprintf(error, maxlength, "JIT incompatible with SourceMod version");
200 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
201 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
205 if (error && maxlength)
207 snprintf(error, maxlength, "JIT is missing a necessary export!");
212 unsigned int num = jit_getnum();
216 if (error && maxlength)
218 snprintf(error, maxlength, "JIT did not export any virtual machines!");
223 unsigned int api_version;
224 for (unsigned int i=0; i<num; i++)
226 if ((g_pVM=jit_get(i)) == NULL)
228 if (error && maxlength)
230 snprintf(error, maxlength, "JIT did not export any virtual machines!");
234 /* Refuse any API that we might not be able to deal with.
235 * Also refuse anything < 3 because we need fake natives.
237 api_version = g_pVM->GetAPIVersion();
238 if (api_version < 3 || api_version > SOURCEPAWN_VM_API_VERSION)
240 if (error && maxlength)
242 snprintf(error, maxlength, "JIT is not a compatible version");
256 /* Hook this now so we can detect startup without calling StartSourceMod() */
257 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
259 /* Only load if we're not late */
262 StartSourceMod(false);
268 void SourceModBase::StartSourceMod(bool late)
270 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
271 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
273 enginePatch = SH_GET_CALLCLASS(engine);
274 gamedllPatch = SH_GET_CALLCLASS(gamedll);
277 SMGlobalClass *pBase = SMGlobalClass::head;
280 pBase->OnSourceModStartup(false);
281 pBase = pBase->m_pGlobalClassNext;
284 /* Make the global core identity */
285 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
288 pBase = SMGlobalClass::head;
291 pBase->OnSourceModAllInitialized();
292 pBase = pBase->m_pGlobalClassNext;
296 g_ShareSys.AddInterface(NULL, this);
302 static bool g_LevelEndBarrier = false;
303 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
305 /* If we're not loaded... */
308 /* Do all global initialization now */
309 StartSourceMod(true);
312 m_IsMapLoading = true;
313 m_ExecPluginReload = true;
314 m_ExecOnMapEnd = true;
316 g_LastMenuTime = 0.0f;
317 g_LastAuthCheck = 0.0f;
318 g_SimTicks.ticking = true;
319 g_SimTicks.tickcount = 0;
324 SMGlobalClass *pBase = SMGlobalClass::head;
327 pBase->OnSourceModLevelChange(pMapName);
328 pBase = pBase->m_pGlobalClassNext;
331 DoGlobalPluginLoads();
333 m_IsMapLoading = false;
336 pBase = SMGlobalClass::head;
339 pBase->OnSourceModPluginsLoaded();
340 pBase = pBase->m_pGlobalClassNext;
345 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
350 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
353 g_LevelEndBarrier = true;
355 RETURN_META_VALUE(MRES_IGNORED, true);
358 void StartTickSimulation()
360 g_SimTicks.ticking = false;
361 g_SimTicks.tickcount = 0;
362 g_SimTicks.ticktime = gpGlobals->curtime;
365 void StopTickSimulation()
367 g_SimTicks.ticking = true;
368 g_Timers.MapChange(false);
370 g_LastTime = gpGlobals->curtime;
375 g_SimTicks.tickcount++;
376 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
379 void SourceModBase::GameFrame(bool simulating)
384 * Note: This is all hardcoded rather than delegated to save
385 * precious CPU cycles.
387 float curtime = gpGlobals->curtime;
388 int framecount = gpGlobals->framecount;
390 /* Verify that we're still ticking */
391 if (g_SimTicks.ticking)
393 if (g_StillFrames == 0)
395 g_StillFrames = framecount;
396 g_StillTime = curtime;
398 /* Try to detect when we've stopped ticking.
399 * We do this once 10 frames pass and there have been no ticks.
401 if (g_StillTime == curtime)
403 if (framecount - g_StillFrames >= 5)
405 StartTickSimulation();
409 /* We're definitely ticking we get here,
410 * but update everything as a precaution */
411 g_StillFrames = framecount;
412 g_StillTime = curtime;
416 /* We need to make sure we should still be simulating. */
417 if (g_StillTime != curtime)
419 /* Wow, we're ticking again! It's time to revert. */
420 StopTickSimulation();
423 /* Nope, not ticking. Simulate! */
425 curtime = g_SimTicks.ticktime;
428 if (curtime - g_LastTime >= 0.1f)
431 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
433 g_LastAuthCheck = gpGlobals->curtime;
434 g_Players.RunAuthChecks();
438 g_LastTime = curtime;
441 if (g_SimTicks.ticking && curtime - g_LastMenuTime >= 1.0f)
443 g_ValveMenuStyle.ProcessWatchList();
444 g_RadioMenuStyle.ProcessWatchList();
445 g_LastMenuTime = curtime;
448 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
450 g_pOnGameFrame->Execute(NULL);
454 void SourceModBase::LevelShutdown()
456 if (g_LevelEndBarrier)
458 SMGlobalClass *next = SMGlobalClass::head;
461 next->OnSourceModLevelEnd();
462 next = next->m_pGlobalClassNext;
464 g_LevelEndBarrier = false;
467 if (g_pOnMapEnd && m_ExecOnMapEnd)
469 g_pOnMapEnd->Execute(NULL);
470 m_ExecOnMapEnd = false;
473 g_OnMapStarted = false;
475 if (m_ExecPluginReload)
477 g_PluginSys.ReloadOrUnloadPlugins();
478 m_ExecPluginReload = false;
482 bool SourceModBase::IsMapLoading() const
484 return m_IsMapLoading;
487 void SourceModBase::DoGlobalPluginLoads()
489 char config_path[PLATFORM_MAX_PATH];
490 char plugins_path[PLATFORM_MAX_PATH];
492 BuildPath(Path_SM, config_path,
494 "configs/plugin_settings.cfg");
495 BuildPath(Path_SM, plugins_path,
496 sizeof(plugins_path),
499 /* Load any auto extensions */
500 g_Extensions.TryAutoload();
502 /* Run the first pass */
503 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
505 /* Mark any extensions as loaded */
506 g_Extensions.MarkAllLoaded();
508 /* No modules yet, it's safe to call this from here */
509 g_PluginSys.LoadAll_SecondPass();
511 /* Re-mark any extensions as loaded */
512 g_Extensions.MarkAllLoaded();
514 /* Call OnAllPluginsLoaded */
515 g_PluginSys.AllPluginsLoaded();
518 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
520 char _buffer[PLATFORM_MAX_PATH];
523 va_start(ap, format);
524 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
527 const char *base = NULL;
528 if (type == Path_Game)
530 base = GetGamePath();
531 } else if (type == Path_SM) {
532 base = GetSourceModPath();
533 } else if (type == Path_SM_Rel) {
539 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
541 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
545 void SourceModBase::CloseSourceMod()
547 /* Force a level end */
551 g_PluginSys.Shutdown();
553 /* Unload extensions */
554 g_Extensions.Shutdown();
556 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
562 g_Forwards.ReleaseForward(g_pOnGameFrame);
567 g_Forwards.ReleaseForward(g_pOnMapEnd);
571 SMGlobalClass *pBase = SMGlobalClass::head;
574 pBase->OnSourceModShutdown();
575 pBase = pBase->m_pGlobalClassNext;
578 /* Delete all data packs */
579 CStack<CDataPack *>::iterator iter;
581 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
586 m_freepacks.popall();
589 pBase = SMGlobalClass::head;
592 pBase->OnSourceModAllShutdown();
593 pBase = pBase->m_pGlobalClassNext;
598 SH_RELEASE_CALLCLASS(enginePatch);
604 SH_RELEASE_CALLCLASS(gamedllPatch);
608 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
609 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
616 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
618 IExtensionInterface *pAPI = pExt->GetAPI();
619 const char *tag = pAPI->GetExtensionTag();
623 va_start(ap, format);
624 vsnprintf(buffer, sizeof(buffer), format, ap);
629 g_Logger.LogMessage("[%s] %s", tag, buffer);
631 g_Logger.LogMessage("%s", buffer);
635 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
637 IExtensionInterface *pAPI = pExt->GetAPI();
638 const char *tag = pAPI->GetExtensionTag();
642 va_start(ap, format);
643 vsnprintf(buffer, sizeof(buffer), format, ap);
648 g_Logger.LogError("[%s] %s", tag, buffer);
650 g_Logger.LogError("%s", buffer);
654 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
658 pContext->LocalToString(params[param], &fmt);
660 int lparam = ++param;
662 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
665 const char *SourceModBase::GetSourceModPath() const
670 const char *SourceModBase::GetGamePath() const
672 return g_BaseDir.c_str();
675 void SourceModBase::SetGlobalTarget(unsigned int index)
680 void SourceModBase::SetAuthChecking(bool set)
682 m_CheckingAuth = set;
685 unsigned int SourceModBase::GetGlobalTarget() const
690 IDataPack *SourceModBase::CreateDataPack()
693 if (m_freepacks.empty())
695 pack = new CDataPack;
697 pack = m_freepacks.front();
704 void SourceModBase::FreeDataPack(IDataPack *pack)
706 m_freepacks.push(static_cast<CDataPack *>(pack));
709 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
715 const char *SourceModBase::GetGameFolderName() const
720 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
722 return g_pSourcePawn;
725 IVirtualMachine *SourceModBase::GetScriptingVM()
730 void SourceModBase::AllPluginsLoaded()
732 SMGlobalClass *base = SMGlobalClass::head;
735 base->OnSourceModGameInitialized();
736 base = base->m_pGlobalClassNext;
740 SMGlobalClass *SMGlobalClass::head = NULL;
742 SMGlobalClass::SMGlobalClass()
744 m_pGlobalClassNext = SMGlobalClass::head;
745 SMGlobalClass::head = this;