Why was this not const? I have no idea, but what a lame commit for me to make after all this time
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 IExtension *g_pGameExt = NULL;
76 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
77 typedef int (*GIVEENGINEPOINTER2)(ISourcePawnEngine *, unsigned int api_version);
78 typedef unsigned int (*GETEXPORTCOUNT)();
79 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
80 typedef void (*NOTIFYSHUTDOWN)();
84 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
90 g_pJIT->CloseLibrary();
93 SourceModBase::SourceModBase()
95 m_IsMapLoading = false;
96 m_ExecPluginReload = false;
97 m_ExecOnMapEnd = 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;
126 return ConfigResult_Ignore;
129 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
131 const char *gamepath = g_SMAPI->GetBaseDir();
133 /* Store full path to game */
134 g_BaseDir.assign(gamepath);
136 /* Store name of game directory by itself */
137 size_t len = strlen(gamepath);
138 for (size_t i = len - 1; i >= 0; i--)
140 if (gamepath[i] == PLATFORM_SEP_CHAR)
142 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
147 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
148 g_CoreConfig.Initialize();
150 /* This shouldn't happen, but can't hurt to be safe */
151 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
153 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
154 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
155 m_GotBasePath = true;
158 /* Attempt to load the JIT! */
159 char file[PLATFORM_MAX_PATH];
161 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
166 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
169 if (error && maxlength)
171 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
180 GIVEENGINEPOINTER2 jit_init2 = (GIVEENGINEPOINTER2)g_pJIT->GetSymbolAddress("GiveEnginePointer2");
183 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
187 if (error && maxlength)
189 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
194 if ((err=jit_init(g_pSourcePawn)) != 0)
197 if (error && maxlength)
199 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
204 /* On version bumps, we should check for older versions as well, if the new version fails.
205 * We can then check the exports to see if any VM versions will be sufficient.
207 if ((err=jit_init2(g_pSourcePawn, SOURCEPAWN_ENGINE_API_VERSION)) != SP_ERROR_NONE)
210 if (error && maxlength)
212 snprintf(error, maxlength, "JIT incompatible with SourceMod version");
218 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
219 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
223 if (error && maxlength)
225 snprintf(error, maxlength, "JIT is missing a necessary export!");
230 unsigned int num = jit_getnum();
234 if (error && maxlength)
236 snprintf(error, maxlength, "JIT did not export any virtual machines!");
241 unsigned int api_version;
242 for (unsigned int i=0; i<num; i++)
244 if ((g_pVM=jit_get(i)) == NULL)
246 if (error && maxlength)
248 snprintf(error, maxlength, "JIT did not export any virtual machines!");
252 /* Refuse any API that we might not be able to deal with.
253 * Also refuse anything < 3 because we need fake natives.
255 api_version = g_pVM->GetAPIVersion();
256 if (api_version < 3 || api_version > SOURCEPAWN_VM_API_VERSION)
258 if (error && maxlength)
260 snprintf(error, maxlength, "JIT is not a compatible version");
274 /* Hook this now so we can detect startup without calling StartSourceMod() */
275 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
277 /* Only load if we're not late */
280 StartSourceMod(false);
286 void SourceModBase::StartSourceMod(bool late)
288 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
289 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
291 enginePatch = SH_GET_CALLCLASS(engine);
292 gamedllPatch = SH_GET_CALLCLASS(gamedll);
295 SMGlobalClass *pBase = SMGlobalClass::head;
298 pBase->OnSourceModStartup(false);
299 pBase = pBase->m_pGlobalClassNext;
302 /* Make the global core identity */
303 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
306 pBase = SMGlobalClass::head;
309 pBase->OnSourceModAllInitialized();
310 pBase = pBase->m_pGlobalClassNext;
314 g_ShareSys.AddInterface(NULL, this);
320 static bool g_LevelEndBarrier = false;
321 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
323 /* If we're not loaded... */
326 /* Do all global initialization now */
327 StartSourceMod(true);
330 m_IsMapLoading = true;
331 m_ExecPluginReload = true;
332 m_ExecOnMapEnd = true;
334 g_LastMenuTime = 0.0f;
335 g_LastAuthCheck = 0.0f;
338 SMGlobalClass *pBase = SMGlobalClass::head;
341 pBase->OnSourceModLevelChange(pMapName);
342 pBase = pBase->m_pGlobalClassNext;
345 DoGlobalPluginLoads();
347 m_IsMapLoading = false;
350 pBase = SMGlobalClass::head;
353 pBase->OnSourceModPluginsLoaded();
354 pBase = pBase->m_pGlobalClassNext;
359 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
364 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
367 g_LevelEndBarrier = true;
369 RETURN_META_VALUE(MRES_IGNORED, true);
372 void SourceModBase::GameFrame(bool simulating)
375 g_HL2.ProcessFakeCliCmdQueue();
378 * Note: This is all hardcoded rather than delegated to save
379 * precious CPU cycles.
381 float curtime = engine->Time();
383 if (curtime - g_LastTime >= 0.1f)
386 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
388 g_LastAuthCheck = gpGlobals->curtime;
389 g_Players.RunAuthChecks();
393 g_LastTime = curtime;
396 if (gpGlobals->curtime - g_LastMenuTime >= 1.0f)
398 g_ValveMenuStyle.ProcessWatchList();
399 g_RadioMenuStyle.ProcessWatchList();
400 g_LastMenuTime = curtime;
403 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
405 g_pOnGameFrame->Execute(NULL);
409 void SourceModBase::LevelShutdown()
411 if (g_LevelEndBarrier)
413 SMGlobalClass *next = SMGlobalClass::head;
416 next->OnSourceModLevelEnd();
417 next = next->m_pGlobalClassNext;
419 g_LevelEndBarrier = false;
422 if (g_pOnMapEnd && m_ExecOnMapEnd)
424 g_pOnMapEnd->Execute(NULL);
425 m_ExecOnMapEnd = false;
428 g_OnMapStarted = false;
430 if (m_ExecPluginReload)
432 g_PluginSys.ReloadOrUnloadPlugins();
433 m_ExecPluginReload = false;
437 bool SourceModBase::IsMapLoading() const
439 return m_IsMapLoading;
442 void SourceModBase::DoGlobalPluginLoads()
444 char config_path[PLATFORM_MAX_PATH];
445 char plugins_path[PLATFORM_MAX_PATH];
447 BuildPath(Path_SM, config_path,
449 "configs/plugin_settings.cfg");
450 BuildPath(Path_SM, plugins_path,
451 sizeof(plugins_path),
454 /* Load any auto extensions */
455 g_Extensions.TryAutoload();
457 /* Load any game extension */
458 const char *game_ext;
459 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
461 char path[PLATFORM_MAX_PATH];
462 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
463 g_pGameExt = g_Extensions.LoadAutoExtension(path);
466 /* Run the first pass */
467 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
469 /* Mark any extensions as loaded */
470 g_Extensions.MarkAllLoaded();
472 /* No modules yet, it's safe to call this from here */
473 g_PluginSys.LoadAll_SecondPass();
475 /* Re-mark any extensions as loaded */
476 g_Extensions.MarkAllLoaded();
478 /* Call OnAllPluginsLoaded */
479 g_PluginSys.AllPluginsLoaded();
482 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
484 char _buffer[PLATFORM_MAX_PATH];
487 va_start(ap, format);
488 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
491 const char *base = NULL;
492 if (type == Path_Game)
494 base = GetGamePath();
495 } else if (type == Path_SM) {
496 base = GetSourceModPath();
497 } else if (type == Path_SM_Rel) {
503 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
505 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
509 void SourceModBase::CloseSourceMod()
511 /* Force a level end */
515 g_PluginSys.Shutdown();
517 /* Unload extensions */
518 g_Extensions.Shutdown();
520 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
526 g_Forwards.ReleaseForward(g_pOnGameFrame);
531 g_Forwards.ReleaseForward(g_pOnMapEnd);
535 SMGlobalClass *pBase = SMGlobalClass::head;
538 pBase->OnSourceModShutdown();
539 pBase = pBase->m_pGlobalClassNext;
542 /* Delete all data packs */
543 CStack<CDataPack *>::iterator iter;
545 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
550 m_freepacks.popall();
553 pBase = SMGlobalClass::head;
556 pBase->OnSourceModAllShutdown();
557 pBase = pBase->m_pGlobalClassNext;
562 SH_RELEASE_CALLCLASS(enginePatch);
568 SH_RELEASE_CALLCLASS(gamedllPatch);
572 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
573 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
580 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
582 IExtensionInterface *pAPI = pExt->GetAPI();
583 const char *tag = pAPI->GetExtensionTag();
587 va_start(ap, format);
588 vsnprintf(buffer, sizeof(buffer), format, ap);
593 g_Logger.LogMessage("[%s] %s", tag, buffer);
595 g_Logger.LogMessage("%s", buffer);
599 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
601 IExtensionInterface *pAPI = pExt->GetAPI();
602 const char *tag = pAPI->GetExtensionTag();
606 va_start(ap, format);
607 vsnprintf(buffer, sizeof(buffer), format, ap);
612 g_Logger.LogError("[%s] %s", tag, buffer);
614 g_Logger.LogError("%s", buffer);
618 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
622 pContext->LocalToString(params[param], &fmt);
624 int lparam = ++param;
626 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
629 const char *SourceModBase::GetSourceModPath() const
634 const char *SourceModBase::GetGamePath() const
636 return g_BaseDir.c_str();
639 void SourceModBase::SetGlobalTarget(unsigned int index)
644 void SourceModBase::SetAuthChecking(bool set)
646 m_CheckingAuth = set;
649 unsigned int SourceModBase::GetGlobalTarget() const
654 IDataPack *SourceModBase::CreateDataPack()
657 if (m_freepacks.empty())
659 pack = new CDataPack;
661 pack = m_freepacks.front();
668 void SourceModBase::FreeDataPack(IDataPack *pack)
670 m_freepacks.push(static_cast<CDataPack *>(pack));
673 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
679 const char *SourceModBase::GetGameFolderName() const
684 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
686 return g_pSourcePawn;
689 IVirtualMachine *SourceModBase::GetScriptingVM()
694 void SourceModBase::AllPluginsLoaded()
696 SMGlobalClass *base = SMGlobalClass::head;
699 base->OnSourceModGameInitialized();
700 base = base->m_pGlobalClassNext;
704 time_t SourceModBase::GetAdjustedTime()
706 return GetAdjustedTime();
709 SMGlobalClass *SMGlobalClass::head = NULL;
711 SMGlobalClass::SMGlobalClass()
713 m_pGlobalClassNext = SMGlobalClass::head;
714 SMGlobalClass::head = this;