extensions/tf2/extension.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Mon Jun 28 17:48:14 2010 -0400 (2010-06-28)
changeset 3056 4e1591dceb8d
parent 2790 6dd851ba15fd
child 3151 aef99299f88b
permissions -rw-r--r--
Added forward/detour for TF2's GetHoliday function (bug 4462, r=pred)
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod Team Fortress 2 Extension
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <sourcemod_version.h>
    33 #include "extension.h"
    34 #include "util.h"
    35 #include "RegNatives.h"
    36 #include "iplayerinfo.h"
    37 #include "sm_trie_tpl.h"
    38 #include "criticals.h"
    39 #include "holiday.h"
    40 #include "CDetour/detours.h"
    41 
    42 /**
    43  * @file extension.cpp
    44  * @brief Implement extension code here.
    45  */
    46 
    47 
    48 TF2Tools g_TF2Tools;
    49 IGameConfig *g_pGameConf = NULL;
    50 
    51 IBinTools *g_pBinTools = NULL;
    52 
    53 SMEXT_LINK(&g_TF2Tools);
    54 
    55 ICvar *icvar = NULL;
    56 
    57 CGlobalVars *gpGlobals = NULL;
    58 
    59 sm_sendprop_info_t *playerSharedOffset;
    60 
    61 extern sp_nativeinfo_t g_TFNatives[];
    62 
    63 int g_resourceEntity;
    64 
    65 SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int , int);
    66 
    67 bool TF2Tools::SDK_OnLoad(char *error, size_t maxlength, bool late)
    68 {
    69 	if (strcmp(g_pSM->GetGameFolderName(), "tf") != 0)
    70 	{
    71 		UTIL_Format(error, maxlength, "Cannot Load TF2 Extension on mods other than TF2");
    72 		return false;
    73 	}
    74 
    75 	ServerClass *sc = UTIL_FindServerClass("CTFPlayer");
    76 	if (sc == NULL)
    77 	{
    78 		UTIL_Format(error, maxlength, "Could not find CTFPlayer server class");
    79 		return false;
    80 	}
    81 
    82 	playerSharedOffset = new sm_sendprop_info_t;
    83 
    84 	if (!UTIL_FindDataTable(sc->m_pTable, "DT_TFPlayerShared", playerSharedOffset, 0))
    85 	{
    86 		UTIL_Format(error, maxlength, "Could not find DT_TFPlayerShared data table");
    87 		return false;
    88 	}
    89 
    90 	sharesys->AddDependency(myself, "bintools.ext", true, true);
    91 
    92 	char conf_error[255] = "";
    93 	if (!gameconfs->LoadGameConfigFile("sm-tf2.games", &g_pGameConf, conf_error, sizeof(conf_error)))
    94 	{
    95 		if (conf_error[0])
    96 		{
    97 			UTIL_Format(error, maxlength, "Could not read sm-tf2.games.txt: %s", conf_error);
    98 		}
    99 		return false;
   100 	}
   101 
   102 	CDetourManager::Init(g_pSM->GetScriptingEngine(), g_pGameConf);
   103 
   104 	sharesys->AddNatives(myself, g_TFNatives);
   105 	sharesys->RegisterLibrary(myself, "tf2");
   106 
   107 	plsys->AddPluginsListener(this);
   108 
   109 	playerhelpers->RegisterCommandTargetProcessor(this);
   110 
   111 	g_critForward = forwards->CreateForward("TF2_CalcIsAttackCritical", ET_Hook, 4, NULL, Param_Cell, Param_Cell, Param_String, Param_CellByRef);
   112 	g_getHolidayForward = forwards->CreateForward("TF2_OnGetHoliday", ET_Event, 1, NULL, Param_CellByRef);
   113 
   114 	g_pCVar = icvar;
   115 
   116 	m_CritDetoursEnabled = false;
   117 	m_GetHolidayDetourEnabled = false;
   118 
   119 	return true;
   120 }
   121 
   122 const char *TF2Tools::GetExtensionVerString()
   123 {
   124 	return SM_FULL_VERSION;
   125 }
   126 
   127 const char *TF2Tools::GetExtensionDateString()
   128 {
   129 	return SM_BUILD_TIMESTAMP;
   130 }
   131 
   132 bool TF2Tools::SDK_OnMetamodLoad(ISmmAPI *ismm, char *error, size_t maxlen, bool late)
   133 {
   134 	GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
   135 
   136 	gpGlobals = ismm->GetCGlobals();
   137 
   138 	SH_ADD_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_STATIC(OnServerActivate), true);
   139 
   140 	GET_V_IFACE_CURRENT(GetEngineFactory, icvar, ICvar, CVAR_INTERFACE_VERSION);
   141 
   142 	GET_V_IFACE_CURRENT(GetServerFactory, gameents, IServerGameEnts, INTERFACEVERSION_SERVERGAMEENTS);
   143 
   144 	GET_V_IFACE_CURRENT(GetEngineFactory, m_GameEventManager, IGameEventManager2, INTERFACEVERSION_GAMEEVENTSMANAGER2);
   145 	m_GameEventManager->AddListener(this, "teamplay_restart_round", true);
   146 
   147 	return true;
   148 }
   149 
   150 void TF2Tools::SDK_OnUnload()
   151 {
   152 	SH_REMOVE_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_STATIC(OnServerActivate), true);
   153 
   154 	g_RegNatives.UnregisterAll();
   155 	gameconfs->CloseGameConfigFile(g_pGameConf);
   156 	playerhelpers->UnregisterCommandTargetProcessor(this);
   157 
   158 	plsys->RemovePluginsListener(this);
   159 
   160 	forwards->ReleaseForward(g_critForward);
   161 	forwards->ReleaseForward(g_getHolidayForward);
   162 }
   163 
   164 void TF2Tools::SDK_OnAllLoaded()
   165 {
   166 	SM_GET_LATE_IFACE(BINTOOLS, g_pBinTools);
   167 }
   168 
   169 bool TF2Tools::RegisterConCommandBase(ConCommandBase *pVar)
   170 {
   171 	return g_SMAPI->RegisterConCommandBase(g_PLAPI, pVar);
   172 }
   173 
   174 void TF2Tools::FireGameEvent( IGameEvent *event )
   175 {
   176 	timersys->NotifyOfGameStart();
   177 	timersys->MapTimeLeftChanged();
   178 }
   179 
   180 bool TF2Tools::QueryRunning(char *error, size_t maxlength)
   181 {
   182 	SM_CHECK_IFACE(BINTOOLS, g_pBinTools);
   183 
   184 	return true;
   185 }
   186 
   187 bool TF2Tools::QueryInterfaceDrop(SMInterface *pInterface)
   188 {
   189 	if (pInterface == g_pBinTools)
   190 	{
   191 		return false;
   192 	}
   193 
   194 	return IExtensionInterface::QueryInterfaceDrop(pInterface);
   195 }
   196 
   197 void TF2Tools::NotifyInterfaceDrop(SMInterface *pInterface)
   198 {
   199 	g_RegNatives.UnregisterAll();
   200 }
   201 
   202 void OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
   203 {
   204 	g_resourceEntity = FindResourceEntity();
   205 }
   206 
   207 bool TF2Tools::ProcessCommandTarget(cmd_target_info_t *info)
   208 {
   209 	int max_clients;
   210 	IPlayerInfo *pInfo;
   211 	unsigned int team_index = 0;
   212 	IGamePlayer *pPlayer, *pAdmin;
   213 
   214 	if ((info->flags & COMMAND_FILTER_NO_MULTI) == COMMAND_FILTER_NO_MULTI)
   215 	{
   216 		return false;
   217 	}
   218 
   219 	if (info->admin)
   220 	{
   221 		if ((pAdmin = playerhelpers->GetGamePlayer(info->admin)) == NULL)
   222 		{
   223 			return false;
   224 		}
   225 		if (!pAdmin->IsInGame())
   226 		{
   227 			return false;
   228 		}
   229 	}
   230 	else
   231 	{
   232 		pAdmin = NULL;
   233 	}
   234 
   235 	if (strcmp(info->pattern, "@red") == 0 )
   236 	{
   237 		team_index = 2;
   238 	}
   239 	else if (strcmp(info->pattern, "@blue") == 0)
   240 	{
   241 		team_index = 3;
   242 	}
   243 	else
   244 	{
   245 		return false;
   246 	}
   247 
   248 	info->num_targets = 0;
   249 
   250 	max_clients = playerhelpers->GetMaxClients();
   251 	for (int i = 1; 
   252 		 i <= max_clients && (cell_t)info->num_targets < info->max_targets; 
   253 		 i++)
   254 	{
   255 		if ((pPlayer = playerhelpers->GetGamePlayer(i)) == NULL)
   256 		{
   257 			continue;
   258 		}
   259 		if (!pPlayer->IsInGame())
   260 		{
   261 			continue;
   262 		}
   263 		if ((pInfo = pPlayer->GetPlayerInfo()) == NULL)
   264 		{
   265 			continue;
   266 		}
   267 		if (pInfo->GetTeamIndex() != (int)team_index)
   268 		{
   269 			continue;
   270 		}
   271 		if (playerhelpers->FilterCommandTarget(pAdmin, pPlayer, info->flags) 
   272 			!= COMMAND_TARGET_VALID)
   273 		{
   274 			continue;
   275 		}
   276 		info->targets[info->num_targets] = i;
   277 		info->num_targets++;
   278 	}
   279 
   280 	if (info->num_targets == 0)
   281 	{
   282 		info->reason = COMMAND_TARGET_EMPTY_FILTER;
   283 	}
   284 	else
   285 	{
   286 		info->reason = COMMAND_TARGET_VALID;
   287 	}
   288 
   289 	info->target_name_style = COMMAND_TARGETNAME_RAW;
   290 	if (team_index == 2)
   291 	{
   292 		UTIL_Format(info->target_name, info->target_name_maxlength, "Red Team");
   293 	}
   294 	else if (team_index == 3)
   295 	{
   296 		UTIL_Format(info->target_name, info->target_name_maxlength, "Blue Team");
   297 	}
   298 
   299 	return true;
   300 }
   301 
   302 void TF2Tools::OnPluginLoaded(IPlugin *plugin)
   303 {
   304 	if (!m_CritDetoursEnabled && g_critForward->GetFunctionCount())
   305 	{
   306 		InitialiseCritDetours();
   307 		m_CritDetoursEnabled = true;
   308 	}
   309 	if (!m_GetHolidayDetourEnabled && g_getHolidayForward->GetFunctionCount())
   310 	{
   311 		InitialiseGetHolidayDetour();
   312 		m_GetHolidayDetourEnabled = true;
   313 	}
   314 }
   315 
   316 void TF2Tools::OnPluginUnloaded(IPlugin *plugin)
   317 {
   318 	if (m_CritDetoursEnabled && !g_critForward->GetFunctionCount())
   319 	{
   320 		RemoveCritDetours();
   321 		m_CritDetoursEnabled = false;
   322 	}
   323 	if (m_GetHolidayDetourEnabled && !g_getHolidayForward->GetFunctionCount())
   324 	{
   325 		RemoveGetHolidayDetour();
   326 		m_GetHolidayDetourEnabled = false;
   327 	}
   328 }
   329 int FindResourceEntity()
   330 {
   331 	return FindEntityByNetClass(-1, "CTFPlayerResource");
   332 }
   333 
   334 
   335 int FindEntityByNetClass(int start, const char *classname)
   336 {
   337 	edict_t *current;
   338 
   339 	for (int i = ((start != -1) ? start : 0); i < gpGlobals->maxEntities; i++)
   340 	{
   341 		current = engine->PEntityOfEntIndex(i);
   342 		if (current == NULL)
   343 		{
   344 			continue;
   345 		}
   346 
   347 		IServerNetworkable *network = current->GetNetworkable();
   348 
   349 		if (network == NULL)
   350 		{
   351 			continue;
   352 		}
   353 
   354 		ServerClass *sClass = network->GetServerClass();
   355 		const char *name = sClass->GetName();
   356 		
   357 
   358 		if (strcmp(name, classname) == 0)
   359 		{
   360 			return i;
   361 		}
   362 	}
   363 
   364 	return -1;
   365 }
   366 
   367 TFClassType ClassnameToType(const char *classname)
   368 {
   369 	static KTrie<TFClassType> trie;
   370 	static bool filled = false;
   371 	
   372 	if (!filled)
   373 	{
   374 		trie.insert("scout", TFClass_Scout);
   375 		trie.insert("sniper", TFClass_Sniper);
   376 		trie.insert("soldier", TFClass_Soldier);
   377 		trie.insert("demoman", TFClass_DemoMan);
   378 		trie.insert("demo", TFClass_DemoMan);
   379 		trie.insert("medic", TFClass_Medic);
   380 		trie.insert("heavy", TFClass_Heavy);
   381 		trie.insert("hwg", TFClass_Heavy);
   382 		trie.insert("pyro", TFClass_Pyro);
   383 		trie.insert("spy", TFClass_Spy);
   384 		trie.insert("engineer", TFClass_Engineer);
   385 		trie.insert("engy", TFClass_Engineer);
   386 
   387 		filled = true;	
   388 	}
   389 	
   390 	TFClassType *value;
   391 
   392 	if (!(value = trie.retrieve(classname)))
   393 	{
   394 		return TFClass_Unknown;	
   395 	}
   396 
   397 	return *value;
   398 }
   399 
   400 
   401 
   402 /**
   403  * A picture of a blue crab given to me as a gift and stored here for safe keeping
   404  *
   405  * http://www.democracycellproject.net/blog/archives/Clown%20car.jpg
   406  */
   407