2 * vim: set ts=4 sw=4 tw=99 noet:
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 "CoreConfig.h"
39 #include "AdminCache.h"
40 #include "sm_stringutil.h"
41 #include "PlayerManager.h"
42 #include "ForwardSys.h"
44 #include <IGameConfigs.h>
45 #include "frame_hooks.h"
46 #include "logic_bridge.h"
48 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
49 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
50 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
51 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
53 SourceModBase g_SourceMod;
55 ILibrary *g_pJIT = NULL;
56 SourceHook::String g_BaseDir;
57 ISourcePawnEngine *g_pSourcePawn = NULL;
58 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
59 IdentityToken_t *g_pCoreIdent = NULL;
60 IForward *g_pOnMapEnd = NULL;
61 IGameConfig *g_pGameConf = NULL;
62 bool g_Loaded = false;
63 bool sm_show_debug_spew = false;
64 bool sm_disable_jit = false;
66 typedef ISourcePawnEngine *(*GET_SP_V1)();
67 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
68 typedef void (*NOTIFYSHUTDOWN)();
70 #ifdef PLATFORM_WINDOWS
71 ConVar sm_basepath("sm_basepath", "addons\\sourcemod", 0, "SourceMod base path (set via command line)");
72 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
73 ConVar sm_basepath("sm_basepath", "addons/sourcemod", 0, "SourceMod base path (set via command line)");
78 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
84 if (g_pSourcePawn2 != NULL)
86 g_pSourcePawn2->Shutdown();
89 g_pJIT->CloseLibrary();
92 SourceModBase::SourceModBase()
94 m_IsMapLoading = false;
95 m_ExecPluginReload = false;
96 m_GotBasePath = false;
99 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
105 if (strcasecmp(key, "BasePath") == 0)
107 if (source == ConfigSource_Console)
109 UTIL_Format(error, maxlength, "Cannot be set at runtime");
110 return ConfigResult_Reject;
115 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
116 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
118 m_GotBasePath = true;
121 return ConfigResult_Accept;
123 else if (strcasecmp(key, "DebugSpew") == 0)
125 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
127 return ConfigResult_Accept;
129 else if (strcasecmp(key, "DisableJIT") == 0)
131 sm_disable_jit = (strcasecmp(value, "yes") == 0) ? true : false;
133 g_pSourcePawn2->SetJitEnabled(!sm_disable_jit);
135 return ConfigResult_Accept;
138 return ConfigResult_Ignore;
141 static bool sSourceModInitialized = false;
143 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
145 const char *gamepath = g_SMAPI->GetBaseDir();
147 /* Store full path to game */
148 g_BaseDir.assign(gamepath);
150 /* Store name of game directory by itself */
151 size_t len = strlen(gamepath);
152 for (size_t i = len - 1; i < len; i--)
154 if (gamepath[i] == PLATFORM_SEP_CHAR)
156 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
161 const char *basepath = icvar->GetCommandLineValue("sm_basepath");
162 /* Set a custom base path if there is one. */
163 if (basepath != NULL && basepath[0] != '\0')
165 m_GotBasePath = true;
167 /* Otherwise, use a default and keep the m_GotBasePath unlocked. */
170 basepath = sm_basepath.GetDefault();
173 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), basepath);
174 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "%s", basepath);
176 if (!StartLogicBridge(error, maxlength))
181 /* Initialize CoreConfig to get the SourceMod base path properly - this parses core.cfg */
182 g_CoreConfig.Initialize();
184 /* There will always be a path by this point, since it was force-set above. */
185 m_GotBasePath = true;
187 /* Attempt to load the JIT! */
188 char file[PLATFORM_MAX_PATH];
190 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
195 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
198 if (error && maxlength)
200 UTIL_Format(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
207 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
208 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
212 if (error && maxlength)
214 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
219 else if (getv2 == NULL)
221 if (error && maxlength)
223 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
229 g_pSourcePawn = getv1();
230 g_pSourcePawn2 = getv2();
232 if (g_pSourcePawn2->GetAPIVersion() < 3)
234 g_pSourcePawn2 = NULL;
235 if (error && maxlength)
237 snprintf(error, maxlength, "JIT version is out of date");
242 if (!g_pSourcePawn2->Initialize())
244 g_pSourcePawn2 = NULL;
245 if (error && maxlength)
247 snprintf(error, maxlength, "JIT could not be initialized");
252 g_pSourcePawn2->SetDebugListener(logicore.debugger);
255 g_pSourcePawn2->SetJitEnabled(!sm_disable_jit);
257 sSourceModInitialized = true;
259 /* Hook this now so we can detect startup without calling StartSourceMod() */
260 SH_ADD_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(this, &SourceModBase::LevelInit), false);
262 /* Only load if we're not late */
265 StartSourceMod(false);
271 void SourceModBase::StartSourceMod(bool late)
273 SH_ADD_HOOK(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false);
274 SH_ADD_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false);
276 enginePatch = SH_GET_CALLCLASS(engine);
277 gamedllPatch = SH_GET_CALLCLASS(gamedll);
282 SMGlobalClass *pBase = SMGlobalClass::head;
285 pBase->OnSourceModStartup(false);
286 pBase = pBase->m_pGlobalClassNext;
288 g_pGameConf = logicore.GetCoreGameConfig();
291 pBase = SMGlobalClass::head;
294 pBase->OnSourceModAllInitialized();
295 pBase = pBase->m_pGlobalClassNext;
299 pBase = SMGlobalClass::head;
302 pBase->OnSourceModAllInitialized_Post();
303 pBase = pBase->m_pGlobalClassNext;
307 sharesys->AddInterface(NULL, this);
312 /* Initialize VSP stuff */
313 if (vsp_interface != NULL)
315 g_SourceMod_Core.OnVSPListening(vsp_interface);
320 /* We missed doing anythin gin this if we late-loaded. Sneak it in now. */
324 /* If we want to autoload, do that now */
325 const char *disabled = GetCoreConfigValue("DisableAutoUpdate");
326 if (disabled == NULL || strcasecmp(disabled, "yes") != 0)
328 extsys->LoadAutoExtension("updater.ext." PLATFORM_LIB_EXT);
331 const char *timeout = GetCoreConfigValue("SlowScriptTimeout");
336 if (atoi(timeout) != 0)
338 g_pSourcePawn2->InstallWatchdogTimer(atoi(timeout) * 1000);
342 static bool g_LevelEndBarrier = false;
343 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
345 /* If we're not loaded... */
348 /* Do all global initialization now */
349 StartSourceMod(true);
352 m_IsMapLoading = true;
353 m_ExecPluginReload = true;
356 SMGlobalClass *pBase = SMGlobalClass::head;
359 pBase->OnSourceModLevelChange(pMapName);
360 pBase = pBase->m_pGlobalClassNext;
363 DoGlobalPluginLoads();
365 m_IsMapLoading = false;
368 pBase = SMGlobalClass::head;
371 pBase->OnSourceModPluginsLoaded();
372 pBase = pBase->m_pGlobalClassNext;
377 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
380 g_LevelEndBarrier = true;
382 RETURN_META_VALUE(MRES_IGNORED, true);
385 void SourceModBase::LevelShutdown()
387 if (g_LevelEndBarrier)
389 SMGlobalClass *next = SMGlobalClass::head;
392 next->OnSourceModLevelEnd();
393 next = next->m_pGlobalClassNext;
396 if (g_pOnMapEnd != NULL)
398 g_pOnMapEnd->Execute(NULL);
401 g_Timers.RemoveMapChangeTimers();
403 g_LevelEndBarrier = false;
406 g_OnMapStarted = false;
408 if (m_ExecPluginReload)
410 scripts->RefreshAll();
411 m_ExecPluginReload = false;
415 bool SourceModBase::IsMapLoading() const
417 return m_IsMapLoading;
420 void SourceModBase::DoGlobalPluginLoads()
422 char config_path[PLATFORM_MAX_PATH];
423 char plugins_path[PLATFORM_MAX_PATH];
425 BuildPath(Path_SM, config_path,
427 "configs/plugin_settings.cfg");
428 BuildPath(Path_SM, plugins_path,
429 sizeof(plugins_path),
432 /* Load any auto extensions */
433 extsys->TryAutoload();
435 /* Fire the extensions ready message */
436 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
438 /* Load any game extension */
439 const char *game_ext;
440 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
442 char path[PLATFORM_MAX_PATH];
443 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
444 extsys->LoadAutoExtension(path);
447 scripts->LoadAll(config_path, plugins_path);
450 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
452 char _buffer[PLATFORM_MAX_PATH];
455 va_start(ap, format);
456 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
459 /* If we get a "file://" notation, strip off the file:// part so we're left
460 * with an absolute path. Note that the absolute path gets returned, so
461 * usage with relative paths here is completely invalid.
463 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
465 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
468 const char *base = NULL;
469 if (type == Path_Game)
471 base = GetGamePath();
473 else if (type == Path_SM)
475 base = GetSourceModPath();
477 else if (type == Path_SM_Rel)
484 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
488 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
492 void SourceModBase::CloseSourceMod()
494 if (!sSourceModInitialized)
497 SH_REMOVE_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(this, &SourceModBase::LevelInit), false);
501 /* Force a level end */
507 ShutdownLogicBridge();
511 void SourceModBase::ShutdownServices()
516 /* Unload extensions */
520 g_Forwards.ReleaseForward(g_pOnMapEnd);
523 SMGlobalClass *pBase = SMGlobalClass::head;
526 pBase->OnSourceModShutdown();
527 pBase = pBase->m_pGlobalClassNext;
530 /* Delete all data packs */
531 CStack<CDataPack *>::iterator iter;
533 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
538 m_freepacks.popall();
541 pBase = SMGlobalClass::head;
544 pBase->OnSourceModAllShutdown();
545 pBase = pBase->m_pGlobalClassNext;
550 SH_RELEASE_CALLCLASS(enginePatch);
556 SH_RELEASE_CALLCLASS(gamedllPatch);
560 SH_REMOVE_HOOK(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false);
561 SH_REMOVE_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false);
564 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
566 IExtensionInterface *pAPI = pExt->GetAPI();
567 const char *tag = pAPI->GetExtensionTag();
571 va_start(ap, format);
572 vsnprintf(buffer, sizeof(buffer), format, ap);
577 g_Logger.LogMessage("[%s] %s", tag, buffer);
579 g_Logger.LogMessage("%s", buffer);
583 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
585 IExtensionInterface *pAPI = pExt->GetAPI();
586 const char *tag = pAPI->GetExtensionTag();
590 va_start(ap, format);
591 vsnprintf(buffer, sizeof(buffer), format, ap);
596 g_Logger.LogError("[%s] %s", tag, buffer);
598 g_Logger.LogError("%s", buffer);
602 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
606 pContext->LocalToString(params[param], &fmt);
608 int lparam = ++param;
610 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
613 const char *SourceModBase::GetSourceModPath() const
618 const char *SourceModBase::GetGamePath() const
620 return g_BaseDir.c_str();
623 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
625 unsigned int old = m_target;
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()
682 SMGlobalClass *base = SMGlobalClass::head;
685 base->OnSourceModGameInitialized();
686 base = base->m_pGlobalClassNext;
690 time_t SourceModBase::GetAdjustedTime()
692 return ::GetAdjustedTime();
695 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
697 m_frame_hooks.push_back(hook);
700 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
702 for (size_t i = 0; i < m_frame_hooks.size(); i++)
704 if (m_frame_hooks[i] == hook)
706 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
712 void SourceModBase::ProcessGameFrameHooks(bool simulating)
714 if (m_frame_hooks.size() == 0)
719 for (size_t i = 0; i < m_frame_hooks.size(); i++)
721 m_frame_hooks[i](simulating);
725 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
731 len = FormatArgs(buffer, maxlength, fmt, ap);
737 size_t SourceModBase::FormatArgs(char *buffer,
742 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
745 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
747 ::AddFrameAction(FrameAction(fn, data));
750 const char *SourceModBase::GetCoreConfigValue(const char *key)
752 return g_CoreConfig.GetCoreConfigValue(key);
755 int SourceModBase::GetPluginId()
760 int SourceModBase::GetShApiVersion()
763 g_SMAPI->GetShVersions(api, impl);
768 bool SourceModBase::IsMapRunning()
770 return g_OnMapStarted;
773 SMGlobalClass *SMGlobalClass::head = NULL;