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 "systems/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"
52 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
53 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
54 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
55 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
57 SourceModBase g_SourceMod;
59 ILibrary *g_pJIT = NULL;
60 SourceHook::String g_BaseDir;
61 ISourcePawnEngine *g_pSourcePawn = NULL;
62 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
63 IdentityToken_t *g_pCoreIdent = NULL;
64 IForward *g_pOnMapEnd = NULL;
65 bool g_Loaded = false;
67 typedef ISourcePawnEngine *(*GET_SP_V1)();
68 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
69 typedef void (*NOTIFYSHUTDOWN)();
73 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
79 if (g_pSourcePawn2 != NULL)
81 g_pSourcePawn2->Shutdown();
84 g_pJIT->CloseLibrary();
87 SourceModBase::SourceModBase()
89 m_IsMapLoading = false;
90 m_ExecPluginReload = false;
91 m_GotBasePath = false;
94 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
100 if (strcasecmp(key, "BasePath") == 0)
102 if (source == ConfigSource_Console)
104 UTIL_Format(error, maxlength, "Cannot be set at runtime");
105 return ConfigResult_Reject;
110 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
111 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
113 m_GotBasePath = true;
116 return ConfigResult_Accept;
119 return ConfigResult_Ignore;
122 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
124 const char *gamepath = g_SMAPI->GetBaseDir();
126 /* Store full path to game */
127 g_BaseDir.assign(gamepath);
129 /* Store name of game directory by itself */
130 size_t len = strlen(gamepath);
131 for (size_t i = len - 1; i >= 0; i--)
133 if (gamepath[i] == PLATFORM_SEP_CHAR)
135 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
140 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
141 g_CoreConfig.Initialize();
143 /* This shouldn't happen, but can't hurt to be safe */
144 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
146 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
147 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
148 m_GotBasePath = true;
151 /* Attempt to load the JIT! */
152 char file[PLATFORM_MAX_PATH];
154 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
159 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
162 if (error && maxlength)
164 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
171 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
172 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
176 if (error && maxlength)
178 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
183 else if (getv2 == NULL)
185 if (error && maxlength)
187 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
193 g_pSourcePawn = getv1();
194 g_pSourcePawn2 = getv2();
196 if (g_pSourcePawn2->GetAPIVersion() < 2)
198 g_pSourcePawn2 = NULL;
199 if (error && maxlength)
201 snprintf(error, maxlength, "JIT version is out of date");
206 if (!g_pSourcePawn2->Initialize())
208 g_pSourcePawn2 = NULL;
209 if (error && maxlength)
211 snprintf(error, maxlength, "JIT could not be initialized");
216 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
217 g_pSourcePawn2->SetProfiler(&g_Profiler);
219 /* Hook this now so we can detect startup without calling StartSourceMod() */
220 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
222 /* Only load if we're not late */
225 StartSourceMod(false);
231 void SourceModBase::StartSourceMod(bool late)
233 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
234 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
236 enginePatch = SH_GET_CALLCLASS(engine);
237 gamedllPatch = SH_GET_CALLCLASS(gamedll);
239 g_ShareSys.Initialize();
241 /* Make the global core identity */
242 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
245 SMGlobalClass *pBase = SMGlobalClass::head;
248 pBase->OnSourceModStartup(false);
249 pBase = pBase->m_pGlobalClassNext;
253 pBase = SMGlobalClass::head;
256 pBase->OnSourceModAllInitialized();
257 pBase = pBase->m_pGlobalClassNext;
261 pBase = SMGlobalClass::head;
264 pBase->OnSourceModAllInitialized_Post();
265 pBase = pBase->m_pGlobalClassNext;
269 g_ShareSys.AddInterface(NULL, this);
274 /* Initialize VSP stuff */
275 if (vsp_interface != NULL)
277 g_SourceMod_Core.OnVSPListening(vsp_interface);
281 static bool g_LevelEndBarrier = false;
282 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
284 /* If we're not loaded... */
287 /* Do all global initialization now */
288 StartSourceMod(true);
291 m_IsMapLoading = true;
292 m_ExecPluginReload = true;
295 SMGlobalClass *pBase = SMGlobalClass::head;
298 pBase->OnSourceModLevelChange(pMapName);
299 pBase = pBase->m_pGlobalClassNext;
302 DoGlobalPluginLoads();
304 m_IsMapLoading = false;
307 pBase = SMGlobalClass::head;
310 pBase->OnSourceModPluginsLoaded();
311 pBase = pBase->m_pGlobalClassNext;
316 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
319 g_LevelEndBarrier = true;
321 RETURN_META_VALUE(MRES_IGNORED, true);
324 void SourceModBase::LevelShutdown()
326 if (g_LevelEndBarrier)
328 SMGlobalClass *next = SMGlobalClass::head;
331 next->OnSourceModLevelEnd();
332 next = next->m_pGlobalClassNext;
335 if (g_pOnMapEnd != NULL)
337 g_pOnMapEnd->Execute(NULL);
340 g_Timers.RemoveMapChangeTimers();
342 g_LevelEndBarrier = false;
345 g_OnMapStarted = false;
347 if (m_ExecPluginReload)
349 g_PluginSys.ReloadOrUnloadPlugins();
350 m_ExecPluginReload = false;
354 bool SourceModBase::IsMapLoading() const
356 return m_IsMapLoading;
359 void SourceModBase::DoGlobalPluginLoads()
361 char config_path[PLATFORM_MAX_PATH];
362 char plugins_path[PLATFORM_MAX_PATH];
364 BuildPath(Path_SM, config_path,
366 "configs/plugin_settings.cfg");
367 BuildPath(Path_SM, plugins_path,
368 sizeof(plugins_path),
371 /* Load any auto extensions */
372 g_Extensions.TryAutoload();
374 /* Fire the extensions ready message */
375 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
377 /* Load any game extension */
378 const char *game_ext;
379 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
381 char path[PLATFORM_MAX_PATH];
382 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
383 g_Extensions.LoadAutoExtension(path);
386 /* Run the first pass */
387 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
389 /* Mark any extensions as loaded */
390 g_Extensions.MarkAllLoaded();
392 /* No modules yet, it's safe to call this from here */
393 g_PluginSys.LoadAll_SecondPass();
395 /* Re-mark any extensions as loaded */
396 g_Extensions.MarkAllLoaded();
398 /* Call OnAllPluginsLoaded */
399 g_PluginSys.AllPluginsLoaded();
402 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
404 char _buffer[PLATFORM_MAX_PATH];
407 va_start(ap, format);
408 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
411 /* If we get a "file://" notation, strip off the file:// part so we're left
412 * with an absolute path. Note that the absolute path gets returned, so
413 * usage with relative paths here is completely invalid.
415 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
417 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
420 const char *base = NULL;
421 if (type == Path_Game)
423 base = GetGamePath();
425 else if (type == Path_SM)
427 base = GetSourceModPath();
429 else if (type == Path_SM_Rel)
436 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
440 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
444 void SourceModBase::CloseSourceMod()
446 /* Force a level end */
450 g_PluginSys.Shutdown();
452 /* Unload extensions */
453 g_Extensions.Shutdown();
455 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
461 g_Forwards.ReleaseForward(g_pOnMapEnd);
465 SMGlobalClass *pBase = SMGlobalClass::head;
468 pBase->OnSourceModShutdown();
469 pBase = pBase->m_pGlobalClassNext;
472 /* Delete all data packs */
473 CStack<CDataPack *>::iterator iter;
475 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
480 m_freepacks.popall();
483 pBase = SMGlobalClass::head;
486 pBase->OnSourceModAllShutdown();
487 pBase = pBase->m_pGlobalClassNext;
492 SH_RELEASE_CALLCLASS(enginePatch);
498 SH_RELEASE_CALLCLASS(gamedllPatch);
502 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
503 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
510 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
512 IExtensionInterface *pAPI = pExt->GetAPI();
513 const char *tag = pAPI->GetExtensionTag();
517 va_start(ap, format);
518 vsnprintf(buffer, sizeof(buffer), format, ap);
523 g_Logger.LogMessage("[%s] %s", tag, buffer);
525 g_Logger.LogMessage("%s", buffer);
529 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
531 IExtensionInterface *pAPI = pExt->GetAPI();
532 const char *tag = pAPI->GetExtensionTag();
536 va_start(ap, format);
537 vsnprintf(buffer, sizeof(buffer), format, ap);
542 g_Logger.LogError("[%s] %s", tag, buffer);
544 g_Logger.LogError("%s", buffer);
548 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
552 pContext->LocalToString(params[param], &fmt);
554 int lparam = ++param;
556 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
559 const char *SourceModBase::GetSourceModPath() const
564 const char *SourceModBase::GetGamePath() const
566 return g_BaseDir.c_str();
569 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
571 unsigned int old = m_target;
576 unsigned int SourceModBase::GetGlobalTarget() const
581 IDataPack *SourceModBase::CreateDataPack()
584 if (m_freepacks.empty())
586 pack = new CDataPack;
588 pack = m_freepacks.front();
595 void SourceModBase::FreeDataPack(IDataPack *pack)
597 m_freepacks.push(static_cast<CDataPack *>(pack));
600 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
606 const char *SourceModBase::GetGameFolderName() const
611 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
613 return g_pSourcePawn;
616 IVirtualMachine *SourceModBase::GetScriptingVM()
621 void SourceModBase::AllPluginsLoaded()
623 SMGlobalClass *base = SMGlobalClass::head;
626 base->OnSourceModGameInitialized();
627 base = base->m_pGlobalClassNext;
631 time_t SourceModBase::GetAdjustedTime()
633 return ::GetAdjustedTime();
636 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
638 m_frame_hooks.push_back(hook);
641 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
643 for (size_t i = 0; i < m_frame_hooks.size(); i++)
645 if (m_frame_hooks[i] == hook)
647 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
653 void SourceModBase::ProcessGameFrameHooks(bool simulating)
655 if (m_frame_hooks.size() == 0)
660 for (size_t i = 0; i < m_frame_hooks.size(); i++)
662 m_frame_hooks[i](simulating);
666 SMGlobalClass *SMGlobalClass::head = NULL;
668 SMGlobalClass::SMGlobalClass()
670 m_pGlobalClassNext = SMGlobalClass::head;
671 SMGlobalClass::head = this;