3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "sourcemod.h"
34 #include "sourcemm_api.h"
35 #include "systems/LibrarySys.h"
36 #include "vm/sp_vm_engine.h"
37 #include <sh_string.h>
38 #include "PluginSys.h"
40 #include "CoreConfig.h"
42 #include "ExtensionSys.h"
43 #include "AdminCache.h"
44 #include "sm_stringutil.h"
45 #include "PlayerManager.h"
46 #include "Translator.h"
47 #include "ForwardSys.h"
49 #include "MenuStyle_Valve.h"
50 #include "MenuStyle_Radio.h"
52 #include "HalfLife2.h"
53 #include "GameConfigs.h"
55 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
56 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
57 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
58 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
60 SourcePawnEngine g_SourcePawn;
61 SourceModBase g_SourceMod;
63 ILibrary *g_pJIT = NULL;
64 SourceHook::String g_BaseDir;
65 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
66 IVirtualMachine *g_pVM;
67 IdentityToken_t *g_pCoreIdent = NULL;
68 float g_LastTime = 0.0f;
69 float g_LastMenuTime = 0.0f;
70 float g_LastAuthCheck = 0.0f;
71 IForward *g_pOnGameFrame = NULL;
72 IForward *g_pOnMapEnd = NULL;
73 bool g_Loaded = false;
74 int g_StillFrames = 0;
75 float g_StillTime = 0.0f;
76 IExtension *g_pGameExt = NULL;
78 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
79 typedef int (*GIVEENGINEPOINTER2)(ISourcePawnEngine *, unsigned int api_version);
80 typedef unsigned int (*GETEXPORTCOUNT)();
81 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
82 typedef void (*NOTIFYSHUTDOWN)();
86 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
92 g_pJIT->CloseLibrary();
95 SourceModBase::SourceModBase()
97 m_IsMapLoading = false;
98 m_ExecPluginReload = false;
99 m_ExecOnMapEnd = false;
100 m_GotBasePath = false;
103 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
109 if (strcasecmp(key, "BasePath") == 0)
111 if (source == ConfigSource_Console)
113 UTIL_Format(error, maxlength, "Cannot be set at runtime");
114 return ConfigResult_Reject;
119 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
120 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
122 m_GotBasePath = true;
125 return ConfigResult_Accept;
128 return ConfigResult_Ignore;
131 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
133 const char *gamepath = g_SMAPI->GetBaseDir();
135 /* Store full path to game */
136 g_BaseDir.assign(gamepath);
138 /* Store name of game directory by itself */
139 size_t len = strlen(gamepath);
140 for (size_t i = len - 1; i >= 0; i--)
142 if (gamepath[i] == PLATFORM_SEP_CHAR)
144 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
149 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
150 g_CoreConfig.Initialize();
152 /* This shouldn't happen, but can't hurt to be safe */
153 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
155 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
156 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
157 m_GotBasePath = true;
160 /* Attempt to load the JIT! */
161 char file[PLATFORM_MAX_PATH];
163 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
168 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
171 if (error && maxlength)
173 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
182 GIVEENGINEPOINTER2 jit_init2 = (GIVEENGINEPOINTER2)g_pJIT->GetSymbolAddress("GiveEnginePointer2");
185 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
189 if (error && maxlength)
191 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
196 if ((err=jit_init(g_pSourcePawn)) != 0)
199 if (error && maxlength)
201 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
206 /* On version bumps, we should check for older versions as well, if the new version fails.
207 * We can then check the exports to see if any VM versions will be sufficient.
209 if ((err=jit_init2(g_pSourcePawn, SOURCEPAWN_ENGINE_API_VERSION)) != SP_ERROR_NONE)
212 if (error && maxlength)
214 snprintf(error, maxlength, "JIT incompatible with SourceMod version");
220 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
221 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
225 if (error && maxlength)
227 snprintf(error, maxlength, "JIT is missing a necessary export!");
232 unsigned int num = jit_getnum();
236 if (error && maxlength)
238 snprintf(error, maxlength, "JIT did not export any virtual machines!");
243 unsigned int api_version;
244 for (unsigned int i=0; i<num; i++)
246 if ((g_pVM=jit_get(i)) == NULL)
248 if (error && maxlength)
250 snprintf(error, maxlength, "JIT did not export any virtual machines!");
254 /* Refuse any API that we might not be able to deal with.
255 * Also refuse anything < 3 because we need fake natives.
257 api_version = g_pVM->GetAPIVersion();
258 if (api_version < 3 || api_version > SOURCEPAWN_VM_API_VERSION)
260 if (error && maxlength)
262 snprintf(error, maxlength, "JIT is not a compatible version");
276 /* Hook this now so we can detect startup without calling StartSourceMod() */
277 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
279 /* Only load if we're not late */
282 StartSourceMod(false);
288 void SourceModBase::StartSourceMod(bool late)
290 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
291 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
293 enginePatch = SH_GET_CALLCLASS(engine);
294 gamedllPatch = SH_GET_CALLCLASS(gamedll);
297 SMGlobalClass *pBase = SMGlobalClass::head;
300 pBase->OnSourceModStartup(false);
301 pBase = pBase->m_pGlobalClassNext;
304 /* Make the global core identity */
305 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
308 pBase = SMGlobalClass::head;
311 pBase->OnSourceModAllInitialized();
312 pBase = pBase->m_pGlobalClassNext;
316 g_ShareSys.AddInterface(NULL, this);
322 static bool g_LevelEndBarrier = false;
323 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
325 /* If we're not loaded... */
328 /* Do all global initialization now */
329 StartSourceMod(true);
332 m_IsMapLoading = true;
333 m_ExecPluginReload = true;
334 m_ExecOnMapEnd = true;
336 g_LastMenuTime = 0.0f;
337 g_LastAuthCheck = 0.0f;
338 g_SimTicks.ticking = true;
339 g_SimTicks.tickcount = 0;
344 SMGlobalClass *pBase = SMGlobalClass::head;
347 pBase->OnSourceModLevelChange(pMapName);
348 pBase = pBase->m_pGlobalClassNext;
351 DoGlobalPluginLoads();
353 m_IsMapLoading = false;
356 pBase = SMGlobalClass::head;
359 pBase->OnSourceModPluginsLoaded();
360 pBase = pBase->m_pGlobalClassNext;
365 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
370 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
373 g_LevelEndBarrier = true;
375 RETURN_META_VALUE(MRES_IGNORED, true);
378 void StartTickSimulation()
380 g_SimTicks.ticking = false;
381 g_SimTicks.tickcount = 0;
382 g_SimTicks.ticktime = gpGlobals->curtime;
385 void StopTickSimulation()
387 g_SimTicks.ticking = true;
388 g_Timers.MapChange(false);
390 g_LastTime = gpGlobals->curtime;
395 g_SimTicks.tickcount++;
396 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
399 void SourceModBase::GameFrame(bool simulating)
402 g_HL2.ProcessFakeCliCmdQueue();
405 * Note: This is all hardcoded rather than delegated to save
406 * precious CPU cycles.
408 float curtime = gpGlobals->curtime;
409 int framecount = gpGlobals->framecount;
411 /* Verify that we're still ticking */
412 if (g_SimTicks.ticking)
414 if (g_StillFrames == 0)
416 g_StillFrames = framecount;
417 g_StillTime = curtime;
419 /* Try to detect when we've stopped ticking.
420 * We do this once 10 frames pass and there have been no ticks.
422 if (g_StillTime == curtime)
424 if (framecount - g_StillFrames >= 5)
426 StartTickSimulation();
430 /* We're definitely ticking we get here,
431 * but update everything as a precaution */
432 g_StillFrames = framecount;
433 g_StillTime = curtime;
437 /* We need to make sure we should still be simulating. */
438 if (g_StillTime != curtime)
440 /* Wow, we're ticking again! It's time to revert. */
441 StopTickSimulation();
444 /* Nope, not ticking. Simulate! */
446 curtime = g_SimTicks.ticktime;
449 if (curtime - g_LastTime >= 0.1f)
452 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
454 g_LastAuthCheck = gpGlobals->curtime;
455 g_Players.RunAuthChecks();
459 g_LastTime = curtime;
462 if (g_SimTicks.ticking && curtime - g_LastMenuTime >= 1.0f)
464 g_ValveMenuStyle.ProcessWatchList();
465 g_RadioMenuStyle.ProcessWatchList();
466 g_LastMenuTime = curtime;
469 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
471 g_pOnGameFrame->Execute(NULL);
475 void SourceModBase::LevelShutdown()
477 if (g_LevelEndBarrier)
479 SMGlobalClass *next = SMGlobalClass::head;
482 next->OnSourceModLevelEnd();
483 next = next->m_pGlobalClassNext;
485 g_LevelEndBarrier = false;
488 if (g_pOnMapEnd && m_ExecOnMapEnd)
490 g_pOnMapEnd->Execute(NULL);
491 m_ExecOnMapEnd = false;
494 g_OnMapStarted = false;
496 if (m_ExecPluginReload)
498 g_PluginSys.ReloadOrUnloadPlugins();
499 m_ExecPluginReload = false;
503 bool SourceModBase::IsMapLoading() const
505 return m_IsMapLoading;
508 void SourceModBase::DoGlobalPluginLoads()
510 char config_path[PLATFORM_MAX_PATH];
511 char plugins_path[PLATFORM_MAX_PATH];
513 BuildPath(Path_SM, config_path,
515 "configs/plugin_settings.cfg");
516 BuildPath(Path_SM, plugins_path,
517 sizeof(plugins_path),
520 /* Load any auto extensions */
521 g_Extensions.TryAutoload();
523 /* Load any game extension */
524 const char *game_ext;
525 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
527 char path[PLATFORM_MAX_PATH];
528 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
529 g_pGameExt = g_Extensions.LoadAutoExtension(path);
532 /* Run the first pass */
533 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
535 /* Mark any extensions as loaded */
536 g_Extensions.MarkAllLoaded();
538 /* No modules yet, it's safe to call this from here */
539 g_PluginSys.LoadAll_SecondPass();
541 /* Re-mark any extensions as loaded */
542 g_Extensions.MarkAllLoaded();
544 /* Call OnAllPluginsLoaded */
545 g_PluginSys.AllPluginsLoaded();
548 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
550 char _buffer[PLATFORM_MAX_PATH];
553 va_start(ap, format);
554 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
557 const char *base = NULL;
558 if (type == Path_Game)
560 base = GetGamePath();
561 } else if (type == Path_SM) {
562 base = GetSourceModPath();
563 } else if (type == Path_SM_Rel) {
569 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
571 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
575 void SourceModBase::CloseSourceMod()
577 /* Force a level end */
581 g_PluginSys.Shutdown();
583 /* Unload extensions */
584 g_Extensions.Shutdown();
586 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
592 g_Forwards.ReleaseForward(g_pOnGameFrame);
597 g_Forwards.ReleaseForward(g_pOnMapEnd);
601 SMGlobalClass *pBase = SMGlobalClass::head;
604 pBase->OnSourceModShutdown();
605 pBase = pBase->m_pGlobalClassNext;
608 /* Delete all data packs */
609 CStack<CDataPack *>::iterator iter;
611 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
616 m_freepacks.popall();
619 pBase = SMGlobalClass::head;
622 pBase->OnSourceModAllShutdown();
623 pBase = pBase->m_pGlobalClassNext;
628 SH_RELEASE_CALLCLASS(enginePatch);
634 SH_RELEASE_CALLCLASS(gamedllPatch);
638 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
639 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
646 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
648 IExtensionInterface *pAPI = pExt->GetAPI();
649 const char *tag = pAPI->GetExtensionTag();
653 va_start(ap, format);
654 vsnprintf(buffer, sizeof(buffer), format, ap);
659 g_Logger.LogMessage("[%s] %s", tag, buffer);
661 g_Logger.LogMessage("%s", buffer);
665 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
667 IExtensionInterface *pAPI = pExt->GetAPI();
668 const char *tag = pAPI->GetExtensionTag();
672 va_start(ap, format);
673 vsnprintf(buffer, sizeof(buffer), format, ap);
678 g_Logger.LogError("[%s] %s", tag, buffer);
680 g_Logger.LogError("%s", buffer);
684 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
688 pContext->LocalToString(params[param], &fmt);
690 int lparam = ++param;
692 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
695 const char *SourceModBase::GetSourceModPath() const
700 const char *SourceModBase::GetGamePath() const
702 return g_BaseDir.c_str();
705 void SourceModBase::SetGlobalTarget(unsigned int index)
710 void SourceModBase::SetAuthChecking(bool set)
712 m_CheckingAuth = set;
715 unsigned int SourceModBase::GetGlobalTarget() const
720 IDataPack *SourceModBase::CreateDataPack()
723 if (m_freepacks.empty())
725 pack = new CDataPack;
727 pack = m_freepacks.front();
734 void SourceModBase::FreeDataPack(IDataPack *pack)
736 m_freepacks.push(static_cast<CDataPack *>(pack));
739 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
745 const char *SourceModBase::GetGameFolderName() const
750 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
752 return g_pSourcePawn;
755 IVirtualMachine *SourceModBase::GetScriptingVM()
760 void SourceModBase::AllPluginsLoaded()
762 SMGlobalClass *base = SMGlobalClass::head;
765 base->OnSourceModGameInitialized();
766 base = base->m_pGlobalClassNext;
770 time_t SourceModBase::GetAdjustedTime()
772 return GetAdjustedTime();
775 SMGlobalClass *SMGlobalClass::head = NULL;
777 SMGlobalClass::SMGlobalClass()
779 m_pGlobalClassNext = SMGlobalClass::head;
780 SMGlobalClass::head = this;