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