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