core/HalfLife2.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Tue Mar 19 11:19:19 2013 -0400 (2013-03-19)
changeset 3854 8abb0924497b
parent 3822 dfee1850a179
child 3855 d8ba5eddf543
permissions -rw-r--r--
Tweaked Dota 2 support to account for lack of IPluginHelpers (bug 5656, r=asherkin).
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     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 "HalfLife2.h"
    33 #include "sourcemod.h"
    34 #include "sourcemm_api.h"
    35 #include "UserMessages.h"
    36 #include "PlayerManager.h"
    37 #include "sm_stringutil.h"
    38 #include <IGameConfigs.h>
    39 #include <compat_wrappers.h>
    40 #include <Logger.h>
    41 #include "LibrarySys.h"
    42 #include "logic_bridge.h"
    43 #include <tier0/mem.h>
    44 
    45 #if SOURCE_ENGINE == SE_CSGO
    46 #include <cstrike15_usermessages.pb.h>
    47 #endif
    48 
    49 
    50 typedef ICommandLine *(*FakeGetCommandLine)();
    51 
    52 #if defined _WIN32
    53 #define TIER0_NAME			"tier0.dll"
    54 #define VSTDLIB_NAME		"vstdlib.dll"
    55 #elif defined __APPLE__
    56 #define TIER0_NAME			"libtier0.dylib"
    57 #define VSTDLIB_NAME		"libvstdlib.dylib"
    58 #elif defined __linux__
    59 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS
    60 #define TIER0_NAME			"libtier0_srv.so"
    61 #define VSTDLIB_NAME		"libvstdlib_srv.so"
    62 #elif SOURCE_ENGINE >= SE_LEFT4DEAD
    63 #define TIER0_NAME			"libtier0.so"
    64 #define VSTDLIB_NAME		"libvstdlib.so"
    65 #else
    66 #define TIER0_NAME			"tier0_i486.so"
    67 #define VSTDLIB_NAME		"vstdlib_i486.so"
    68 #endif
    69 #endif
    70 
    71 CHalfLife2 g_HL2;
    72 ConVar *sv_lan = NULL;
    73 
    74 static void *g_EntList = NULL;
    75 static int entInfoOffset = -1;
    76 
    77 namespace SourceHook
    78 {
    79 	template<>
    80 	int HashFunction<datamap_t *>(datamap_t * const &k)
    81 	{
    82 		return reinterpret_cast<int>(k);
    83 	}
    84 
    85 	template<>
    86 	int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
    87 	{
    88 		return (k1-k2);
    89 	}
    90 }
    91 
    92 CHalfLife2::CHalfLife2()
    93 {
    94 	m_pClasses = sm_trie_create();
    95 }
    96 
    97 CHalfLife2::~CHalfLife2()
    98 {
    99 	sm_trie_destroy(m_pClasses);
   100 
   101 	List<DataTableInfo *>::iterator iter;
   102 	DataTableInfo *pInfo;
   103 	for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
   104 	{
   105 		pInfo = (*iter);
   106 		delete pInfo;
   107 	}
   108 
   109 	m_Tables.clear();
   110 
   111 	THash<datamap_t *, DataMapTrie>::iterator h_iter;
   112 	for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
   113 	{
   114 		if (h_iter->val.trie)
   115 		{
   116 			sm_trie_destroy(h_iter->val.trie);
   117 			h_iter->val.trie = NULL;
   118 		}
   119 	}
   120 
   121 	m_Maps.clear();
   122 }
   123 
   124 #if SOURCE_ENGINE != SE_DARKMESSIAH
   125 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
   126 #endif
   127 
   128 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
   129 bool is_original_engine = false;
   130 #endif
   131 
   132 void CHalfLife2::OnSourceModStartup(bool late)
   133 {
   134 #if SOURCE_ENGINE != SE_DARKMESSIAH
   135 
   136 	/* The Ship currently is the only known game to use an older version of the engine */
   137 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
   138 	if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
   139 #else
   140 	if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
   141 #endif
   142 	{
   143 		is_original_engine = true;
   144 	}
   145 	else if (g_pSharedChangeInfo == NULL)
   146 	{
   147 		g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
   148 	}
   149 #endif
   150 }
   151 
   152 void CHalfLife2::OnSourceModAllInitialized()
   153 {
   154 	m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
   155 	m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
   156 	m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
   157 	m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
   158 	g_ShareSys.AddInterface(NULL, this);
   159 }
   160 
   161 void CHalfLife2::OnSourceModAllInitialized_Post()
   162 {
   163 	InitLogicalEntData();
   164 	InitCommandLine();
   165 }
   166 
   167 void CHalfLife2::InitLogicalEntData()
   168 {
   169 	char *addr = NULL;
   170 
   171 	/*
   172 	 * gEntList and/or g_pEntityList
   173 	 *
   174 	 * First try to lookup pointer directly for platforms with symbols.
   175 	 * If symbols aren't present (Windows or stripped Linux/Mac), 
   176 	 * attempt find via LevelShutdown + offset
   177 	 */
   178 	if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
   179 	{
   180 #if !defined PLATFORM_WINDOWS
   181 		if (!addr)
   182 		{
   183 			// Key exists so notify if lookup fails, but try other method.
   184 			g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
   185 		}
   186 		else
   187 		{
   188 #endif
   189 			g_EntList = reinterpret_cast<void *>(addr);
   190 #if !defined PLATFORM_WINDOWS
   191 		}
   192 #endif
   193 	}
   194 
   195 
   196 	if (!g_EntList)
   197 	{
   198 		if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
   199 		{
   200 			g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
   201 			return;
   202 		}
   203 
   204 		if (!addr)
   205 		{
   206 			g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
   207 			return;
   208 		}
   209 
   210 		int offset;
   211 		if (!g_pGameConf->GetOffset("gEntList", &offset))
   212 		{
   213 			g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
   214 			return;
   215 		}
   216 
   217 		g_EntList = *reinterpret_cast<void **>(addr + offset);
   218 	}
   219 	
   220 	if (!g_EntList)
   221 	{
   222 		g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
   223 		return;
   224 	}
   225 
   226 	if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
   227 	{
   228 		g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
   229 		return;
   230 	}
   231 }
   232 
   233 void CHalfLife2::InitCommandLine()
   234 {
   235 	char path[PLATFORM_MAX_PATH];
   236 	char error[256];
   237 	
   238 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
   239 
   240 	if (!g_LibSys.IsPathFile(path))
   241 	{
   242 		g_Logger.LogError("Could not find path for: " TIER0_NAME);
   243 		return;
   244 	}
   245 
   246 	ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
   247 	m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
   248 
   249 	/* '_Tier0' dropped on Alien Swarm version */
   250 	if (m_pGetCommandLine == NULL)
   251 	{
   252 		m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
   253 	}
   254 
   255 	if (m_pGetCommandLine == NULL)
   256 	{
   257 		/* We probably have a Ship engine. */
   258 		lib->CloseLibrary();
   259 		g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
   260 		if (!g_LibSys.IsPathFile(path))
   261 		{
   262 			g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
   263 			return;
   264 		}
   265 
   266 		if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
   267 		{
   268 			g_Logger.LogError("Could not load %s: %s", path, error);
   269 			return;
   270 		}
   271 
   272 		m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
   273 
   274 		if (m_pGetCommandLine == NULL)
   275 		{
   276 			g_Logger.LogError("Could not locate any command line functionality");
   277 		}
   278 
   279 		lib->CloseLibrary();
   280 	}
   281 }
   282 
   283 ICommandLine *CHalfLife2::GetValveCommandLine()
   284 {
   285 	if (!m_pGetCommandLine)
   286 		return NULL;
   287 
   288 	return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
   289 }
   290 
   291 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
   292 bool CHalfLife2::IsOriginalEngine()
   293 {
   294 	return is_original_engine;
   295 }
   296 #endif
   297 
   298 #if SOURCE_ENGINE != SE_DARKMESSIAH
   299 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
   300 {
   301 	return engine->GetChangeAccessor( (const edict_t *)this );
   302 }
   303 #endif
   304 
   305 bool UTIL_FindInSendTable(SendTable *pTable, 
   306 						  const char *name,
   307 						  sm_sendprop_info_t *info,
   308 						  unsigned int offset)
   309 {
   310 	const char *pname;
   311 	int props = pTable->GetNumProps();
   312 	SendProp *prop;
   313 
   314 	for (int i=0; i<props; i++)
   315 	{
   316 		prop = pTable->GetProp(i);
   317 		pname = prop->GetName();
   318 		if (pname && strcmp(name, pname) == 0)
   319 		{
   320 			info->prop = prop;
   321 			info->actual_offset = offset + info->prop->GetOffset();
   322 			return true;
   323 		}
   324 		if (prop->GetDataTable())
   325 		{
   326 			if (UTIL_FindInSendTable(prop->GetDataTable(), 
   327 				name,
   328 				info,
   329 				offset + prop->GetOffset())
   330 				)
   331 			{
   332 				return true;
   333 			}
   334 		}
   335 	}
   336 
   337 	return false;
   338 }
   339 
   340 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name, bool *isNested)
   341 {
   342 	if (isNested)
   343 	{
   344 		*isNested = false;
   345 	}
   346 	
   347 	while (pMap)
   348 	{
   349 		for (int i=0; i<pMap->dataNumFields; i++)
   350 		{
   351 			if (pMap->dataDesc[i].fieldName == NULL)
   352 			{
   353 				continue;
   354 			}
   355 			if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
   356 			{
   357 				return &(pMap->dataDesc[i]);
   358 			}
   359 			if (pMap->dataDesc[i].td)
   360 			{
   361 				if (isNested)
   362 				{
   363 					*isNested = (UTIL_FindInDataMap(pMap->dataDesc[i].td, name, NULL) != NULL);
   364 					if (*isNested)
   365 					{
   366 						return NULL;
   367 					} else {
   368 						continue;
   369 					}
   370 				} else { // Use the old behaviour, we dont want to spring this on extensions - even if they're doing bad things.
   371 					typedescription_t *_td;
   372 					if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name, NULL)) != NULL)
   373 					{
   374 						return _td;
   375 					}
   376 				}
   377 			}
   378 		}
   379 		pMap = pMap->baseMap;
   380 	}
   381 
   382 	return NULL; 
   383 }
   384 
   385 ServerClass *CHalfLife2::FindServerClass(const char *classname)
   386 {
   387 	DataTableInfo *pInfo = _FindServerClass(classname);
   388 
   389 	if (!pInfo)
   390 	{
   391 		return NULL;
   392 	}
   393 
   394 	return pInfo->sc;
   395 }
   396 
   397 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
   398 {
   399 	DataTableInfo *pInfo = NULL;
   400 
   401 	if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
   402 	{
   403 		ServerClass *sc = gamedll->GetAllServerClasses();
   404 		while (sc)
   405 		{
   406 			if (strcmp(classname, sc->GetName()) == 0)
   407 			{
   408 				pInfo = new DataTableInfo;
   409 				pInfo->sc = sc;
   410 				sm_trie_insert(m_pClasses, classname, pInfo);
   411 				m_Tables.push_back(pInfo);
   412 				break;
   413 			}
   414 			sc = sc->m_pNext;
   415 		}
   416 		if (!pInfo)
   417 		{
   418 			return NULL;
   419 		}
   420 	}
   421 
   422 	return pInfo;
   423 }
   424 
   425 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
   426 {
   427 	DataTableInfo *pInfo;
   428 	sm_sendprop_info_t *prop;
   429 
   430 	if ((pInfo = _FindServerClass(classname)) == NULL)
   431 	{
   432 		return false;
   433 	}
   434 
   435 	if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
   436 	{
   437 		sm_sendprop_info_t temp_info;
   438 
   439 		if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
   440 		{
   441 			return false;
   442 		}
   443 
   444 		pInfo->lookup.insert(offset, temp_info);
   445 		*info = temp_info;
   446 	}
   447 	else
   448 	{
   449 		*info = *prop;
   450 	}
   451 	
   452 	return true;
   453 }
   454 
   455 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
   456 {
   457 	sm_sendprop_info_t info;
   458 
   459 	if (!FindSendPropInfo(classname, offset, &info))
   460 	{
   461 		return NULL;
   462 	}
   463 
   464 	return info.prop;
   465 }
   466 
   467 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
   468 {
   469 	return this->FindInDataMap(pMap, offset, NULL);
   470 }
   471 
   472 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset, bool *isNested)
   473 {
   474 	typedescription_t *td = NULL;
   475 	DataMapTrie &val = m_Maps[pMap];
   476 
   477 	if (!val.trie)
   478 	{
   479 		val.trie = sm_trie_create();
   480 	}
   481 	if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
   482 	{
   483 		if ((td = UTIL_FindInDataMap(pMap, offset, isNested)) != NULL)
   484 		{
   485 			sm_trie_insert(val.trie, offset, td);
   486 		}
   487 	}
   488 
   489 	return td;
   490 }
   491 
   492 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
   493 {
   494 #if SOURCE_ENGINE != SE_DARKMESSIAH
   495 	if (g_pSharedChangeInfo != NULL)
   496 	{
   497 		if (offset)
   498 		{
   499 			pEdict->StateChanged(offset);
   500 		}
   501 		else
   502 		{
   503 			pEdict->StateChanged();
   504 		}
   505 	}
   506 	else
   507 #endif
   508 	{
   509 		pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
   510 	}
   511 }
   512 
   513 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
   514 {
   515 #if SOURCE_ENGINE != SE_CSGO
   516 	bf_write *pBitBuf = NULL;
   517 #endif
   518 	cell_t players[] = {client};
   519 
   520 	if (dest == HUD_PRINTTALK)
   521 	{
   522 		const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
   523 
   524 		/* Use SayText user message instead */
   525 		if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
   526 		{
   527 			char buffer[192];
   528 			UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
   529 
   530 #if SOURCE_ENGINE == SE_CSGO
   531 			CCSUsrMsg_SayText *pMsg;
   532 			if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   533 			{
   534 				return false;
   535 			}
   536 
   537 			pMsg->set_ent_idx(0);
   538 			pMsg->set_text(buffer);
   539 			pMsg->set_chat(false);
   540 #else
   541 			if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   542 			{
   543 				return false;
   544 			}
   545 
   546 			pBitBuf->WriteByte(0);
   547 			pBitBuf->WriteString(buffer);
   548 			pBitBuf->WriteByte(1);
   549 #endif
   550 
   551 			g_UserMsgs.EndMessage();
   552 
   553 			return true;
   554 		}
   555 	}
   556 
   557 #if SOURCE_ENGINE == SE_CSGO
   558 	CCSUsrMsg_TextMsg *pMsg;
   559 	if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   560 	{
   561 		return false;
   562 	}
   563 
   564 	// Client tries to read all 5 'params' and will crash if less
   565 	pMsg->set_msg_dst(dest);
   566 	pMsg->add_params(msg);
   567 	pMsg->add_params("");
   568 	pMsg->add_params("");
   569 	pMsg->add_params("");
   570 	pMsg->add_params("");
   571 #else
   572 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   573 	{
   574 		return false;
   575 	}
   576 
   577 	pBitBuf->WriteByte(dest);
   578 	pBitBuf->WriteString(msg);
   579 #endif
   580 
   581 	g_UserMsgs.EndMessage();
   582 
   583 	return true;
   584 }
   585 
   586 bool CHalfLife2::HintTextMsg(int client, const char *msg)
   587 {
   588 	cell_t players[] = {client};
   589 
   590 #if SOURCE_ENGINE == SE_CSGO
   591 	CCSUsrMsg_HintText *pMsg;
   592 	if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   593 	{
   594 		return false;
   595 	}
   596 
   597 	pMsg->set_text(msg);
   598 #else
   599 	bf_write *pBitBuf = NULL;
   600 
   601 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   602 	{
   603 		return false;
   604 	}
   605 
   606 	const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
   607 	if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
   608 	{
   609 		pBitBuf->WriteByte(1);
   610 	}
   611 	pBitBuf->WriteString(msg);
   612 #endif
   613 	g_UserMsgs.EndMessage();
   614 
   615 	return true;
   616 }
   617 
   618 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
   619 {
   620 #if SOURCE_ENGINE == SE_CSGO
   621 	CCSUsrMsg_HintText *pMsg;
   622 	if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
   623 	{
   624 		return false;
   625 	}
   626 
   627 	pMsg->set_text(msg);
   628 #else
   629 	bf_write *pBitBuf = NULL;
   630 
   631 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
   632 	{
   633 		return false;
   634 	}
   635 
   636 	const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
   637 	if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
   638 	{
   639 		pBitBuf->WriteByte(1);
   640 	}
   641 	pBitBuf->WriteString(msg);
   642 #endif
   643 
   644 	g_UserMsgs.EndMessage();
   645 
   646 	return true;
   647 }
   648 
   649 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
   650 {
   651 	KeyValues *SubKey = NULL;
   652 	int count = 0;
   653 	cell_t players[] = {client};
   654 
   655 #if SOURCE_ENGINE == SE_CSGO
   656 	CCSUsrMsg_VGUIMenu *pMsg;
   657 	if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
   658 	{
   659 		return false;
   660 	}
   661 #else
   662 	bf_write *pBitBuf = NULL;
   663 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
   664 	{
   665 		return false;
   666 	}
   667 #endif
   668 
   669 	if (data)
   670 	{
   671 		SubKey = data->GetFirstSubKey();
   672 		while (SubKey)
   673 		{
   674 			count++;
   675 			SubKey = SubKey->GetNextKey();
   676 		}
   677 		SubKey = data->GetFirstSubKey();
   678 	}
   679 
   680 #if SOURCE_ENGINE == SE_CSGO
   681 	pMsg->set_name(name);
   682 	pMsg->set_show(show);
   683 
   684 	while (SubKey)
   685 	{
   686 		CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
   687 		key->set_name(SubKey->GetName());
   688 		key->set_str(SubKey->GetString());
   689 		SubKey = SubKey->GetNextKey();
   690 	}
   691 #else
   692 	pBitBuf->WriteString(name);
   693 	pBitBuf->WriteByte((show) ? 1 : 0);
   694 	pBitBuf->WriteByte(count);
   695 	while (SubKey)
   696 	{
   697 		pBitBuf->WriteString(SubKey->GetName());
   698 		pBitBuf->WriteString(SubKey->GetString());
   699 		SubKey = SubKey->GetNextKey();
   700 	}
   701 #endif
   702 
   703 	g_UserMsgs.EndMessage();
   704 
   705 	return true;
   706 }
   707 
   708 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
   709 {
   710 	DelayedFakeCliCmd *pFake;
   711 
   712 	if (m_FreeCmds.empty())
   713 	{
   714 		pFake = new DelayedFakeCliCmd;
   715 	} else {
   716 		pFake = m_FreeCmds.front();
   717 		m_FreeCmds.pop();
   718 	}
   719 
   720 	pFake->client = client;
   721 	pFake->userid = userid;
   722 	pFake->cmd.assign(cmd);
   723 
   724 	m_CmdQueue.push(pFake);
   725 }
   726 
   727 void CHalfLife2::ProcessFakeCliCmdQueue()
   728 {
   729 	while (!m_CmdQueue.empty())
   730 	{
   731 		DelayedFakeCliCmd *pFake = m_CmdQueue.first();
   732 
   733 		if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
   734 		{
   735 			CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
   736 #if SOURCE_ENGINE == SE_DOTA
   737 			engine->ClientCommand(pPlayer->GetEdict(), "%s", pFake->cmd.c_str());
   738 #else
   739 			serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
   740 #endif
   741 		}
   742 
   743 		m_CmdQueue.pop();
   744 	}
   745 }
   746 
   747 bool CHalfLife2::IsLANServer()
   748 {
   749 	sv_lan = icvar->FindVar("sv_lan");
   750 
   751 	if (!sv_lan)
   752 	{
   753 		return false;
   754 	}
   755 
   756 	return (sv_lan->GetInt() != 0);
   757 }
   758 
   759 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
   760 {
   761 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
   762 	if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
   763 #else
   764 	if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
   765 #endif
   766 	{
   767 		Assert(filesystem);
   768 #ifdef _MSC_VER
   769 		Assert(_heapchk() == _HEAPOK);
   770 #endif
   771 
   772 		FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
   773 		if (!f)
   774 			return false;
   775 
   776 		// load file into a null-terminated buffer
   777 		int fileSize = filesystem->Size(f);
   778 		char *buffer = (char *)MemAllocScratch(fileSize + 1);
   779 
   780 		Assert(buffer);
   781 
   782 		filesystem->Read(buffer, fileSize, f); // read into local buffer
   783 
   784 		buffer[fileSize] = 0; // null terminate file as EOF
   785 
   786 		filesystem->Close( f );	// close file after reading
   787 
   788 		bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
   789 
   790 		MemFreeScratch();
   791 
   792 		return retOK;
   793 	}
   794 	else
   795 	{
   796 		return kv->LoadFromFile(filesystem, resourceName, pathID);
   797 	}
   798 }
   799 
   800 void CHalfLife2::PushCommandStack(const CCommand *cmd)
   801 {
   802 	CachedCommandInfo info;
   803 
   804 	info.args = cmd;
   805 #if SOURCE_ENGINE <= SE_DARKMESSIAH
   806 	strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
   807 #endif
   808 
   809 	m_CommandStack.push(info);
   810 }
   811 
   812 const CCommand *CHalfLife2::PeekCommandStack()
   813 {
   814 	if (m_CommandStack.empty())
   815 	{
   816 		return NULL;
   817 	}
   818 
   819 	return m_CommandStack.front().args;
   820 }
   821 
   822 void CHalfLife2::PopCommandStack()
   823 {
   824 	m_CommandStack.pop();
   825 }
   826 
   827 const char *CHalfLife2::CurrentCommandName()
   828 {
   829 #if SOURCE_ENGINE >= SE_ORANGEBOX
   830 	return m_CommandStack.front().args->Arg(0);
   831 #else
   832 	return m_CommandStack.front().cmd;
   833 #endif
   834 }
   835 
   836 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
   837 {
   838 	DelayedKickInfo kick;
   839 
   840 	kick.client = client;
   841 	kick.userid = userid;
   842 	UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
   843 
   844 	m_DelayedKicks.push(kick);
   845 }
   846 
   847 void CHalfLife2::ProcessDelayedKicks()
   848 {
   849 	while (!m_DelayedKicks.empty())
   850 	{
   851 		DelayedKickInfo info = m_DelayedKicks.first();
   852 		m_DelayedKicks.pop();
   853 
   854 		CPlayer *player = g_Players.GetPlayerByIndex(info.client);
   855 		if (player == NULL || player->GetUserId() != info.userid)
   856 		{
   857 			continue;
   858 		}
   859 
   860 		player->Kick(info.buffer);
   861 	}
   862 }
   863 
   864 edict_t *CHalfLife2::EdictOfIndex(int index)
   865 {
   866 	return ::PEntityOfEntIndex(index);
   867 }
   868 
   869 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
   870 {
   871 	return ::IndexOfEdict(pEnt);
   872 }
   873 
   874 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
   875 {
   876 	if (!hndl.IsValid())
   877 	{
   878 		return NULL;
   879 	}
   880 
   881 	int index = hndl.GetEntryIndex();
   882 
   883 	edict_t *pStoredEdict;
   884 	CBaseEntity *pStoredEntity;
   885 
   886 	if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
   887 	{
   888 		return NULL;
   889 	}
   890 
   891 	if (pStoredEdict == NULL || pStoredEntity == NULL)
   892 	{
   893 		return NULL;
   894 	}
   895 
   896 	IServerEntity *pSE = pStoredEdict->GetIServerEntity();
   897 
   898 	if (pSE == NULL)
   899 	{
   900 		return NULL;
   901 	}
   902 
   903 	if (pSE->GetRefEHandle() != hndl)
   904 	{
   905 		return NULL;
   906 	}
   907 
   908 	return pStoredEdict;
   909 }
   910 
   911 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
   912 {
   913 	IServerEntity *pEntOther = pEnt->GetIServerEntity();
   914 
   915 	if (pEntOther == NULL)
   916 	{
   917 		return;
   918 	}
   919 
   920 	hndl.Set(pEntOther);
   921 }
   922 
   923 const char *CHalfLife2::GetCurrentMap()
   924 {
   925 	return STRING(gpGlobals->mapname);
   926 }
   927 
   928 void CHalfLife2::ServerCommand(const char *buffer)
   929 {
   930 	engine->ServerCommand(buffer);
   931 }
   932 
   933 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
   934 {
   935 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
   936 	CBaseHandle hndl = pUnknown->GetRefEHandle();
   937 	return (hndl.ToInt() | (1<<31));
   938 }
   939 
   940 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
   941 {
   942 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
   943 	{
   944 		return NULL;
   945 	}
   946 
   947 	CEntInfo *pInfo = NULL;
   948 
   949 	if (entRef & (1<<31))
   950 	{
   951 		/* Proper ent reference */
   952 		int hndlValue = entRef & ~(1<<31);
   953 		CBaseHandle hndl(hndlValue);
   954 
   955 		pInfo = LookupEntity(hndl.GetEntryIndex());
   956 		if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
   957 		{
   958 			return NULL;
   959 		}
   960 	}
   961 	else
   962 	{
   963 		/* Old style index only */
   964 		pInfo = LookupEntity(entRef);
   965 	}
   966 
   967 	if (!pInfo)
   968 	{
   969 		return NULL;
   970 	}
   971 
   972 	IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
   973 	if (pUnk)
   974 	{
   975 		return pUnk->GetBaseEntity();
   976 	}
   977 
   978 	return NULL;
   979 }
   980 
   981 /**
   982  * Retrieves the CEntInfo pointer from g_EntList for a given entity index
   983  */
   984 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
   985 {
   986 	// Make sure that our index is within the bounds of the global ent array
   987 	if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
   988 	{
   989 		return NULL;
   990 	}
   991 
   992 	if (!g_EntList || entInfoOffset == -1)
   993 	{
   994 		/* Attempt to use engine interface instead */
   995 		static CEntInfo tempInfo;
   996 		tempInfo.m_pNext = NULL;
   997 		tempInfo.m_pPrev = NULL;
   998 
   999 		edict_t *pEdict = PEntityOfEntIndex(entIndex);
  1000 
  1001 		if (!pEdict)
  1002 		{
  1003 			return NULL;
  1004 		}
  1005 
  1006 		IServerUnknown *pUnk = pEdict->GetUnknown();
  1007 
  1008 		if (!pUnk)
  1009 		{
  1010 			return NULL;
  1011 		}
  1012 
  1013 		tempInfo.m_pEntity = pUnk;
  1014 		tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
  1015 
  1016 		return &tempInfo;
  1017 	}
  1018 
  1019 	CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
  1020 	return &pArray[entIndex];
  1021 }
  1022 
  1023 /**
  1024 	SERIAL_MASK = 0x7fff (15 bits)
  1025 
  1026 	#define	MAX_EDICT_BITS				11
  1027 	#define NUM_ENT_ENTRY_BITS		(MAX_EDICT_BITS + 1)
  1028 	m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS); 
  1029 	
  1030 	Top 5 bits of a handle are unused.
  1031 	Bit 31 - Our 'reference' flag indicator
  1032 */
  1033 
  1034 cell_t CHalfLife2::IndexToReference(int entIndex)
  1035 {
  1036 	CBaseEntity *pEnt = ReferenceToEntity(entIndex);
  1037 	if (!pEnt)
  1038 	{
  1039 		return INVALID_EHANDLE_INDEX;
  1040 	}
  1041 
  1042 	return EntityToReference(pEnt);
  1043 }
  1044 
  1045 int CHalfLife2::ReferenceToIndex(cell_t entRef)
  1046 {
  1047 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
  1048 	{
  1049 		return INVALID_EHANDLE_INDEX;
  1050 	}
  1051 
  1052 	if (entRef & (1<<31))
  1053 	{
  1054 		/* Proper ent reference */
  1055 		int hndlValue = entRef & ~(1<<31);
  1056 		CBaseHandle hndl(hndlValue);
  1057 
  1058 		CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
  1059 
  1060 		if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
  1061 		{
  1062 			return INVALID_EHANDLE_INDEX;
  1063 		}
  1064 
  1065 		return hndl.GetEntryIndex();
  1066 	}
  1067 
  1068 	return entRef;
  1069 }
  1070 
  1071 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
  1072 {
  1073 	if (pEntity == NULL)
  1074 	{
  1075 		return INVALID_EHANDLE_INDEX;
  1076 	}
  1077 
  1078 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
  1079 	CBaseHandle hndl = pUnknown->GetRefEHandle();
  1080 
  1081 	if (hndl == INVALID_EHANDLE_INDEX)
  1082 	{
  1083 		return INVALID_EHANDLE_INDEX;
  1084 	}
  1085 	
  1086 	if (hndl.GetEntryIndex() >= MAX_EDICTS)
  1087 	{
  1088 		return (hndl.ToInt() | (1<<31));
  1089 	}
  1090 	else
  1091 	{
  1092 		return hndl.GetEntryIndex();
  1093 	}
  1094 }
  1095 
  1096 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
  1097 {
  1098 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
  1099 	{
  1100 		return INVALID_EHANDLE_INDEX;
  1101 	}
  1102 
  1103 	int hndlValue = entRef & ~(1<<31);
  1104 	CBaseHandle hndl(hndlValue);
  1105 
  1106 	if (hndl.GetEntryIndex() < MAX_EDICTS)
  1107 	{
  1108 		return hndl.GetEntryIndex();
  1109 	}
  1110 
  1111 	return entRef;
  1112 }
  1113 
  1114 void *CHalfLife2::GetGlobalEntityList()
  1115 {
  1116 	return g_EntList;
  1117 }
  1118 
  1119 int CHalfLife2::GetSendPropOffset(SendProp *prop)
  1120 {
  1121 	return prop->GetOffset();
  1122 }
  1123 
  1124 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
  1125 {
  1126 	if (pEdict == NULL || pEdict->IsFree())
  1127 	{
  1128 		return NULL;
  1129 	}
  1130 	
  1131 	IServerUnknown *pUnk = pEdict->GetUnknown();
  1132 	if (pUnk == NULL)
  1133 	{
  1134 		return NULL;
  1135 	}
  1136 	
  1137 	CBaseEntity * pEntity = pUnk->GetBaseEntity();
  1138 	
  1139 	if (pEntity == NULL)
  1140 	{
  1141 		return NULL;
  1142 	}
  1143 	
  1144 	return GetEntityClassname(pEntity);
  1145 }
  1146 
  1147 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
  1148 {
  1149 	static int offset = -1;
  1150 	if (offset == -1)
  1151 	{
  1152 		CBaseEntity *pGetterEnt = ReferenceToEntity(0);
  1153 		datamap_t *pMap = GetDataMap(pGetterEnt);
  1154 		typedescription_t *pDesc = FindInDataMap(pMap, "m_iClassname");
  1155 		offset = GetTypeDescOffs(pDesc);
  1156 	}
  1157 
  1158 	return *(const char **)(((unsigned char *)pEntity) + offset);
  1159 }
  1160 
  1161 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1162 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
  1163 {
  1164 	static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
  1165 	if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
  1166 		return false;
  1167 
  1168 	static size_t helperCmdLen = strlen(pHelperCmd->GetName());
  1169 
  1170 	CUtlVector<CUtlString> results;
  1171 	pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
  1172 	if (results.Count() == 0)
  1173 		return false;
  1174 
  1175 	// Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
  1176 	// so skip ahead to start of map path/name
  1177 
  1178 	// Like the engine, we're only going to deal with the first match.
  1179 
  1180 	strncopy(outFullname, &results[0][helperCmdLen + 1], size);
  1181 
  1182 	return true;
  1183 }
  1184 #endif
  1185 
  1186 bool CHalfLife2::IsMapValid(const char *map)
  1187 {
  1188 	bool ret = engine->IsMapValid(map);
  1189 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1190 	if (!ret)
  1191 	{
  1192 		static char szFuzzyName[PLATFORM_MAX_PATH];
  1193 		if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
  1194 		{
  1195 			ret = engine->IsMapValid(szFuzzyName);
  1196 		}
  1197 	}
  1198 #endif
  1199 	return ret;
  1200 }