3 * =============================================================================
5 * Copyright (C) 2004-2008 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 "Translator.h"
46 #include "ForwardSys.h"
48 #include "GameConfigs.h"
49 #include "DebugReporter.h"
51 #include "frame_hooks.h"
53 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
54 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
55 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
56 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
58 SourceModBase g_SourceMod;
60 ILibrary *g_pJIT = NULL;
61 SourceHook::String g_BaseDir;
62 ISourcePawnEngine *g_pSourcePawn = NULL;
63 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
64 IdentityToken_t *g_pCoreIdent = NULL;
65 IForward *g_pOnMapEnd = NULL;
66 bool g_Loaded = false;
67 bool sm_show_debug_spew = false;
69 typedef ISourcePawnEngine *(*GET_SP_V1)();
70 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
71 typedef void (*NOTIFYSHUTDOWN)();
73 #ifdef PLATFORM_WINDOWS
74 ConVar sm_basepath("sm_basepath", "addons\\sourcemod", 0, "SourceMod base path (set via command line)");
75 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
76 ConVar sm_basepath("sm_basepath", "addons/sourcemod", 0, "SourceMod base path (set via command line)");
81 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
87 if (g_pSourcePawn2 != NULL)
89 g_pSourcePawn2->Shutdown();
92 g_pJIT->CloseLibrary();
95 SourceModBase::SourceModBase()
97 m_IsMapLoading = false;
98 m_ExecPluginReload = false;
99 m_GotBasePath = false;
102 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
108 if (strcasecmp(key, "BasePath") == 0)
110 if (source == ConfigSource_Console)
112 UTIL_Format(error, maxlength, "Cannot be set at runtime");
113 return ConfigResult_Reject;
118 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
119 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
121 m_GotBasePath = true;
124 return ConfigResult_Accept;
126 else if (strcasecmp(key, "DebugSpew") == 0)
128 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
130 return ConfigResult_Accept;
133 return ConfigResult_Ignore;
136 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
138 const char *gamepath = g_SMAPI->GetBaseDir();
140 /* Store full path to game */
141 g_BaseDir.assign(gamepath);
143 /* Store name of game directory by itself */
144 size_t len = strlen(gamepath);
145 for (size_t i = len - 1; i >= 0; i--)
147 if (gamepath[i] == PLATFORM_SEP_CHAR)
149 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
154 const char *basepath = icvar->GetCommandLineValue("sm_basepath");
155 /* Set a custom base path if there is one. */
156 if (basepath != NULL && basepath[0] != '\0')
158 m_GotBasePath = true;
160 /* Otherwise, use a default and keep the m_GotBasePath unlocked. */
163 basepath = sm_basepath.GetDefault();
166 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), basepath);
167 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "%s", basepath);
169 /* Initialize CoreConfig to get the SourceMod base path properly - this parses core.cfg */
170 g_CoreConfig.Initialize();
172 /* There will always be a path by this point, since it was force-set above. */
173 m_GotBasePath = true;
175 /* Attempt to load the JIT! */
176 char file[PLATFORM_MAX_PATH];
178 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
183 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
186 if (error && maxlength)
188 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
195 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
196 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
200 if (error && maxlength)
202 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
207 else if (getv2 == NULL)
209 if (error && maxlength)
211 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
217 g_pSourcePawn = getv1();
218 g_pSourcePawn2 = getv2();
220 if (g_pSourcePawn2->GetAPIVersion() < 3)
222 g_pSourcePawn2 = NULL;
223 if (error && maxlength)
225 snprintf(error, maxlength, "JIT version is out of date");
230 if (!g_pSourcePawn2->Initialize())
232 g_pSourcePawn2 = NULL;
233 if (error && maxlength)
235 snprintf(error, maxlength, "JIT could not be initialized");
240 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
241 g_pSourcePawn2->SetProfiler(&g_Profiler);
243 /* Hook this now so we can detect startup without calling StartSourceMod() */
244 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
246 /* Only load if we're not late */
249 StartSourceMod(false);
255 void SourceModBase::StartSourceMod(bool late)
257 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
258 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
260 enginePatch = SH_GET_CALLCLASS(engine);
261 gamedllPatch = SH_GET_CALLCLASS(gamedll);
263 g_ShareSys.Initialize();
265 /* Make the global core identity */
266 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
269 SMGlobalClass *pBase = SMGlobalClass::head;
272 pBase->OnSourceModStartup(false);
273 pBase = pBase->m_pGlobalClassNext;
277 pBase = SMGlobalClass::head;
280 pBase->OnSourceModAllInitialized();
281 pBase = pBase->m_pGlobalClassNext;
285 pBase = SMGlobalClass::head;
288 pBase->OnSourceModAllInitialized_Post();
289 pBase = pBase->m_pGlobalClassNext;
293 g_ShareSys.AddInterface(NULL, this);
298 /* Initialize VSP stuff */
299 if (vsp_interface != NULL)
301 g_SourceMod_Core.OnVSPListening(vsp_interface);
304 /* If we want to autoload, do that now */
305 const char *disabled = GetCoreConfigValue("DisableAutoUpdate");
306 if (disabled == NULL || strcasecmp(disabled, "yes") != 0)
308 g_Extensions.LoadAutoExtension("updater.ext." PLATFORM_LIB_EXT);
312 static bool g_LevelEndBarrier = false;
313 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
315 /* If we're not loaded... */
318 /* Do all global initialization now */
319 StartSourceMod(true);
322 m_IsMapLoading = true;
323 m_ExecPluginReload = true;
326 SMGlobalClass *pBase = SMGlobalClass::head;
329 pBase->OnSourceModLevelChange(pMapName);
330 pBase = pBase->m_pGlobalClassNext;
333 DoGlobalPluginLoads();
335 m_IsMapLoading = false;
338 pBase = SMGlobalClass::head;
341 pBase->OnSourceModPluginsLoaded();
342 pBase = pBase->m_pGlobalClassNext;
347 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
350 g_LevelEndBarrier = true;
352 RETURN_META_VALUE(MRES_IGNORED, true);
355 void SourceModBase::LevelShutdown()
357 if (g_LevelEndBarrier)
359 SMGlobalClass *next = SMGlobalClass::head;
362 next->OnSourceModLevelEnd();
363 next = next->m_pGlobalClassNext;
366 if (g_pOnMapEnd != NULL)
368 g_pOnMapEnd->Execute(NULL);
371 g_Timers.RemoveMapChangeTimers();
373 g_LevelEndBarrier = false;
376 g_OnMapStarted = false;
378 if (m_ExecPluginReload)
380 g_PluginSys.ReloadOrUnloadPlugins();
381 m_ExecPluginReload = false;
385 bool SourceModBase::IsMapLoading() const
387 return m_IsMapLoading;
390 void SourceModBase::DoGlobalPluginLoads()
392 char config_path[PLATFORM_MAX_PATH];
393 char plugins_path[PLATFORM_MAX_PATH];
395 BuildPath(Path_SM, config_path,
397 "configs/plugin_settings.cfg");
398 BuildPath(Path_SM, plugins_path,
399 sizeof(plugins_path),
402 /* Load any auto extensions */
403 g_Extensions.TryAutoload();
405 /* Fire the extensions ready message */
406 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
408 /* Load any game extension */
409 const char *game_ext;
410 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
412 char path[PLATFORM_MAX_PATH];
413 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
414 g_Extensions.LoadAutoExtension(path);
417 /* Run the first pass */
418 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
420 /* Mark any extensions as loaded */
421 g_Extensions.MarkAllLoaded();
423 /* No modules yet, it's safe to call this from here */
424 g_PluginSys.LoadAll_SecondPass();
426 /* Re-mark any extensions as loaded */
427 g_Extensions.MarkAllLoaded();
429 /* Call OnAllPluginsLoaded */
430 g_PluginSys.AllPluginsLoaded();
433 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
435 char _buffer[PLATFORM_MAX_PATH];
438 va_start(ap, format);
439 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
442 /* If we get a "file://" notation, strip off the file:// part so we're left
443 * with an absolute path. Note that the absolute path gets returned, so
444 * usage with relative paths here is completely invalid.
446 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
448 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
451 const char *base = NULL;
452 if (type == Path_Game)
454 base = GetGamePath();
456 else if (type == Path_SM)
458 base = GetSourceModPath();
460 else if (type == Path_SM_Rel)
467 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
471 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
475 void SourceModBase::CloseSourceMod()
477 /* Force a level end */
481 g_PluginSys.Shutdown();
483 /* Unload extensions */
484 g_Extensions.Shutdown();
486 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
492 g_Forwards.ReleaseForward(g_pOnMapEnd);
496 SMGlobalClass *pBase = SMGlobalClass::head;
499 pBase->OnSourceModShutdown();
500 pBase = pBase->m_pGlobalClassNext;
503 /* Delete all data packs */
504 CStack<CDataPack *>::iterator iter;
506 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
511 m_freepacks.popall();
514 pBase = SMGlobalClass::head;
517 pBase->OnSourceModAllShutdown();
518 pBase = pBase->m_pGlobalClassNext;
523 SH_RELEASE_CALLCLASS(enginePatch);
529 SH_RELEASE_CALLCLASS(gamedllPatch);
533 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
534 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
541 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
543 IExtensionInterface *pAPI = pExt->GetAPI();
544 const char *tag = pAPI->GetExtensionTag();
548 va_start(ap, format);
549 vsnprintf(buffer, sizeof(buffer), format, ap);
554 g_Logger.LogMessage("[%s] %s", tag, buffer);
556 g_Logger.LogMessage("%s", buffer);
560 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
562 IExtensionInterface *pAPI = pExt->GetAPI();
563 const char *tag = pAPI->GetExtensionTag();
567 va_start(ap, format);
568 vsnprintf(buffer, sizeof(buffer), format, ap);
573 g_Logger.LogError("[%s] %s", tag, buffer);
575 g_Logger.LogError("%s", buffer);
579 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
583 pContext->LocalToString(params[param], &fmt);
585 int lparam = ++param;
587 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
590 const char *SourceModBase::GetSourceModPath() const
595 const char *SourceModBase::GetGamePath() const
597 return g_BaseDir.c_str();
600 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
602 unsigned int old = m_target;
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 void SourceModBase::AllPluginsLoaded()
654 SMGlobalClass *base = SMGlobalClass::head;
657 base->OnSourceModGameInitialized();
658 base = base->m_pGlobalClassNext;
662 time_t SourceModBase::GetAdjustedTime()
664 return ::GetAdjustedTime();
667 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
669 m_frame_hooks.push_back(hook);
672 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
674 for (size_t i = 0; i < m_frame_hooks.size(); i++)
676 if (m_frame_hooks[i] == hook)
678 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
684 void SourceModBase::ProcessGameFrameHooks(bool simulating)
686 if (m_frame_hooks.size() == 0)
691 for (size_t i = 0; i < m_frame_hooks.size(); i++)
693 m_frame_hooks[i](simulating);
697 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
703 len = FormatArgs(buffer, maxlength, fmt, ap);
709 size_t SourceModBase::FormatArgs(char *buffer,
714 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
717 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
719 ::AddFrameAction(FrameAction(fn, data));
722 const char *SourceModBase::GetCoreConfigValue(const char *key)
724 return g_CoreConfig.GetCoreConfigValue(key);
727 int SourceModBase::GetPluginId()
732 SMGlobalClass *SMGlobalClass::head = NULL;
734 SMGlobalClass::SMGlobalClass()
736 m_pGlobalClassNext = SMGlobalClass::head;
737 SMGlobalClass::head = this;