extensions/tf2/extension.cpp
author David Anderson <dvander@alliedmods.net>
Thu Aug 08 22:02:42 2013 -0700 (2013-08-08)
changeset 3980 dc7dfcd855dc
parent 3892 2dac7e7ce4f1
child 4092 f184c016f489
permissions -rw-r--r--
More Windows build fix.
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod Team Fortress 2 Extension
     5  * Copyright (C) 2004-2011 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 "conditions.h"
    41 #include "gameplayrules.h"
    42 #include "teleporter.h"
    43 #include "CDetour/detours.h"
    44 
    45 /**
    46  * @file extension.cpp
    47  * @brief Implement extension code here.
    48  */
    49 
    50 
    51 TF2Tools g_TF2Tools;
    52 IGameConfig *g_pGameConf = NULL;
    53 
    54 IBinTools *g_pBinTools = NULL;
    55 
    56 SMEXT_LINK(&g_TF2Tools);
    57 
    58 ICvar *icvar = NULL;
    59 
    60 CGlobalVars *gpGlobals = NULL;
    61 
    62 sm_sendprop_info_t *playerSharedOffset;
    63 
    64 extern sp_nativeinfo_t g_TFNatives[];
    65 
    66 int g_resourceEntity;
    67 
    68 SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int , int);
    69 
    70 bool TF2Tools::SDK_OnLoad(char *error, size_t maxlength, bool late)
    71 {
    72 	if (strcmp(g_pSM->GetGameFolderName(), "tf") != 0)
    73 	{
    74 		UTIL_Format(error, maxlength, "Cannot Load TF2 Extension on mods other than TF2");
    75 		return false;
    76 	}
    77 
    78 	ServerClass *sc = UTIL_FindServerClass("CTFPlayer");
    79 	if (sc == NULL)
    80 	{
    81 		UTIL_Format(error, maxlength, "Could not find CTFPlayer server class");
    82 		return false;
    83 	}
    84 
    85 	playerSharedOffset = new sm_sendprop_info_t;
    86 
    87 	if (!UTIL_FindDataTable(sc->m_pTable, "DT_TFPlayerShared", playerSharedOffset, 0))
    88 	{
    89 		UTIL_Format(error, maxlength, "Could not find DT_TFPlayerShared data table");
    90 		return false;
    91 	}
    92 
    93 	sharesys->AddDependency(myself, "bintools.ext", true, true);
    94 
    95 	char conf_error[255] = "";
    96 	if (!gameconfs->LoadGameConfigFile("sm-tf2.games", &g_pGameConf, conf_error, sizeof(conf_error)))
    97 	{
    98 		if (conf_error[0])
    99 		{
   100 			UTIL_Format(error, maxlength, "Could not read sm-tf2.games.txt: %s", conf_error);
   101 		}
   102 		return false;
   103 	}
   104 
   105 	CDetourManager::Init(g_pSM->GetScriptingEngine(), g_pGameConf);
   106 
   107 	sharesys->AddNatives(myself, g_TFNatives);
   108 	sharesys->RegisterLibrary(myself, "tf2");
   109 
   110 	plsys->AddPluginsListener(this);
   111 
   112 	playerhelpers->RegisterCommandTargetProcessor(this);
   113 	playerhelpers->AddClientListener(this);
   114 
   115 	g_critForward = forwards->CreateForward("TF2_CalcIsAttackCritical", ET_Hook, 4, NULL, Param_Cell, Param_Cell, Param_String, Param_CellByRef);
   116 	g_isHolidayForward = forwards->CreateForward("TF2_OnIsHolidayActive", ET_Event, 2, NULL, Param_Cell, Param_CellByRef);
   117 	g_addCondForward = forwards->CreateForward("TF2_OnConditionAdded", ET_Ignore, 2, NULL, Param_Cell, Param_Cell);
   118 	g_removeCondForward = forwards->CreateForward("TF2_OnConditionRemoved", ET_Ignore, 2, NULL, Param_Cell, Param_Cell);
   119 	g_waitingPlayersStartForward = forwards->CreateForward("TF2_OnWaitingForPlayersStart", ET_Ignore, 0, NULL);
   120 	g_waitingPlayersEndForward = forwards->CreateForward("TF2_OnWaitingForPlayersEnd", ET_Ignore, 0, NULL);
   121 	g_teleportForward = forwards->CreateForward("TF2_OnPlayerTeleport", ET_Hook, 3, NULL, Param_Cell, Param_Cell, Param_CellByRef);
   122 
   123 	g_pCVar = icvar;
   124 
   125 	m_CritDetoursEnabled = false;
   126 	m_IsHolidayDetourEnabled = false;
   127 	m_CondChecksEnabled = false;
   128 	m_RulesDetoursEnabled = false;
   129 	m_TeleportDetourEnabled = false;
   130 
   131 	return true;
   132 }
   133 
   134 const char *TF2Tools::GetExtensionVerString()
   135 {
   136 	return SM_VERSION_STRING;
   137 }
   138 
   139 const char *TF2Tools::GetExtensionDateString()
   140 {
   141 	return SM_BUILD_TIMESTAMP;
   142 }
   143 
   144 bool TF2Tools::SDK_OnMetamodLoad(ISmmAPI *ismm, char *error, size_t maxlen, bool late)
   145 {
   146 	GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
   147 
   148 	gpGlobals = ismm->GetCGlobals();
   149 
   150 	SH_ADD_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_STATIC(OnServerActivate), true);
   151 
   152 	GET_V_IFACE_CURRENT(GetEngineFactory, icvar, ICvar, CVAR_INTERFACE_VERSION);
   153 
   154 	GET_V_IFACE_CURRENT(GetServerFactory, gameents, IServerGameEnts, INTERFACEVERSION_SERVERGAMEENTS);
   155 
   156 	GET_V_IFACE_CURRENT(GetEngineFactory, m_GameEventManager, IGameEventManager2, INTERFACEVERSION_GAMEEVENTSMANAGER2);
   157 	m_GameEventManager->AddListener(this, "teamplay_restart_round", true);
   158 
   159 	return true;
   160 }
   161 
   162 void TF2Tools::SDK_OnUnload()
   163 {
   164 	SH_REMOVE_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_STATIC(OnServerActivate), true);
   165 
   166 	g_RegNatives.UnregisterAll();
   167 	gameconfs->CloseGameConfigFile(g_pGameConf);
   168 	playerhelpers->UnregisterCommandTargetProcessor(this);
   169 	playerhelpers->RemoveClientListener(this);
   170 
   171 	plsys->RemovePluginsListener(this);
   172 
   173 	forwards->ReleaseForward(g_critForward);
   174 	forwards->ReleaseForward(g_isHolidayForward);
   175 	forwards->ReleaseForward(g_addCondForward);
   176 	forwards->ReleaseForward(g_removeCondForward);
   177 	forwards->ReleaseForward(g_waitingPlayersStartForward);
   178 	forwards->ReleaseForward(g_waitingPlayersEndForward);
   179 	forwards->ReleaseForward(g_teleportForward);
   180 }
   181 
   182 void TF2Tools::SDK_OnAllLoaded()
   183 {
   184 	SM_GET_LATE_IFACE(BINTOOLS, g_pBinTools);
   185 }
   186 
   187 bool TF2Tools::RegisterConCommandBase(ConCommandBase *pVar)
   188 {
   189 	return g_SMAPI->RegisterConCommandBase(g_PLAPI, pVar);
   190 }
   191 
   192 void TF2Tools::FireGameEvent( IGameEvent *event )
   193 {
   194 	timersys->NotifyOfGameStart();
   195 	timersys->MapTimeLeftChanged();
   196 }
   197 
   198 bool TF2Tools::QueryRunning(char *error, size_t maxlength)
   199 {
   200 	SM_CHECK_IFACE(BINTOOLS, g_pBinTools);
   201 
   202 	return true;
   203 }
   204 
   205 bool TF2Tools::QueryInterfaceDrop(SMInterface *pInterface)
   206 {
   207 	if (pInterface == g_pBinTools)
   208 	{
   209 		return false;
   210 	}
   211 
   212 	return IExtensionInterface::QueryInterfaceDrop(pInterface);
   213 }
   214 
   215 void TF2Tools::NotifyInterfaceDrop(SMInterface *pInterface)
   216 {
   217 	g_RegNatives.UnregisterAll();
   218 }
   219 
   220 void OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
   221 {
   222 	g_resourceEntity = FindResourceEntity();
   223 }
   224 
   225 bool TF2Tools::ProcessCommandTarget(cmd_target_info_t *info)
   226 {
   227 	int max_clients;
   228 	IPlayerInfo *pInfo;
   229 	unsigned int team_index = 0;
   230 	IGamePlayer *pPlayer, *pAdmin;
   231 
   232 	if ((info->flags & COMMAND_FILTER_NO_MULTI) == COMMAND_FILTER_NO_MULTI)
   233 	{
   234 		return false;
   235 	}
   236 
   237 	if (info->admin)
   238 	{
   239 		if ((pAdmin = playerhelpers->GetGamePlayer(info->admin)) == NULL)
   240 		{
   241 			return false;
   242 		}
   243 		if (!pAdmin->IsInGame())
   244 		{
   245 			return false;
   246 		}
   247 	}
   248 	else
   249 	{
   250 		pAdmin = NULL;
   251 	}
   252 
   253 	if (strcmp(info->pattern, "@red") == 0 )
   254 	{
   255 		team_index = 2;
   256 	}
   257 	else if (strcmp(info->pattern, "@blue") == 0)
   258 	{
   259 		team_index = 3;
   260 	}
   261 	else
   262 	{
   263 		return false;
   264 	}
   265 
   266 	info->num_targets = 0;
   267 
   268 	max_clients = playerhelpers->GetMaxClients();
   269 	for (int i = 1; 
   270 		 i <= max_clients && (cell_t)info->num_targets < info->max_targets; 
   271 		 i++)
   272 	{
   273 		if ((pPlayer = playerhelpers->GetGamePlayer(i)) == NULL)
   274 		{
   275 			continue;
   276 		}
   277 		if (!pPlayer->IsInGame())
   278 		{
   279 			continue;
   280 		}
   281 		if ((pInfo = pPlayer->GetPlayerInfo()) == NULL)
   282 		{
   283 			continue;
   284 		}
   285 		if (pInfo->GetTeamIndex() != (int)team_index)
   286 		{
   287 			continue;
   288 		}
   289 		if (playerhelpers->FilterCommandTarget(pAdmin, pPlayer, info->flags) 
   290 			!= COMMAND_TARGET_VALID)
   291 		{
   292 			continue;
   293 		}
   294 		info->targets[info->num_targets] = i;
   295 		info->num_targets++;
   296 	}
   297 
   298 	if (info->num_targets == 0)
   299 	{
   300 		info->reason = COMMAND_TARGET_EMPTY_FILTER;
   301 	}
   302 	else
   303 	{
   304 		info->reason = COMMAND_TARGET_VALID;
   305 	}
   306 
   307 	info->target_name_style = COMMAND_TARGETNAME_RAW;
   308 	if (team_index == 2)
   309 	{
   310 		UTIL_Format(info->target_name, info->target_name_maxlength, "Red Team");
   311 	}
   312 	else if (team_index == 3)
   313 	{
   314 		UTIL_Format(info->target_name, info->target_name_maxlength, "Blue Team");
   315 	}
   316 	
   317 	return true;
   318 }
   319 
   320 void TF2Tools::OnPluginLoaded(IPlugin *plugin)
   321 {
   322 	if (!m_CritDetoursEnabled && g_critForward->GetFunctionCount())
   323 	{
   324 		m_CritDetoursEnabled = InitialiseCritDetours();
   325 	}
   326 
   327 	if (!m_IsHolidayDetourEnabled && g_isHolidayForward->GetFunctionCount())
   328 	{
   329 		m_IsHolidayDetourEnabled = InitialiseIsHolidayDetour();
   330 	}
   331 
   332 	if (!m_CondChecksEnabled
   333 		&& ( g_addCondForward->GetFunctionCount() || g_removeCondForward->GetFunctionCount() )
   334 		)
   335 	{
   336 		m_CondChecksEnabled = InitialiseConditionChecks();
   337 	}
   338 
   339 	if (!m_RulesDetoursEnabled
   340 		&& ( g_waitingPlayersStartForward->GetFunctionCount() || g_waitingPlayersEndForward->GetFunctionCount() )
   341 		)
   342 	{
   343 		m_RulesDetoursEnabled = InitialiseRulesDetours();
   344 	}
   345 
   346 	if (!m_TeleportDetourEnabled && g_teleportForward->GetFunctionCount())
   347 	{
   348 		m_TeleportDetourEnabled = InitialiseTeleporterDetour();
   349 	}
   350 }
   351 
   352 void TF2Tools::OnPluginUnloaded(IPlugin *plugin)
   353 {
   354 	if (m_CritDetoursEnabled && !g_critForward->GetFunctionCount())
   355 	{
   356 		RemoveCritDetours();
   357 		m_CritDetoursEnabled = false;
   358 	}
   359 	if (m_IsHolidayDetourEnabled && !g_isHolidayForward->GetFunctionCount())
   360 	{
   361 		RemoveIsHolidayDetour();
   362 		m_IsHolidayDetourEnabled = false;
   363 	}
   364 	if (m_CondChecksEnabled)
   365 	{
   366 		if (!g_addCondForward->GetFunctionCount() && !g_removeCondForward->GetFunctionCount())
   367 		{
   368 			RemoveConditionChecks();
   369 			m_CondChecksEnabled = false;
   370 		}
   371 	}
   372 	if (m_RulesDetoursEnabled)
   373 	{
   374 		if (!g_waitingPlayersStartForward->GetFunctionCount() && !g_waitingPlayersEndForward->GetFunctionCount())
   375 		{
   376 			RemoveRulesDetours();
   377 			m_RulesDetoursEnabled = false;
   378 		}
   379 	}
   380 	if (m_TeleportDetourEnabled && !g_teleportForward->GetFunctionCount())
   381 	{
   382 		RemoveTeleporterDetour();
   383 		m_TeleportDetourEnabled = false;
   384 	}
   385 }
   386 
   387 void TF2Tools::OnClientPutInServer(int client)
   388 {
   389 	Conditions_OnClientPutInServer(client);
   390 }
   391 
   392 int FindResourceEntity()
   393 {
   394 	return FindEntityByNetClass(-1, "CTFPlayerResource");
   395 }
   396 
   397 
   398 int FindEntityByNetClass(int start, const char *classname)
   399 {
   400 	edict_t *current;
   401 
   402 	for (int i = ((start != -1) ? start : 0); i < gpGlobals->maxEntities; i++)
   403 	{
   404 		current = engine->PEntityOfEntIndex(i);
   405 		if (current == NULL)
   406 		{
   407 			continue;
   408 		}
   409 
   410 		IServerNetworkable *network = current->GetNetworkable();
   411 
   412 		if (network == NULL)
   413 		{
   414 			continue;
   415 		}
   416 
   417 		ServerClass *sClass = network->GetServerClass();
   418 		const char *name = sClass->GetName();
   419 		
   420 
   421 		if (strcmp(name, classname) == 0)
   422 		{
   423 			return i;
   424 		}
   425 	}
   426 
   427 	return -1;
   428 }
   429 
   430 TFClassType ClassnameToType(const char *classname)
   431 {
   432 	static KTrie<TFClassType> trie;
   433 	static bool filled = false;
   434 	
   435 	if (!filled)
   436 	{
   437 		trie.insert("scout", TFClass_Scout);
   438 		trie.insert("sniper", TFClass_Sniper);
   439 		trie.insert("soldier", TFClass_Soldier);
   440 		trie.insert("demoman", TFClass_DemoMan);
   441 		trie.insert("demo", TFClass_DemoMan);
   442 		trie.insert("medic", TFClass_Medic);
   443 		trie.insert("heavy", TFClass_Heavy);
   444 		trie.insert("heavyweap", TFClass_Heavy);
   445 		trie.insert("heavyweapons", TFClass_Heavy);
   446 		trie.insert("hwg", TFClass_Heavy);
   447 		trie.insert("pyro", TFClass_Pyro);
   448 		trie.insert("spy", TFClass_Spy);
   449 		trie.insert("engineer", TFClass_Engineer);
   450 		trie.insert("engy", TFClass_Engineer);
   451 
   452 		filled = true;	
   453 	}
   454 	
   455 	TFClassType *value;
   456 
   457 	if (!(value = trie.retrieve(classname)))
   458 	{
   459 		return TFClass_Unknown;	
   460 	}
   461 
   462 	return *value;
   463 }
   464 
   465 
   466 
   467 /**
   468  * A picture of a blue crab given to me as a gift and stored here for safe keeping
   469  *
   470  * http://sourcemod.net/Clown%20car.jpg
   471  */
   472