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_GotBasePath = false;
79 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
85 if (strcasecmp(key, "BasePath") == 0)
87 if (source == ConfigSource_Console)
89 UTIL_Format(error, maxlength, "Cannot be set at runtime");
90 return ConfigResult_Reject;
95 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
96 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
101 return ConfigResult_Accept;
104 return ConfigResult_Ignore;
107 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
109 const char *gamepath = g_SMAPI->GetBaseDir();
111 /* Store full path to game */
112 g_BaseDir.assign(gamepath);
114 /* Store name of game directory by itself */
115 size_t len = strlen(gamepath);
116 for (size_t i = len - 1; i >= 0; i--)
118 if (gamepath[i] == PLATFORM_SEP_CHAR)
120 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
125 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
126 g_CoreConfig.Initialize();
128 /* This shouldn't happen, but can't hurt to be safe */
129 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
131 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
132 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
133 m_GotBasePath = true;
136 /* Attempt to load the JIT! */
137 char file[PLATFORM_MAX_PATH];
139 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
144 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
147 if (error && maxlength)
149 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
157 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
161 if (error && maxlength)
163 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
168 if ((err=jit_init(g_pSourcePawn)) != 0)
171 if (error && maxlength)
173 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
178 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
179 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
183 if (error && maxlength)
185 snprintf(error, maxlength, "JIT is missing a necessary export!");
190 unsigned int num = jit_getnum();
191 if (!num || ((g_pVM=jit_get(0)) == NULL))
194 if (error && maxlength)
196 snprintf(error, maxlength, "JIT did not export any virtual machines!");
201 unsigned int api = g_pVM->GetAPIVersion();
202 if (api != SOURCEPAWN_VM_API_VERSION)
205 if (error && maxlength)
207 snprintf(error, maxlength, "JIT is not a compatible version");
212 /* Hook this now so we can detect startup without calling StartSourceMod() */
213 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
215 /* Only load if we're not late */
218 StartSourceMod(false);
224 void SourceModBase::StartSourceMod(bool late)
226 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
227 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
229 enginePatch = SH_GET_CALLCLASS(engine);
230 gamedllPatch = SH_GET_CALLCLASS(gamedll);
233 SMGlobalClass *pBase = SMGlobalClass::head;
236 pBase->OnSourceModStartup(false);
237 pBase = pBase->m_pGlobalClassNext;
240 /* Make the global core identity */
241 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
244 pBase = SMGlobalClass::head;
247 pBase->OnSourceModAllInitialized();
248 pBase = pBase->m_pGlobalClassNext;
252 g_ShareSys.AddInterface(NULL, this);
258 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
260 /* If we're not loaded... */
263 /* Do all global initialization now */
264 StartSourceMod(true);
267 m_IsMapLoading = true;
268 m_ExecPluginReload = true;
270 g_LastMenuTime = 0.0f;
271 g_LastAuthCheck = 0.0f;
272 g_SimTicks.ticking = true;
273 g_SimTicks.tickcount = 0;
278 SMGlobalClass *pBase = SMGlobalClass::head;
281 pBase->OnSourceModLevelChange(pMapName);
282 pBase = pBase->m_pGlobalClassNext;
285 DoGlobalPluginLoads();
287 m_IsMapLoading = false;
290 pBase = SMGlobalClass::head;
293 pBase->OnSourceModPluginsLoaded();
294 pBase = pBase->m_pGlobalClassNext;
299 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
304 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
307 RETURN_META_VALUE(MRES_IGNORED, true);
310 void StartTickSimulation()
312 g_SimTicks.ticking = false;
313 g_SimTicks.tickcount = 0;
314 g_SimTicks.ticktime = gpGlobals->curtime;
317 void StopTickSimulation()
319 g_SimTicks.ticking = true;
320 g_Timers.MapChange();
322 g_LastTime = gpGlobals->curtime;
327 g_SimTicks.tickcount++;
328 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
331 void SourceModBase::GameFrame(bool simulating)
334 * Note: This is all hardcoded rather than delegated to save
335 * precious CPU cycles.
337 float curtime = gpGlobals->curtime;
338 int framecount = gpGlobals->framecount;
340 /* Verify that we're still ticking */
341 if (g_SimTicks.ticking)
343 if (g_StillFrames == 0)
345 g_StillFrames = framecount;
346 g_StillTime = curtime;
348 /* Try to detect when we've stopped ticking.
349 * We do this once 10 frames pass and there have been no ticks.
351 if (g_StillTime == curtime)
353 if (framecount - g_StillFrames >= 5)
355 StartTickSimulation();
359 /* We're definitely ticking we get here,
360 * but update everything as a precaution */
361 g_StillFrames = framecount;
362 g_StillTime = curtime;
366 /* We need to make sure we should still be simulating. */
367 if (g_StillTime != curtime)
369 /* Wow, we're ticking again! It's time to revert. */
370 StopTickSimulation();
373 /* Nope, not ticking. Simulate! */
375 curtime = g_SimTicks.ticktime;
378 if (curtime - g_LastTime >= 0.1f)
381 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
383 g_LastAuthCheck = gpGlobals->curtime;
384 g_Players.RunAuthChecks();
388 g_LastTime = curtime;
391 if (g_SimTicks.tickcount && (curtime - g_LastMenuTime >= 1.0f))
393 g_ValveMenuStyle.ProcessWatchList();
394 g_RadioMenuStyle.ProcessWatchList();
395 g_LastMenuTime = curtime;
398 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
400 g_pOnGameFrame->Execute(NULL);
404 void SourceModBase::LevelShutdown()
408 g_pOnMapEnd->Execute(NULL);
411 if (m_ExecPluginReload)
413 g_PluginSys.ReloadOrUnloadPlugins();
414 m_ExecPluginReload = false;
418 bool SourceModBase::IsMapLoading() const
420 return m_IsMapLoading;
423 void SourceModBase::DoGlobalPluginLoads()
425 char config_path[PLATFORM_MAX_PATH];
426 char plugins_path[PLATFORM_MAX_PATH];
428 BuildPath(Path_SM, config_path,
430 "configs/plugin_settings.cfg");
431 BuildPath(Path_SM, plugins_path,
432 sizeof(plugins_path),
435 /* Load any auto extensions */
436 g_Extensions.TryAutoload();
438 /* Run the first pass */
439 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
441 /* Mark any extensions as loaded */
442 g_Extensions.MarkAllLoaded();
444 /* No modules yet, it's safe to call this from here */
445 g_PluginSys.LoadAll_SecondPass();
447 /* Re-mark any extensions as loaded */
448 g_Extensions.MarkAllLoaded();
451 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
453 char _buffer[PLATFORM_MAX_PATH];
456 va_start(ap, format);
457 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
460 const char *base = NULL;
461 if (type == Path_Game)
463 base = GetGamePath();
464 } else if (type == Path_SM) {
465 base = GetSourceModPath();
466 } else if (type == Path_SM_Rel) {
472 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
474 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
478 void SourceModBase::CloseSourceMod()
480 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
486 g_Forwards.ReleaseForward(g_pOnGameFrame);
491 g_Forwards.ReleaseForward(g_pOnMapEnd);
495 SMGlobalClass *pBase = SMGlobalClass::head;
498 pBase->OnSourceModShutdown();
499 pBase = pBase->m_pGlobalClassNext;
502 /* Delete all data packs */
503 CStack<CDataPack *>::iterator iter;
505 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
510 m_freepacks.popall();
513 pBase = SMGlobalClass::head;
516 pBase->OnSourceModAllShutdown();
517 pBase = pBase->m_pGlobalClassNext;
522 SH_RELEASE_CALLCLASS(enginePatch);
528 SH_RELEASE_CALLCLASS(gamedllPatch);
532 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
533 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
540 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
542 IExtensionInterface *pAPI = pExt->GetAPI();
543 const char *tag = pAPI->GetExtensionTag();
547 va_start(ap, format);
548 vsnprintf(buffer, sizeof(buffer), format, ap);
553 g_Logger.LogMessage("[%s] %s", tag, buffer);
555 g_Logger.LogMessage("%s", buffer);
559 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
561 IExtensionInterface *pAPI = pExt->GetAPI();
562 const char *tag = pAPI->GetExtensionTag();
566 va_start(ap, format);
567 vsnprintf(buffer, sizeof(buffer), format, ap);
572 g_Logger.LogError("[%s] %s", tag, buffer);
574 g_Logger.LogError("%s", buffer);
578 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
582 pContext->LocalToString(params[param], &fmt);
584 int lparam = ++param;
586 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
589 const char *SourceModBase::GetSourceModPath() const
594 const char *SourceModBase::GetGamePath() const
596 return g_BaseDir.c_str();
599 void SourceModBase::SetGlobalTarget(unsigned int index)
604 void SourceModBase::SetAuthChecking(bool set)
606 m_CheckingAuth = set;
609 unsigned int SourceModBase::GetGlobalTarget() const
614 IDataPack *SourceModBase::CreateDataPack()
617 if (m_freepacks.empty())
619 pack = new CDataPack;
621 pack = m_freepacks.front();
628 void SourceModBase::FreeDataPack(IDataPack *pack)
630 m_freepacks.push(static_cast<CDataPack *>(pack));
633 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
639 const char *SourceModBase::GetGameFolderName() const
644 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
646 return g_pSourcePawn;
649 IVirtualMachine *SourceModBase::GetScriptingVM()
654 SMGlobalClass *SMGlobalClass::head = NULL;
656 SMGlobalClass::SMGlobalClass()
658 m_pGlobalClassNext = SMGlobalClass::head;
659 SMGlobalClass::head = this;