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"
34 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
35 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
36 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
38 SourcePawnEngine g_SourcePawn;
39 SourceModBase g_SourceMod;
41 ILibrary *g_pJIT = NULL;
42 SourceHook::String g_BaseDir;
43 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
44 IVirtualMachine *g_pVM;
45 IdentityToken_t *g_pCoreIdent = NULL;
46 float g_LastTime = 0.0f;
47 float g_LastMenuTime = 0.0f;
48 float g_LastAuthCheck = 0.0f;
49 IForward *g_pOnGameFrame = NULL;
50 IForward *g_pOnMapEnd = NULL;
51 bool g_Loaded = false;
52 int g_StillFrames = 0;
53 float g_StillTime = 0.0f;
55 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
56 typedef unsigned int (*GETEXPORTCOUNT)();
57 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
58 typedef void (*NOTIFYSHUTDOWN)();
62 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
68 g_pJIT->CloseLibrary();
71 SourceModBase::SourceModBase()
73 m_IsMapLoading = false;
74 m_ExecPluginReload = false;
75 m_GotBasePath = false;
78 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
84 if (strcasecmp(key, "BasePath") == 0)
86 if (source == ConfigSource_Console)
88 UTIL_Format(error, maxlength, "Cannot be set at runtime");
89 return ConfigResult_Reject;
94 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
95 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
100 return ConfigResult_Accept;
103 return ConfigResult_Ignore;
106 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
108 const char *gamepath = g_SMAPI->GetBaseDir();
110 /* Store full path to game */
111 g_BaseDir.assign(gamepath);
113 /* Store name of game directory by itself */
114 size_t len = strlen(gamepath);
115 for (size_t i = len - 1; i >= 0; i--)
117 if (gamepath[i] == PLATFORM_SEP_CHAR)
119 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
124 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
125 g_CoreConfig.Initialize();
127 /* This shouldn't happen, but can't hurt to be safe */
128 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
130 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
131 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
132 m_GotBasePath = true;
135 /* Attempt to load the JIT! */
136 char file[PLATFORM_MAX_PATH];
138 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
143 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
146 if (error && maxlength)
148 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
156 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
160 if (error && maxlength)
162 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
167 if ((err=jit_init(g_pSourcePawn)) != 0)
170 if (error && maxlength)
172 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
177 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
178 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
182 if (error && maxlength)
184 snprintf(error, maxlength, "JIT is missing a necessary export!");
189 unsigned int num = jit_getnum();
190 if (!num || ((g_pVM=jit_get(0)) == NULL))
193 if (error && maxlength)
195 snprintf(error, maxlength, "JIT did not export any virtual machines!");
200 unsigned int api = g_pVM->GetAPIVersion();
201 if (api != SOURCEPAWN_VM_API_VERSION)
204 if (error && maxlength)
206 snprintf(error, maxlength, "JIT is not a compatible version");
211 /* Hook this now so we can detect startup without calling StartSourceMod() */
212 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
214 /* Only load if we're not late */
217 StartSourceMod(false);
223 void SourceModBase::StartSourceMod(bool late)
225 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
226 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
228 enginePatch = SH_GET_CALLCLASS(engine);
229 gamedllPatch = SH_GET_CALLCLASS(gamedll);
232 SMGlobalClass *pBase = SMGlobalClass::head;
235 pBase->OnSourceModStartup(false);
236 pBase = pBase->m_pGlobalClassNext;
239 /* Make the global core identity */
240 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
243 pBase = SMGlobalClass::head;
246 pBase->OnSourceModAllInitialized();
247 pBase = pBase->m_pGlobalClassNext;
251 g_ShareSys.AddInterface(NULL, this);
257 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
259 /* If we're not loaded... */
262 /* Do all global initialization now */
263 StartSourceMod(true);
266 m_IsMapLoading = true;
267 m_ExecPluginReload = true;
269 g_LastMenuTime = 0.0f;
270 g_LastAuthCheck = 0.0f;
271 g_SimTicks.ticking = true;
272 g_SimTicks.tickcount = 0;
277 SMGlobalClass *pBase = SMGlobalClass::head;
280 pBase->OnSourceModLevelChange(pMapName);
281 pBase = pBase->m_pGlobalClassNext;
284 DoGlobalPluginLoads();
286 m_IsMapLoading = false;
289 pBase = SMGlobalClass::head;
292 pBase->OnSourceModPluginsLoaded();
293 pBase = pBase->m_pGlobalClassNext;
298 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
303 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
306 RETURN_META_VALUE(MRES_IGNORED, true);
309 void StartTickSimulation()
311 g_SimTicks.ticking = false;
312 g_SimTicks.tickcount = 0;
313 g_SimTicks.ticktime = gpGlobals->curtime;
316 void StopTickSimulation()
318 g_SimTicks.ticking = true;
319 g_Timers.MapChange();
321 g_LastTime = gpGlobals->curtime;
326 g_SimTicks.tickcount++;
327 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
330 void SourceModBase::GameFrame(bool simulating)
333 * Note: This is all hardcoded rather than delegated to save
334 * precious CPU cycles.
336 float curtime = gpGlobals->curtime;
337 int framecount = gpGlobals->framecount;
339 /* Verify that we're still ticking */
340 if (g_SimTicks.ticking)
342 if (g_StillFrames == 0)
344 g_StillFrames = framecount;
345 g_StillTime = curtime;
347 /* Try to detect when we've stopped ticking.
348 * We do this once 10 frames pass and there have been no ticks.
350 if (g_StillTime == curtime)
352 if (framecount - g_StillFrames >= 5)
354 StartTickSimulation();
358 /* We're definitely ticking we get here,
359 * but update everything as a precaution */
360 g_StillFrames = framecount;
361 g_StillTime = curtime;
365 /* We need to make sure we should still be simulating. */
366 if (g_StillTime != curtime)
368 /* Wow, we're ticking again! It's time to revert. */
369 StopTickSimulation();
372 /* Nope, not ticking. Simulate! */
374 curtime = g_SimTicks.ticktime;
377 if (curtime - g_LastTime >= 0.1f)
380 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
382 g_LastAuthCheck = gpGlobals->curtime;
383 g_Players.RunAuthChecks();
387 g_LastTime = curtime;
390 if (g_SimTicks.tickcount && (curtime - g_LastMenuTime >= 1.0f))
392 g_ValveMenuStyle.ProcessWatchList();
393 g_LastMenuTime = curtime;
396 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
398 g_pOnGameFrame->Execute(NULL);
402 void SourceModBase::LevelShutdown()
406 g_pOnMapEnd->Execute(NULL);
409 if (m_ExecPluginReload)
411 g_PluginSys.ReloadOrUnloadPlugins();
412 m_ExecPluginReload = false;
416 bool SourceModBase::IsMapLoading() const
418 return m_IsMapLoading;
421 void SourceModBase::DoGlobalPluginLoads()
423 char config_path[PLATFORM_MAX_PATH];
424 char plugins_path[PLATFORM_MAX_PATH];
426 BuildPath(Path_SM, config_path,
428 "configs/plugin_settings.cfg");
429 BuildPath(Path_SM, plugins_path,
430 sizeof(plugins_path),
433 /* Load any auto extensions */
434 g_Extensions.TryAutoload();
436 /* Run the first pass */
437 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
439 /* Mark any extensions as loaded */
440 g_Extensions.MarkAllLoaded();
442 /* No modules yet, it's safe to call this from here */
443 g_PluginSys.LoadAll_SecondPass();
445 /* Re-mark any extensions as loaded */
446 g_Extensions.MarkAllLoaded();
449 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
451 char _buffer[PLATFORM_MAX_PATH];
454 va_start(ap, format);
455 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
458 const char *base = NULL;
459 if (type == Path_Game)
461 base = GetGamePath();
462 } else if (type == Path_SM) {
463 base = GetSourceModPath();
464 } else if (type == Path_SM_Rel) {
470 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
472 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
476 void SourceModBase::CloseSourceMod()
478 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
484 g_Forwards.ReleaseForward(g_pOnGameFrame);
489 g_Forwards.ReleaseForward(g_pOnMapEnd);
493 SMGlobalClass *pBase = SMGlobalClass::head;
496 pBase->OnSourceModShutdown();
497 pBase = pBase->m_pGlobalClassNext;
500 /* Delete all data packs */
501 CStack<CDataPack *>::iterator iter;
503 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
508 m_freepacks.popall();
511 pBase = SMGlobalClass::head;
514 pBase->OnSourceModAllShutdown();
515 pBase = pBase->m_pGlobalClassNext;
520 SH_RELEASE_CALLCLASS(enginePatch);
526 SH_RELEASE_CALLCLASS(gamedllPatch);
530 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
531 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
538 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
540 IExtensionInterface *pAPI = pExt->GetAPI();
541 const char *tag = pAPI->GetExtensionTag();
545 va_start(ap, format);
546 vsnprintf(buffer, sizeof(buffer), format, ap);
551 g_Logger.LogMessage("[%s] %s", tag, buffer);
553 g_Logger.LogMessage("%s", buffer);
557 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
559 IExtensionInterface *pAPI = pExt->GetAPI();
560 const char *tag = pAPI->GetExtensionTag();
564 va_start(ap, format);
565 vsnprintf(buffer, sizeof(buffer), format, ap);
570 g_Logger.LogError("[%s] %s", tag, buffer);
572 g_Logger.LogError("%s", buffer);
576 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
580 pContext->LocalToString(params[param], &fmt);
582 int lparam = ++param;
584 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
587 const char *SourceModBase::GetSourceModPath() const
592 const char *SourceModBase::GetGamePath() const
594 return g_BaseDir.c_str();
597 void SourceModBase::SetGlobalTarget(unsigned int index)
602 void SourceModBase::SetAuthChecking(bool set)
604 m_CheckingAuth = set;
607 unsigned int SourceModBase::GetGlobalTarget() const
612 IDataPack *SourceModBase::CreateDataPack()
615 if (m_freepacks.empty())
617 pack = new CDataPack;
619 pack = m_freepacks.front();
626 void SourceModBase::FreeDataPack(IDataPack *pack)
628 m_freepacks.push(static_cast<CDataPack *>(pack));
631 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
637 const char *SourceModBase::GetGameFolderName() const
642 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
644 return g_pSourcePawn;
647 IVirtualMachine *SourceModBase::GetScriptingVM()
652 SMGlobalClass *SMGlobalClass::head = NULL;
654 SMGlobalClass::SMGlobalClass()
656 m_pGlobalClassNext = SMGlobalClass::head;
657 SMGlobalClass::head = this;