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