3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
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>
41 #include "LibrarySys.h"
42 #include "logic_bridge.h"
43 #include <tier0/mem.h>
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>
52 typedef ICommandLine *(*FakeGetCommandLine)();
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_HL2DM || SOURCE_ENGINE == SE_DODS || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_TF2 || SOURCE_ENGINE == SE_LEFT4DEAD2
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"
68 #define TIER0_NAME "tier0_i486.so"
69 #define VSTDLIB_NAME "vstdlib_i486.so"
74 ConVar *sv_lan = NULL;
76 static void *g_EntList = NULL;
77 static int entInfoOffset = -1;
82 int HashFunction<datamap_t *>(datamap_t * const &k)
84 return reinterpret_cast<int>(k);
88 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
94 CHalfLife2::CHalfLife2()
96 m_pClasses = sm_trie_create();
99 CHalfLife2::~CHalfLife2()
101 sm_trie_destroy(m_pClasses);
103 List<DataTableInfo *>::iterator iter;
104 DataTableInfo *pInfo;
105 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
113 THash<datamap_t *, DataMapTrie>::iterator h_iter;
114 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
116 if (h_iter->val.trie)
118 delete h_iter->val.trie;
119 h_iter->val.trie = NULL;
126 #if SOURCE_ENGINE != SE_DARKMESSIAH
127 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
130 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
131 bool is_original_engine = false;
134 void CHalfLife2::OnSourceModStartup(bool late)
136 #if SOURCE_ENGINE != SE_DARKMESSIAH
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)
142 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
145 is_original_engine = true;
147 else if (g_pSharedChangeInfo == NULL)
149 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
154 void CHalfLife2::OnSourceModAllInitialized()
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 sharesys->AddInterface(NULL, this);
163 void CHalfLife2::OnSourceModAllInitialized_Post()
165 InitLogicalEntData();
169 void CHalfLife2::InitLogicalEntData()
174 * gEntList and/or g_pEntityList
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
180 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
182 #if !defined PLATFORM_WINDOWS
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");
191 g_EntList = reinterpret_cast<void *>(addr);
192 #if !defined PLATFORM_WINDOWS
200 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
202 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
208 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
213 if (!g_pGameConf->GetOffset("gEntList", &offset))
215 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
219 g_EntList = *reinterpret_cast<void **>(addr + offset);
224 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
228 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
230 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
235 void CHalfLife2::InitCommandLine()
237 char path[PLATFORM_MAX_PATH];
240 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
242 if (!g_LibSys.IsPathFile(path))
244 g_Logger.LogError("Could not find path for: " TIER0_NAME);
248 ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
249 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
251 /* '_Tier0' dropped on Alien Swarm version */
252 if (m_pGetCommandLine == NULL)
254 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
257 if (m_pGetCommandLine == NULL)
259 /* We probably have a Ship engine. */
261 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
262 if (!g_LibSys.IsPathFile(path))
264 g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
268 if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
270 g_Logger.LogError("Could not load %s: %s", path, error);
274 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
276 if (m_pGetCommandLine == NULL)
278 g_Logger.LogError("Could not locate any command line functionality");
285 ICommandLine *CHalfLife2::GetValveCommandLine()
287 if (!m_pGetCommandLine)
290 return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
293 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
294 bool CHalfLife2::IsOriginalEngine()
296 return is_original_engine;
300 #if SOURCE_ENGINE != SE_DARKMESSIAH
301 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
303 #if SOURCE_ENGINE == SE_DOTA
304 return engine->GetChangeAccessor( IndexOfEdict((const edict_t *)this) );
306 return engine->GetChangeAccessor( (const edict_t *)this );
311 bool UTIL_FindInSendTable(SendTable *pTable,
313 sm_sendprop_info_t *info,
317 int props = pTable->GetNumProps();
320 for (int i=0; i<props; i++)
322 prop = pTable->GetProp(i);
323 pname = prop->GetName();
324 if (pname && strcmp(name, pname) == 0)
327 info->actual_offset = offset + info->prop->GetOffset();
330 if (prop->GetDataTable())
332 if (UTIL_FindInSendTable(prop->GetDataTable(),
335 offset + prop->GetOffset())
346 bool UTIL_FindDataMapInfo(datamap_t *pMap, const char *name, sm_datatable_info_t *pDataTable)
350 for (int i = 0; i < pMap->dataNumFields; ++i)
352 if (pMap->dataDesc[i].fieldName == NULL)
356 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
358 pDataTable->prop = &(pMap->dataDesc[i]);
359 pDataTable->actual_offset = GetTypeDescOffs(pDataTable->prop);
362 if (pMap->dataDesc[i].td == NULL || !UTIL_FindDataMapInfo(pMap->dataDesc[i].td, name, pDataTable))
367 pDataTable->actual_offset += GetTypeDescOffs(&(pMap->dataDesc[i]));
371 pMap = pMap->baseMap;
377 ServerClass *CHalfLife2::FindServerClass(const char *classname)
379 DataTableInfo *pInfo = _FindServerClass(classname);
389 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
391 DataTableInfo *pInfo = NULL;
393 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
395 ServerClass *sc = gamedll->GetAllServerClasses();
398 if (strcmp(classname, sc->GetName()) == 0)
400 pInfo = new DataTableInfo;
402 sm_trie_insert(m_pClasses, classname, pInfo);
403 m_Tables.push_back(pInfo);
417 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
419 DataTableInfo *pInfo;
420 sm_sendprop_info_t *prop;
422 if ((pInfo = _FindServerClass(classname)) == NULL)
427 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
429 sm_sendprop_info_t temp_info;
431 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
436 pInfo->lookup.insert(offset, temp_info);
447 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
449 sm_sendprop_info_t info;
451 if (!FindSendPropInfo(classname, offset, &info))
459 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
461 sm_datatable_info_t dt_info;
463 if (!(this->FindDataMapInfo(pMap, offset, &dt_info)))
471 bool CHalfLife2::FindDataMapInfo(datamap_t *pMap, const char *offset, sm_datatable_info_t *pDataTable)
473 DataMapTrie &val = m_Maps[pMap];
477 val.trie = new KTrie<sm_datatable_info_t>;
480 sm_datatable_info_t * pNewTable = val.trie->retrieve(offset);
484 if (UTIL_FindDataMapInfo(pMap, offset, pDataTable))
486 val.trie->insert(offset, *pDataTable);
490 pDataTable->prop = NULL;
495 *pDataTable = *pNewTable;
498 return (pDataTable->prop != NULL);
501 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
503 #if SOURCE_ENGINE != SE_DARKMESSIAH
504 if (g_pSharedChangeInfo != NULL)
508 pEdict->StateChanged(offset);
512 pEdict->StateChanged();
518 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
522 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
524 #ifndef USE_PROTOBUF_USERMESSAGES
525 bf_write *pBitBuf = NULL;
527 cell_t players[] = {client};
529 if (dest == HUD_PRINTTALK)
531 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
533 /* Use SayText user message instead */
534 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
537 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
539 #if SOURCE_ENGINE == SE_DOTA
540 CUserMsg_SayText *pMsg;
541 if ((pMsg = (CUserMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
547 pMsg->set_text(buffer);
548 pMsg->set_chat(false);
549 #elif SOURCE_ENGINE == SE_CSGO
550 CCSUsrMsg_SayText *pMsg;
551 if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
556 pMsg->set_ent_idx(0);
557 pMsg->set_text(buffer);
558 pMsg->set_chat(false);
560 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
565 pBitBuf->WriteByte(0);
566 pBitBuf->WriteString(buffer);
567 pBitBuf->WriteByte(1);
570 g_UserMsgs.EndMessage();
576 #if SOURCE_ENGINE == SE_DOTA
577 CUserMsg_TextMsg *pMsg;
578 if ((pMsg = (CUserMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
583 pMsg->set_dest(dest);
584 pMsg->add_param(msg);
589 #elif SOURCE_ENGINE == SE_CSGO
590 CCSUsrMsg_TextMsg *pMsg;
591 if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
596 // Client tries to read all 5 'params' and will crash if less
597 pMsg->set_msg_dst(dest);
598 pMsg->add_params(msg);
599 pMsg->add_params("");
600 pMsg->add_params("");
601 pMsg->add_params("");
602 pMsg->add_params("");
604 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
609 pBitBuf->WriteByte(dest);
610 pBitBuf->WriteString(msg);
613 g_UserMsgs.EndMessage();
618 bool CHalfLife2::HintTextMsg(int client, const char *msg)
620 cell_t players[] = {client};
622 #if SOURCE_ENGINE == SE_DOTA
623 CUserMsg_HintText *pMsg;
624 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
629 pMsg->set_message(msg);
630 #elif SOURCE_ENGINE == SE_CSGO
631 CCSUsrMsg_HintText *pMsg;
632 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
639 bf_write *pBitBuf = NULL;
641 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
646 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
647 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
649 pBitBuf->WriteByte(1);
651 pBitBuf->WriteString(msg);
653 g_UserMsgs.EndMessage();
658 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
660 #if SOURCE_ENGINE == SE_DOTA
661 CUserMsg_HintText *pMsg;
662 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
667 pMsg->set_message(msg);
668 #elif SOURCE_ENGINE == SE_CSGO
669 CCSUsrMsg_HintText *pMsg;
670 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
677 bf_write *pBitBuf = NULL;
679 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
684 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
685 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
687 pBitBuf->WriteByte(1);
689 pBitBuf->WriteString(msg);
692 g_UserMsgs.EndMessage();
697 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
699 KeyValues *SubKey = NULL;
701 cell_t players[] = {client};
703 #if SOURCE_ENGINE == SE_DOTA
704 CUserMsg_VGUIMenu *pMsg;
705 if ((pMsg = (CUserMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
709 #elif SOURCE_ENGINE == SE_CSGO
710 CCSUsrMsg_VGUIMenu *pMsg;
711 if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
716 bf_write *pBitBuf = NULL;
717 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
725 SubKey = data->GetFirstSubKey();
729 SubKey = SubKey->GetNextKey();
731 SubKey = data->GetFirstSubKey();
734 #if SOURCE_ENGINE == SE_DOTA
735 pMsg->set_name(name);
736 pMsg->set_show(show);
740 CUserMsg_VGUIMenu_Keys *key = pMsg->add_keys();
741 key->set_name(SubKey->GetName());
742 key->set_value(SubKey->GetString());
743 SubKey = SubKey->GetNextKey();
745 #elif SOURCE_ENGINE == SE_CSGO
746 pMsg->set_name(name);
747 pMsg->set_show(show);
751 CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
752 key->set_name(SubKey->GetName());
753 key->set_str(SubKey->GetString());
754 SubKey = SubKey->GetNextKey();
757 pBitBuf->WriteString(name);
758 pBitBuf->WriteByte((show) ? 1 : 0);
759 pBitBuf->WriteByte(count);
762 pBitBuf->WriteString(SubKey->GetName());
763 pBitBuf->WriteString(SubKey->GetString());
764 SubKey = SubKey->GetNextKey();
768 g_UserMsgs.EndMessage();
773 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
775 DelayedFakeCliCmd *pFake;
777 if (m_FreeCmds.empty())
779 pFake = new DelayedFakeCliCmd;
781 pFake = m_FreeCmds.front();
785 pFake->client = client;
786 pFake->userid = userid;
787 pFake->cmd.assign(cmd);
789 m_CmdQueue.push(pFake);
792 void CHalfLife2::ProcessFakeCliCmdQueue()
794 while (!m_CmdQueue.empty())
796 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
798 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
800 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
801 #if SOURCE_ENGINE == SE_DOTA
802 engine->ClientCommand(pPlayer->GetIndex(), "%s", pFake->cmd.c_str());
804 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
812 bool CHalfLife2::IsLANServer()
814 sv_lan = icvar->FindVar("sv_lan");
821 return (sv_lan->GetInt() != 0);
824 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
826 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
827 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
829 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
834 Assert(_heapchk() == _HEAPOK);
837 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
841 // load file into a null-terminated buffer
842 int fileSize = filesystem->Size(f);
843 char *buffer = (char *)MemAllocScratch(fileSize + 1);
847 filesystem->Read(buffer, fileSize, f); // read into local buffer
849 buffer[fileSize] = 0; // null terminate file as EOF
851 filesystem->Close( f ); // close file after reading
853 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
861 return kv->LoadFromFile(filesystem, resourceName, pathID);
865 void CHalfLife2::PushCommandStack(const CCommand *cmd)
867 CachedCommandInfo info;
870 #if SOURCE_ENGINE <= SE_DARKMESSIAH
871 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
874 m_CommandStack.push(info);
877 const CCommand *CHalfLife2::PeekCommandStack()
879 if (m_CommandStack.empty())
884 return m_CommandStack.front().args;
887 void CHalfLife2::PopCommandStack()
889 m_CommandStack.pop();
892 const char *CHalfLife2::CurrentCommandName()
894 #if SOURCE_ENGINE >= SE_ORANGEBOX
895 return m_CommandStack.front().args->Arg(0);
897 return m_CommandStack.front().cmd;
901 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
903 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
904 if (!pPlayer || !pPlayer->IsConnected() || pPlayer->IsInKickQueue())
909 pPlayer->MarkAsBeingKicked();
911 DelayedKickInfo kick;
913 kick.client = client;
914 kick.userid = userid;
915 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
917 m_DelayedKicks.push(kick);
920 void CHalfLife2::ProcessDelayedKicks()
922 while (!m_DelayedKicks.empty())
924 DelayedKickInfo info = m_DelayedKicks.first();
925 m_DelayedKicks.pop();
927 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
928 if (player == NULL || player->GetUserId() != info.userid)
933 player->Kick(info.buffer);
937 edict_t *CHalfLife2::EdictOfIndex(int index)
939 return ::PEntityOfEntIndex(index);
942 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
944 return ::IndexOfEdict(pEnt);
947 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
954 int index = hndl.GetEntryIndex();
956 edict_t *pStoredEdict;
957 CBaseEntity *pStoredEntity;
959 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
964 if (pStoredEdict == NULL || pStoredEntity == NULL)
969 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
976 if (pSE->GetRefEHandle() != hndl)
984 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
986 IServerEntity *pEntOther = pEnt->GetIServerEntity();
988 if (pEntOther == NULL)
996 const char *CHalfLife2::GetCurrentMap()
998 return STRING(gpGlobals->mapname);
1001 void CHalfLife2::ServerCommand(const char *buffer)
1003 engine->ServerCommand(buffer);
1006 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
1008 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1009 CBaseHandle hndl = pUnknown->GetRefEHandle();
1010 return (hndl.ToInt() | (1<<31));
1013 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
1015 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1020 CEntInfo *pInfo = NULL;
1022 if (entRef & (1<<31))
1024 /* Proper ent reference */
1025 int hndlValue = entRef & ~(1<<31);
1026 CBaseHandle hndl(hndlValue);
1028 pInfo = LookupEntity(hndl.GetEntryIndex());
1029 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
1036 /* Old style index only */
1037 pInfo = LookupEntity(entRef);
1045 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
1048 return pUnk->GetBaseEntity();
1055 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
1057 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
1059 // Make sure that our index is within the bounds of the global ent array
1060 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
1065 if (!g_EntList || entInfoOffset == -1)
1067 /* Attempt to use engine interface instead */
1068 static CEntInfo tempInfo;
1069 tempInfo.m_pNext = NULL;
1070 tempInfo.m_pPrev = NULL;
1072 edict_t *pEdict = PEntityOfEntIndex(entIndex);
1079 IServerUnknown *pUnk = pEdict->GetUnknown();
1086 tempInfo.m_pEntity = pUnk;
1087 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
1092 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
1093 return &pArray[entIndex];
1097 SERIAL_MASK = 0x7fff (15 bits)
1099 #define MAX_EDICT_BITS 11
1100 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
1101 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
1103 Top 5 bits of a handle are unused.
1104 Bit 31 - Our 'reference' flag indicator
1107 cell_t CHalfLife2::IndexToReference(int entIndex)
1109 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
1112 return INVALID_EHANDLE_INDEX;
1115 return EntityToReference(pEnt);
1118 int CHalfLife2::ReferenceToIndex(cell_t entRef)
1120 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1122 return INVALID_EHANDLE_INDEX;
1125 if (entRef & (1<<31))
1127 /* Proper ent reference */
1128 int hndlValue = entRef & ~(1<<31);
1129 CBaseHandle hndl(hndlValue);
1131 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
1133 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
1135 return INVALID_EHANDLE_INDEX;
1138 return hndl.GetEntryIndex();
1144 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
1146 if (pEntity == NULL)
1148 return INVALID_EHANDLE_INDEX;
1151 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1152 CBaseHandle hndl = pUnknown->GetRefEHandle();
1154 if (hndl == INVALID_EHANDLE_INDEX)
1156 return INVALID_EHANDLE_INDEX;
1159 if (hndl.GetEntryIndex() >= MAX_EDICTS)
1161 return (hndl.ToInt() | (1<<31));
1165 return hndl.GetEntryIndex();
1169 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
1171 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1173 return INVALID_EHANDLE_INDEX;
1176 int hndlValue = entRef & ~(1<<31);
1177 CBaseHandle hndl(hndlValue);
1179 if (hndl.GetEntryIndex() < MAX_EDICTS)
1181 return hndl.GetEntryIndex();
1187 void *CHalfLife2::GetGlobalEntityList()
1192 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1194 return prop->GetOffset();
1197 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
1199 if (pEdict == NULL || pEdict->IsFree())
1204 IServerUnknown *pUnk = pEdict->GetUnknown();
1210 CBaseEntity * pEntity = pUnk->GetBaseEntity();
1212 if (pEntity == NULL)
1217 return GetEntityClassname(pEntity);
1220 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
1222 static int offset = -1;
1225 CBaseEntity *pGetterEnt = ReferenceToEntity(0);
1226 datamap_t *pMap = GetDataMap(pGetterEnt);
1228 sm_datatable_info_t info;
1229 if (!FindDataMapInfo(pMap, "m_iClassname", &info))
1234 offset = info.actual_offset;
1237 return *(const char **)(((unsigned char *)pEntity) + offset);
1240 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1241 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
1243 static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
1244 if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
1247 static size_t helperCmdLen = strlen(pHelperCmd->GetName());
1249 CUtlVector<CUtlString> results;
1250 pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
1251 if (results.Count() == 0)
1254 // Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
1255 // so skip ahead to start of map path/name
1257 // Like the engine, we're only going to deal with the first match.
1259 strncopy(outFullname, &results[0][helperCmdLen + 1], size);
1265 bool CHalfLife2::IsMapValid(const char *map)
1267 if (!map || !map[0])
1270 bool ret = engine->IsMapValid(map);
1271 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1274 static char szFuzzyName[PLATFORM_MAX_PATH];
1275 if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
1277 ret = engine->IsMapValid(szFuzzyName);