3 * =============================================================================
5 * Copyright (C) 2004-2010 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 "LibrarySys.h"
36 #include <sh_string.h>
37 #include "PluginSys.h"
39 #include "CoreConfig.h"
41 #include "ExtensionSys.h"
42 #include "AdminCache.h"
43 #include "sm_stringutil.h"
44 #include "PlayerManager.h"
45 #include "ForwardSys.h"
47 #include <IGameConfigs.h>
48 #include "frame_hooks.h"
49 #include "logic_bridge.h"
51 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
52 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
53 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
54 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
56 SourceModBase g_SourceMod;
58 ILibrary *g_pJIT = NULL;
59 SourceHook::String g_BaseDir;
60 ISourcePawnEngine *g_pSourcePawn = NULL;
61 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
62 IdentityToken_t *g_pCoreIdent = NULL;
63 IForward *g_pOnMapEnd = NULL;
64 IGameConfig *g_pGameConf = NULL;
65 bool g_Loaded = false;
66 bool sm_show_debug_spew = false;
68 typedef ISourcePawnEngine *(*GET_SP_V1)();
69 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
70 typedef void (*NOTIFYSHUTDOWN)();
72 #ifdef PLATFORM_WINDOWS
73 ConVar sm_basepath("sm_basepath", "addons\\sourcemod", 0, "SourceMod base path (set via command line)");
74 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
75 ConVar sm_basepath("sm_basepath", "addons/sourcemod", 0, "SourceMod base path (set via command line)");
80 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
86 if (g_pSourcePawn2 != NULL)
88 g_pSourcePawn2->Shutdown();
91 g_pJIT->CloseLibrary();
94 SourceModBase::SourceModBase()
96 m_IsMapLoading = false;
97 m_ExecPluginReload = false;
98 m_GotBasePath = false;
101 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
107 if (strcasecmp(key, "BasePath") == 0)
109 if (source == ConfigSource_Console)
111 UTIL_Format(error, maxlength, "Cannot be set at runtime");
112 return ConfigResult_Reject;
117 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
118 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
120 m_GotBasePath = true;
123 return ConfigResult_Accept;
125 else if (strcasecmp(key, "DebugSpew") == 0)
127 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
129 return ConfigResult_Accept;
132 return ConfigResult_Ignore;
135 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
137 const char *gamepath = g_SMAPI->GetBaseDir();
139 /* Store full path to game */
140 g_BaseDir.assign(gamepath);
142 /* Store name of game directory by itself */
143 size_t len = strlen(gamepath);
144 for (size_t i = len - 1; i < len; i--)
146 if (gamepath[i] == PLATFORM_SEP_CHAR)
148 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
153 const char *basepath = icvar->GetCommandLineValue("sm_basepath");
154 /* Set a custom base path if there is one. */
155 if (basepath != NULL && basepath[0] != '\0')
157 m_GotBasePath = true;
159 /* Otherwise, use a default and keep the m_GotBasePath unlocked. */
162 basepath = sm_basepath.GetDefault();
165 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), basepath);
166 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "%s", basepath);
168 if (!StartLogicBridge(error, maxlength))
173 /* Initialize CoreConfig to get the SourceMod base path properly - this parses core.cfg */
174 g_CoreConfig.Initialize();
176 /* There will always be a path by this point, since it was force-set above. */
177 m_GotBasePath = true;
179 /* Attempt to load the JIT! */
180 char file[PLATFORM_MAX_PATH];
182 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
187 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
190 if (error && maxlength)
192 UTIL_Format(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
199 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
200 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
204 if (error && maxlength)
206 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
211 else if (getv2 == NULL)
213 if (error && maxlength)
215 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
221 g_pSourcePawn = getv1();
222 g_pSourcePawn2 = getv2();
224 if (g_pSourcePawn2->GetAPIVersion() < 3)
226 g_pSourcePawn2 = NULL;
227 if (error && maxlength)
229 snprintf(error, maxlength, "JIT version is out of date");
234 if (!g_pSourcePawn2->Initialize())
236 g_pSourcePawn2 = NULL;
237 if (error && maxlength)
239 snprintf(error, maxlength, "JIT could not be initialized");
244 g_pSourcePawn2->SetDebugListener(logicore.debugger);
246 /* Hook this now so we can detect startup without calling StartSourceMod() */
247 SH_ADD_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(this, &SourceModBase::LevelInit), false);
249 /* Only load if we're not late */
252 StartSourceMod(false);
258 void SourceModBase::StartSourceMod(bool late)
260 SH_ADD_HOOK(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false);
261 SH_ADD_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false);
263 enginePatch = SH_GET_CALLCLASS(engine);
264 gamedllPatch = SH_GET_CALLCLASS(gamedll);
266 g_ShareSys.Initialize();
268 /* Make the global core identity */
269 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
274 SMGlobalClass *pBase = SMGlobalClass::head;
277 pBase->OnSourceModStartup(false);
278 pBase = pBase->m_pGlobalClassNext;
280 g_pGameConf = logicore.GetCoreGameConfig();
283 pBase = SMGlobalClass::head;
286 pBase->OnSourceModAllInitialized();
287 pBase = pBase->m_pGlobalClassNext;
291 pBase = SMGlobalClass::head;
294 pBase->OnSourceModAllInitialized_Post();
295 pBase = pBase->m_pGlobalClassNext;
299 g_ShareSys.AddInterface(NULL, this);
304 /* Initialize VSP stuff */
305 if (vsp_interface != NULL)
307 g_SourceMod_Core.OnVSPListening(vsp_interface);
310 /* If we want to autoload, do that now */
311 const char *disabled = GetCoreConfigValue("DisableAutoUpdate");
312 if (disabled == NULL || strcasecmp(disabled, "yes") != 0)
314 g_Extensions.LoadAutoExtension("updater.ext." PLATFORM_LIB_EXT);
318 static bool g_LevelEndBarrier = false;
319 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
321 /* If we're not loaded... */
324 /* Do all global initialization now */
325 StartSourceMod(true);
328 m_IsMapLoading = true;
329 m_ExecPluginReload = true;
332 SMGlobalClass *pBase = SMGlobalClass::head;
335 pBase->OnSourceModLevelChange(pMapName);
336 pBase = pBase->m_pGlobalClassNext;
339 DoGlobalPluginLoads();
341 m_IsMapLoading = false;
344 pBase = SMGlobalClass::head;
347 pBase->OnSourceModPluginsLoaded();
348 pBase = pBase->m_pGlobalClassNext;
353 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
356 g_LevelEndBarrier = true;
358 RETURN_META_VALUE(MRES_IGNORED, true);
361 void SourceModBase::LevelShutdown()
363 if (g_LevelEndBarrier)
365 SMGlobalClass *next = SMGlobalClass::head;
368 next->OnSourceModLevelEnd();
369 next = next->m_pGlobalClassNext;
372 if (g_pOnMapEnd != NULL)
374 g_pOnMapEnd->Execute(NULL);
377 g_Timers.RemoveMapChangeTimers();
379 g_LevelEndBarrier = false;
382 g_OnMapStarted = false;
384 if (m_ExecPluginReload)
386 g_PluginSys.ReloadOrUnloadPlugins();
387 m_ExecPluginReload = false;
391 bool SourceModBase::IsMapLoading() const
393 return m_IsMapLoading;
396 void SourceModBase::DoGlobalPluginLoads()
398 char config_path[PLATFORM_MAX_PATH];
399 char plugins_path[PLATFORM_MAX_PATH];
401 BuildPath(Path_SM, config_path,
403 "configs/plugin_settings.cfg");
404 BuildPath(Path_SM, plugins_path,
405 sizeof(plugins_path),
408 /* Load any auto extensions */
409 g_Extensions.TryAutoload();
411 /* Fire the extensions ready message */
412 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
414 /* Load any game extension */
415 const char *game_ext;
416 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
418 char path[PLATFORM_MAX_PATH];
419 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
420 g_Extensions.LoadAutoExtension(path);
423 /* Run the first pass */
424 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
426 /* Mark any extensions as loaded */
427 g_Extensions.MarkAllLoaded();
429 /* No modules yet, it's safe to call this from here */
430 g_PluginSys.LoadAll_SecondPass();
432 /* Re-mark any extensions as loaded */
433 g_Extensions.MarkAllLoaded();
435 /* Call OnAllPluginsLoaded */
436 g_PluginSys.AllPluginsLoaded();
439 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
441 char _buffer[PLATFORM_MAX_PATH];
444 va_start(ap, format);
445 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
448 /* If we get a "file://" notation, strip off the file:// part so we're left
449 * with an absolute path. Note that the absolute path gets returned, so
450 * usage with relative paths here is completely invalid.
452 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
454 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
457 const char *base = NULL;
458 if (type == Path_Game)
460 base = GetGamePath();
462 else if (type == Path_SM)
464 base = GetSourceModPath();
466 else if (type == Path_SM_Rel)
473 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
477 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
481 void SourceModBase::CloseSourceMod()
483 /* Force a level end */
487 g_PluginSys.Shutdown();
489 /* Unload extensions */
490 g_Extensions.Shutdown();
492 SH_REMOVE_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(this, &SourceModBase::LevelInit), false);
498 g_Forwards.ReleaseForward(g_pOnMapEnd);
502 SMGlobalClass *pBase = SMGlobalClass::head;
505 pBase->OnSourceModShutdown();
506 pBase = pBase->m_pGlobalClassNext;
509 /* Delete all data packs */
510 CStack<CDataPack *>::iterator iter;
512 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
517 m_freepacks.popall();
520 pBase = SMGlobalClass::head;
523 pBase->OnSourceModAllShutdown();
524 pBase = pBase->m_pGlobalClassNext;
529 SH_RELEASE_CALLCLASS(enginePatch);
535 SH_RELEASE_CALLCLASS(gamedllPatch);
539 SH_REMOVE_HOOK(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false);
540 SH_REMOVE_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false);
544 ShutdownLogicBridge();
548 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
550 IExtensionInterface *pAPI = pExt->GetAPI();
551 const char *tag = pAPI->GetExtensionTag();
555 va_start(ap, format);
556 vsnprintf(buffer, sizeof(buffer), format, ap);
561 g_Logger.LogMessage("[%s] %s", tag, buffer);
563 g_Logger.LogMessage("%s", buffer);
567 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
569 IExtensionInterface *pAPI = pExt->GetAPI();
570 const char *tag = pAPI->GetExtensionTag();
574 va_start(ap, format);
575 vsnprintf(buffer, sizeof(buffer), format, ap);
580 g_Logger.LogError("[%s] %s", tag, buffer);
582 g_Logger.LogError("%s", buffer);
586 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
590 pContext->LocalToString(params[param], &fmt);
592 int lparam = ++param;
594 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
597 const char *SourceModBase::GetSourceModPath() const
602 const char *SourceModBase::GetGamePath() const
604 return g_BaseDir.c_str();
607 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
609 unsigned int old = m_target;
614 unsigned int SourceModBase::GetGlobalTarget() const
619 IDataPack *SourceModBase::CreateDataPack()
622 if (m_freepacks.empty())
624 pack = new CDataPack;
626 pack = m_freepacks.front();
633 void SourceModBase::FreeDataPack(IDataPack *pack)
635 m_freepacks.push(static_cast<CDataPack *>(pack));
638 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
644 const char *SourceModBase::GetGameFolderName() const
649 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
651 return g_pSourcePawn;
654 IVirtualMachine *SourceModBase::GetScriptingVM()
659 void SourceModBase::AllPluginsLoaded()
661 SMGlobalClass *base = SMGlobalClass::head;
664 base->OnSourceModGameInitialized();
665 base = base->m_pGlobalClassNext;
669 time_t SourceModBase::GetAdjustedTime()
671 return ::GetAdjustedTime();
674 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
676 m_frame_hooks.push_back(hook);
679 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
681 for (size_t i = 0; i < m_frame_hooks.size(); i++)
683 if (m_frame_hooks[i] == hook)
685 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
691 void SourceModBase::ProcessGameFrameHooks(bool simulating)
693 if (m_frame_hooks.size() == 0)
698 for (size_t i = 0; i < m_frame_hooks.size(); i++)
700 m_frame_hooks[i](simulating);
704 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
710 len = FormatArgs(buffer, maxlength, fmt, ap);
716 size_t SourceModBase::FormatArgs(char *buffer,
721 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
724 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
726 ::AddFrameAction(FrameAction(fn, data));
729 const char *SourceModBase::GetCoreConfigValue(const char *key)
731 return g_CoreConfig.GetCoreConfigValue(key);
734 int SourceModBase::GetPluginId()
739 int SourceModBase::GetShApiVersion()
742 g_SMAPI->GetShVersions(api, impl);
747 bool SourceModBase::IsMapRunning()
749 return g_OnMapStarted;
752 SMGlobalClass *SMGlobalClass::head = NULL;