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);
38 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
40 SourcePawnEngine g_SourcePawn;
41 SourceModBase g_SourceMod;
43 ILibrary *g_pJIT = NULL;
44 SourceHook::String g_BaseDir;
45 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
46 IVirtualMachine *g_pVM;
47 IdentityToken_t *g_pCoreIdent = NULL;
48 float g_LastTime = 0.0f;
49 float g_LastMenuTime = 0.0f;
50 float g_LastAuthCheck = 0.0f;
51 IForward *g_pOnGameFrame = NULL;
52 IForward *g_pOnMapEnd = NULL;
53 bool g_Loaded = false;
54 int g_StillFrames = 0;
55 float g_StillTime = 0.0f;
57 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
58 typedef unsigned int (*GETEXPORTCOUNT)();
59 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
60 typedef void (*NOTIFYSHUTDOWN)();
64 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
70 g_pJIT->CloseLibrary();
73 SourceModBase::SourceModBase()
75 m_IsMapLoading = false;
76 m_ExecPluginReload = false;
77 m_ExecOnMapEnd = false;
78 m_GotBasePath = false;
81 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
87 if (strcasecmp(key, "BasePath") == 0)
89 if (source == ConfigSource_Console)
91 UTIL_Format(error, maxlength, "Cannot be set at runtime");
92 return ConfigResult_Reject;
97 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
98 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
100 m_GotBasePath = true;
103 return ConfigResult_Accept;
106 return ConfigResult_Ignore;
109 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
111 const char *gamepath = g_SMAPI->GetBaseDir();
113 /* Store full path to game */
114 g_BaseDir.assign(gamepath);
116 /* Store name of game directory by itself */
117 size_t len = strlen(gamepath);
118 for (size_t i = len - 1; i >= 0; i--)
120 if (gamepath[i] == PLATFORM_SEP_CHAR)
122 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
127 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
128 g_CoreConfig.Initialize();
130 /* This shouldn't happen, but can't hurt to be safe */
131 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
133 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
134 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
135 m_GotBasePath = true;
138 /* Attempt to load the JIT! */
139 char file[PLATFORM_MAX_PATH];
141 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
146 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
149 if (error && maxlength)
151 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
159 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
163 if (error && maxlength)
165 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
170 if ((err=jit_init(g_pSourcePawn)) != 0)
173 if (error && maxlength)
175 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
180 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
181 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
185 if (error && maxlength)
187 snprintf(error, maxlength, "JIT is missing a necessary export!");
192 unsigned int num = jit_getnum();
193 if (!num || ((g_pVM=jit_get(0)) == NULL))
196 if (error && maxlength)
198 snprintf(error, maxlength, "JIT did not export any virtual machines!");
203 unsigned int api = g_pVM->GetAPIVersion();
204 /* :TODO: clean this up (see amb398) */
205 if (api > SOURCEPAWN_VM_API_VERSION || api < 2)
208 if (error && maxlength)
210 snprintf(error, maxlength, "JIT is not a compatible version");
215 /* Hook this now so we can detect startup without calling StartSourceMod() */
216 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
218 /* Only load if we're not late */
221 StartSourceMod(false);
227 void SourceModBase::StartSourceMod(bool late)
229 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
230 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
232 enginePatch = SH_GET_CALLCLASS(engine);
233 gamedllPatch = SH_GET_CALLCLASS(gamedll);
236 SMGlobalClass *pBase = SMGlobalClass::head;
239 pBase->OnSourceModStartup(false);
240 pBase = pBase->m_pGlobalClassNext;
243 /* Make the global core identity */
244 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
247 pBase = SMGlobalClass::head;
250 pBase->OnSourceModAllInitialized();
251 pBase = pBase->m_pGlobalClassNext;
255 g_ShareSys.AddInterface(NULL, this);
261 static bool g_LevelEndBarrier = false;
262 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
264 /* If we're not loaded... */
267 /* Do all global initialization now */
268 StartSourceMod(true);
271 m_IsMapLoading = true;
272 m_ExecPluginReload = true;
273 m_ExecOnMapEnd = true;
275 g_LastMenuTime = 0.0f;
276 g_LastAuthCheck = 0.0f;
277 g_SimTicks.ticking = true;
278 g_SimTicks.tickcount = 0;
283 SMGlobalClass *pBase = SMGlobalClass::head;
286 pBase->OnSourceModLevelChange(pMapName);
287 pBase = pBase->m_pGlobalClassNext;
290 DoGlobalPluginLoads();
292 m_IsMapLoading = false;
295 pBase = SMGlobalClass::head;
298 pBase->OnSourceModPluginsLoaded();
299 pBase = pBase->m_pGlobalClassNext;
304 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
309 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
312 g_LevelEndBarrier = true;
314 RETURN_META_VALUE(MRES_IGNORED, true);
317 void StartTickSimulation()
319 g_SimTicks.ticking = false;
320 g_SimTicks.tickcount = 0;
321 g_SimTicks.ticktime = gpGlobals->curtime;
324 void StopTickSimulation()
326 g_SimTicks.ticking = true;
327 g_Timers.MapChange();
329 g_LastTime = gpGlobals->curtime;
334 g_SimTicks.tickcount++;
335 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
338 void SourceModBase::GameFrame(bool simulating)
341 * Note: This is all hardcoded rather than delegated to save
342 * precious CPU cycles.
344 float curtime = gpGlobals->curtime;
345 int framecount = gpGlobals->framecount;
347 /* Verify that we're still ticking */
348 if (g_SimTicks.ticking)
350 if (g_StillFrames == 0)
352 g_StillFrames = framecount;
353 g_StillTime = curtime;
355 /* Try to detect when we've stopped ticking.
356 * We do this once 10 frames pass and there have been no ticks.
358 if (g_StillTime == curtime)
360 if (framecount - g_StillFrames >= 5)
362 StartTickSimulation();
366 /* We're definitely ticking we get here,
367 * but update everything as a precaution */
368 g_StillFrames = framecount;
369 g_StillTime = curtime;
373 /* We need to make sure we should still be simulating. */
374 if (g_StillTime != curtime)
376 /* Wow, we're ticking again! It's time to revert. */
377 StopTickSimulation();
380 /* Nope, not ticking. Simulate! */
382 curtime = g_SimTicks.ticktime;
385 if (curtime - g_LastTime >= 0.1f)
388 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
390 g_LastAuthCheck = gpGlobals->curtime;
391 g_Players.RunAuthChecks();
395 g_LastTime = curtime;
398 if (g_SimTicks.ticking && curtime - g_LastMenuTime >= 1.0f)
400 g_ValveMenuStyle.ProcessWatchList();
401 g_RadioMenuStyle.ProcessWatchList();
402 g_LastMenuTime = curtime;
405 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
407 g_pOnGameFrame->Execute(NULL);
411 void SourceModBase::LevelShutdown()
413 if (g_LevelEndBarrier)
415 SMGlobalClass *next = SMGlobalClass::head;
418 next->OnSourceModLevelEnd();
419 next = next->m_pGlobalClassNext;
421 g_LevelEndBarrier = false;
424 if (g_pOnMapEnd && m_ExecOnMapEnd)
426 g_pOnMapEnd->Execute(NULL);
427 m_ExecOnMapEnd = false;
430 g_OnMapStarted = false;
432 if (m_ExecPluginReload)
434 g_PluginSys.ReloadOrUnloadPlugins();
435 m_ExecPluginReload = false;
439 bool SourceModBase::IsMapLoading() const
441 return m_IsMapLoading;
444 void SourceModBase::DoGlobalPluginLoads()
446 char config_path[PLATFORM_MAX_PATH];
447 char plugins_path[PLATFORM_MAX_PATH];
449 BuildPath(Path_SM, config_path,
451 "configs/plugin_settings.cfg");
452 BuildPath(Path_SM, plugins_path,
453 sizeof(plugins_path),
456 /* Load any auto extensions */
457 g_Extensions.TryAutoload();
459 /* Run the first pass */
460 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
462 /* Mark any extensions as loaded */
463 g_Extensions.MarkAllLoaded();
465 /* No modules yet, it's safe to call this from here */
466 g_PluginSys.LoadAll_SecondPass();
468 /* Re-mark any extensions as loaded */
469 g_Extensions.MarkAllLoaded();
472 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
474 char _buffer[PLATFORM_MAX_PATH];
477 va_start(ap, format);
478 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
481 const char *base = NULL;
482 if (type == Path_Game)
484 base = GetGamePath();
485 } else if (type == Path_SM) {
486 base = GetSourceModPath();
487 } else if (type == Path_SM_Rel) {
493 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
495 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
499 void SourceModBase::CloseSourceMod()
501 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
507 g_Forwards.ReleaseForward(g_pOnGameFrame);
512 g_Forwards.ReleaseForward(g_pOnMapEnd);
516 SMGlobalClass *pBase = SMGlobalClass::head;
519 pBase->OnSourceModShutdown();
520 pBase = pBase->m_pGlobalClassNext;
523 /* Delete all data packs */
524 CStack<CDataPack *>::iterator iter;
526 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
531 m_freepacks.popall();
534 pBase = SMGlobalClass::head;
537 pBase->OnSourceModAllShutdown();
538 pBase = pBase->m_pGlobalClassNext;
543 SH_RELEASE_CALLCLASS(enginePatch);
549 SH_RELEASE_CALLCLASS(gamedllPatch);
553 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
554 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
561 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
563 IExtensionInterface *pAPI = pExt->GetAPI();
564 const char *tag = pAPI->GetExtensionTag();
568 va_start(ap, format);
569 vsnprintf(buffer, sizeof(buffer), format, ap);
574 g_Logger.LogMessage("[%s] %s", tag, buffer);
576 g_Logger.LogMessage("%s", buffer);
580 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
582 IExtensionInterface *pAPI = pExt->GetAPI();
583 const char *tag = pAPI->GetExtensionTag();
587 va_start(ap, format);
588 vsnprintf(buffer, sizeof(buffer), format, ap);
593 g_Logger.LogError("[%s] %s", tag, buffer);
595 g_Logger.LogError("%s", buffer);
599 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
603 pContext->LocalToString(params[param], &fmt);
605 int lparam = ++param;
607 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
610 const char *SourceModBase::GetSourceModPath() const
615 const char *SourceModBase::GetGamePath() const
617 return g_BaseDir.c_str();
620 void SourceModBase::SetGlobalTarget(unsigned int index)
625 void SourceModBase::SetAuthChecking(bool set)
627 m_CheckingAuth = set;
630 unsigned int SourceModBase::GetGlobalTarget() const
635 IDataPack *SourceModBase::CreateDataPack()
638 if (m_freepacks.empty())
640 pack = new CDataPack;
642 pack = m_freepacks.front();
649 void SourceModBase::FreeDataPack(IDataPack *pack)
651 m_freepacks.push(static_cast<CDataPack *>(pack));
654 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
660 const char *SourceModBase::GetGameFolderName() const
665 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
667 return g_pSourcePawn;
670 IVirtualMachine *SourceModBase::GetScriptingVM()
675 void SourceModBase::AllPluginsLoaded()
677 SMGlobalClass *base = SMGlobalClass::head;
680 base->OnSourceModGameInitialized();
681 base = base->m_pGlobalClassNext;
685 SMGlobalClass *SMGlobalClass::head = NULL;
687 SMGlobalClass::SMGlobalClass()
689 m_pGlobalClassNext = SMGlobalClass::head;
690 SMGlobalClass::head = this;