Initial Import of beta structs extension.
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 g_pJIT->CloseLibrary();
82 SourceModBase::SourceModBase()
84 m_IsMapLoading = false;
85 m_ExecPluginReload = false;
86 m_GotBasePath = false;
89 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
95 if (strcasecmp(key, "BasePath") == 0)
97 if (source == ConfigSource_Console)
99 UTIL_Format(error, maxlength, "Cannot be set at runtime");
100 return ConfigResult_Reject;
105 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
106 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
108 m_GotBasePath = true;
111 return ConfigResult_Accept;
114 return ConfigResult_Ignore;
117 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
119 const char *gamepath = g_SMAPI->GetBaseDir();
121 /* Store full path to game */
122 g_BaseDir.assign(gamepath);
124 /* Store name of game directory by itself */
125 size_t len = strlen(gamepath);
126 for (size_t i = len - 1; i >= 0; i--)
128 if (gamepath[i] == PLATFORM_SEP_CHAR)
130 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
135 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
136 g_CoreConfig.Initialize();
138 /* This shouldn't happen, but can't hurt to be safe */
139 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
141 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
142 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
143 m_GotBasePath = true;
146 /* Attempt to load the JIT! */
147 char file[PLATFORM_MAX_PATH];
149 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
154 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
157 if (error && maxlength)
159 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
166 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
167 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
171 if (error && maxlength)
173 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
178 else if (getv2 == NULL)
180 if (error && maxlength)
182 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
188 g_pSourcePawn = getv1();
189 g_pSourcePawn2 = getv2();
191 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
192 g_pSourcePawn2->SetProfiler(&g_Profiler);
194 /* Hook this now so we can detect startup without calling StartSourceMod() */
195 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
197 /* Only load if we're not late */
200 StartSourceMod(false);
206 void SourceModBase::StartSourceMod(bool late)
208 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
209 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
211 enginePatch = SH_GET_CALLCLASS(engine);
212 gamedllPatch = SH_GET_CALLCLASS(gamedll);
214 g_ShareSys.Initialize();
216 /* Make the global core identity */
217 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
220 SMGlobalClass *pBase = SMGlobalClass::head;
223 pBase->OnSourceModStartup(false);
224 pBase = pBase->m_pGlobalClassNext;
228 pBase = SMGlobalClass::head;
231 pBase->OnSourceModAllInitialized();
232 pBase = pBase->m_pGlobalClassNext;
236 pBase = SMGlobalClass::head;
239 pBase->OnSourceModAllInitialized_Post();
240 pBase = pBase->m_pGlobalClassNext;
244 g_ShareSys.AddInterface(NULL, this);
249 /* Initialize VSP stuff */
250 if (vsp_interface != NULL)
252 g_SourceMod_Core.OnVSPListening(vsp_interface);
256 static bool g_LevelEndBarrier = false;
257 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
259 /* If we're not loaded... */
262 /* Do all global initialization now */
263 StartSourceMod(true);
266 m_IsMapLoading = true;
267 m_ExecPluginReload = true;
270 SMGlobalClass *pBase = SMGlobalClass::head;
273 pBase->OnSourceModLevelChange(pMapName);
274 pBase = pBase->m_pGlobalClassNext;
277 DoGlobalPluginLoads();
279 m_IsMapLoading = false;
282 pBase = SMGlobalClass::head;
285 pBase->OnSourceModPluginsLoaded();
286 pBase = pBase->m_pGlobalClassNext;
291 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
294 g_LevelEndBarrier = true;
296 RETURN_META_VALUE(MRES_IGNORED, true);
299 void SourceModBase::LevelShutdown()
301 if (g_LevelEndBarrier)
303 SMGlobalClass *next = SMGlobalClass::head;
306 next->OnSourceModLevelEnd();
307 next = next->m_pGlobalClassNext;
310 if (g_pOnMapEnd != NULL)
312 g_pOnMapEnd->Execute(NULL);
315 g_Timers.RemoveMapChangeTimers();
317 g_LevelEndBarrier = false;
320 g_OnMapStarted = false;
322 if (m_ExecPluginReload)
324 g_PluginSys.ReloadOrUnloadPlugins();
325 m_ExecPluginReload = false;
329 bool SourceModBase::IsMapLoading() const
331 return m_IsMapLoading;
334 void SourceModBase::DoGlobalPluginLoads()
336 char config_path[PLATFORM_MAX_PATH];
337 char plugins_path[PLATFORM_MAX_PATH];
339 BuildPath(Path_SM, config_path,
341 "configs/plugin_settings.cfg");
342 BuildPath(Path_SM, plugins_path,
343 sizeof(plugins_path),
346 /* Load any auto extensions */
347 g_Extensions.TryAutoload();
349 /* Fire the extensions ready message */
350 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
352 /* Load any game extension */
353 const char *game_ext;
354 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
356 char path[PLATFORM_MAX_PATH];
357 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
358 g_Extensions.LoadAutoExtension(path);
361 /* Run the first pass */
362 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
364 /* Mark any extensions as loaded */
365 g_Extensions.MarkAllLoaded();
367 /* No modules yet, it's safe to call this from here */
368 g_PluginSys.LoadAll_SecondPass();
370 /* Re-mark any extensions as loaded */
371 g_Extensions.MarkAllLoaded();
373 /* Call OnAllPluginsLoaded */
374 g_PluginSys.AllPluginsLoaded();
377 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
379 char _buffer[PLATFORM_MAX_PATH];
382 va_start(ap, format);
383 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
386 /* If we get a "file://" notation, strip off the file:// part so we're left
387 * with an absolute path. Note that the absolute path gets returned, so
388 * usage with relative paths here is completely invalid.
390 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
392 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
395 const char *base = NULL;
396 if (type == Path_Game)
398 base = GetGamePath();
400 else if (type == Path_SM)
402 base = GetSourceModPath();
404 else if (type == Path_SM_Rel)
411 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
415 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
419 void SourceModBase::CloseSourceMod()
421 /* Force a level end */
425 g_PluginSys.Shutdown();
427 /* Unload extensions */
428 g_Extensions.Shutdown();
430 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
436 g_Forwards.ReleaseForward(g_pOnMapEnd);
440 SMGlobalClass *pBase = SMGlobalClass::head;
443 pBase->OnSourceModShutdown();
444 pBase = pBase->m_pGlobalClassNext;
447 /* Delete all data packs */
448 CStack<CDataPack *>::iterator iter;
450 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
455 m_freepacks.popall();
458 pBase = SMGlobalClass::head;
461 pBase->OnSourceModAllShutdown();
462 pBase = pBase->m_pGlobalClassNext;
467 SH_RELEASE_CALLCLASS(enginePatch);
473 SH_RELEASE_CALLCLASS(gamedllPatch);
477 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
478 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
485 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
487 IExtensionInterface *pAPI = pExt->GetAPI();
488 const char *tag = pAPI->GetExtensionTag();
492 va_start(ap, format);
493 vsnprintf(buffer, sizeof(buffer), format, ap);
498 g_Logger.LogMessage("[%s] %s", tag, buffer);
500 g_Logger.LogMessage("%s", buffer);
504 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
506 IExtensionInterface *pAPI = pExt->GetAPI();
507 const char *tag = pAPI->GetExtensionTag();
511 va_start(ap, format);
512 vsnprintf(buffer, sizeof(buffer), format, ap);
517 g_Logger.LogError("[%s] %s", tag, buffer);
519 g_Logger.LogError("%s", buffer);
523 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
527 pContext->LocalToString(params[param], &fmt);
529 int lparam = ++param;
531 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
534 const char *SourceModBase::GetSourceModPath() const
539 const char *SourceModBase::GetGamePath() const
541 return g_BaseDir.c_str();
544 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
546 unsigned int old = m_target;
551 unsigned int SourceModBase::GetGlobalTarget() const
556 IDataPack *SourceModBase::CreateDataPack()
559 if (m_freepacks.empty())
561 pack = new CDataPack;
563 pack = m_freepacks.front();
570 void SourceModBase::FreeDataPack(IDataPack *pack)
572 m_freepacks.push(static_cast<CDataPack *>(pack));
575 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
581 const char *SourceModBase::GetGameFolderName() const
586 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
588 return g_pSourcePawn;
591 IVirtualMachine *SourceModBase::GetScriptingVM()
596 void SourceModBase::AllPluginsLoaded()
598 SMGlobalClass *base = SMGlobalClass::head;
601 base->OnSourceModGameInitialized();
602 base = base->m_pGlobalClassNext;
606 time_t SourceModBase::GetAdjustedTime()
608 return ::GetAdjustedTime();
611 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
613 m_frame_hooks.push_back(hook);
616 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
618 for (size_t i = 0; i < m_frame_hooks.size(); i++)
620 if (m_frame_hooks[i] == hook)
622 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
628 void SourceModBase::ProcessGameFrameHooks(bool simulating)
630 if (m_frame_hooks.size() == 0)
635 for (size_t i = 0; i < m_frame_hooks.size(); i++)
637 m_frame_hooks[i](simulating);
641 SMGlobalClass *SMGlobalClass::head = NULL;
643 SMGlobalClass::SMGlobalClass()
645 m_pGlobalClassNext = SMGlobalClass::head;
646 SMGlobalClass::head = this;