Fixed IsMapValid passing blank string to engine's IsMapValid which crashes some games.
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_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"
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 sm_trie_destroy(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 g_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 return engine->GetChangeAccessor( (const edict_t *)this );
307 bool UTIL_FindInSendTable(SendTable *pTable,
309 sm_sendprop_info_t *info,
313 int props = pTable->GetNumProps();
316 for (int i=0; i<props; i++)
318 prop = pTable->GetProp(i);
319 pname = prop->GetName();
320 if (pname && strcmp(name, pname) == 0)
323 info->actual_offset = offset + info->prop->GetOffset();
326 if (prop->GetDataTable())
328 if (UTIL_FindInSendTable(prop->GetDataTable(),
331 offset + prop->GetOffset())
342 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name, bool *isNested)
351 for (int i=0; i<pMap->dataNumFields; i++)
353 if (pMap->dataDesc[i].fieldName == NULL)
357 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
359 return &(pMap->dataDesc[i]);
361 if (pMap->dataDesc[i].td)
365 *isNested = (UTIL_FindInDataMap(pMap->dataDesc[i].td, name, NULL) != NULL);
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)
381 pMap = pMap->baseMap;
387 ServerClass *CHalfLife2::FindServerClass(const char *classname)
389 DataTableInfo *pInfo = _FindServerClass(classname);
399 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
401 DataTableInfo *pInfo = NULL;
403 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
405 ServerClass *sc = gamedll->GetAllServerClasses();
408 if (strcmp(classname, sc->GetName()) == 0)
410 pInfo = new DataTableInfo;
412 sm_trie_insert(m_pClasses, classname, pInfo);
413 m_Tables.push_back(pInfo);
427 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
429 DataTableInfo *pInfo;
430 sm_sendprop_info_t *prop;
432 if ((pInfo = _FindServerClass(classname)) == NULL)
437 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
439 sm_sendprop_info_t temp_info;
441 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
446 pInfo->lookup.insert(offset, temp_info);
457 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
459 sm_sendprop_info_t info;
461 if (!FindSendPropInfo(classname, offset, &info))
469 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
471 return this->FindInDataMap(pMap, offset, NULL);
474 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset, bool *isNested)
476 typedescription_t *td = NULL;
477 DataMapTrie &val = m_Maps[pMap];
481 val.trie = sm_trie_create();
483 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
485 if ((td = UTIL_FindInDataMap(pMap, offset, isNested)) != NULL)
487 sm_trie_insert(val.trie, offset, td);
494 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
496 #if SOURCE_ENGINE != SE_DARKMESSIAH
497 if (g_pSharedChangeInfo != NULL)
501 pEdict->StateChanged(offset);
505 pEdict->StateChanged();
511 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
515 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
517 #ifndef USE_PROTOBUF_USERMESSAGES
518 bf_write *pBitBuf = NULL;
520 cell_t players[] = {client};
522 if (dest == HUD_PRINTTALK)
524 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
526 /* Use SayText user message instead */
527 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
530 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
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)
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)
549 pMsg->set_ent_idx(0);
550 pMsg->set_text(buffer);
551 pMsg->set_chat(false);
553 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
558 pBitBuf->WriteByte(0);
559 pBitBuf->WriteString(buffer);
560 pBitBuf->WriteByte(1);
563 g_UserMsgs.EndMessage();
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)
576 pMsg->set_dest(dest);
577 pMsg->add_param(msg);
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)
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("");
597 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
602 pBitBuf->WriteByte(dest);
603 pBitBuf->WriteString(msg);
606 g_UserMsgs.EndMessage();
611 bool CHalfLife2::HintTextMsg(int client, const char *msg)
613 cell_t players[] = {client};
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)
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)
632 bf_write *pBitBuf = NULL;
634 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
639 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
640 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
642 pBitBuf->WriteByte(1);
644 pBitBuf->WriteString(msg);
646 g_UserMsgs.EndMessage();
651 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
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)
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)
670 bf_write *pBitBuf = NULL;
672 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
677 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
678 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
680 pBitBuf->WriteByte(1);
682 pBitBuf->WriteString(msg);
685 g_UserMsgs.EndMessage();
690 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
692 KeyValues *SubKey = NULL;
694 cell_t players[] = {client};
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)
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)
709 bf_write *pBitBuf = NULL;
710 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
718 SubKey = data->GetFirstSubKey();
722 SubKey = SubKey->GetNextKey();
724 SubKey = data->GetFirstSubKey();
727 #if SOURCE_ENGINE == SE_DOTA
728 pMsg->set_name(name);
729 pMsg->set_show(show);
733 CUserMsg_VGUIMenu_Keys *key = pMsg->add_keys();
734 key->set_name(SubKey->GetName());
735 key->set_value(SubKey->GetString());
736 SubKey = SubKey->GetNextKey();
738 #elif SOURCE_ENGINE == SE_CSGO
739 pMsg->set_name(name);
740 pMsg->set_show(show);
744 CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
745 key->set_name(SubKey->GetName());
746 key->set_str(SubKey->GetString());
747 SubKey = SubKey->GetNextKey();
750 pBitBuf->WriteString(name);
751 pBitBuf->WriteByte((show) ? 1 : 0);
752 pBitBuf->WriteByte(count);
755 pBitBuf->WriteString(SubKey->GetName());
756 pBitBuf->WriteString(SubKey->GetString());
757 SubKey = SubKey->GetNextKey();
761 g_UserMsgs.EndMessage();
766 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
768 DelayedFakeCliCmd *pFake;
770 if (m_FreeCmds.empty())
772 pFake = new DelayedFakeCliCmd;
774 pFake = m_FreeCmds.front();
778 pFake->client = client;
779 pFake->userid = userid;
780 pFake->cmd.assign(cmd);
782 m_CmdQueue.push(pFake);
785 void CHalfLife2::ProcessFakeCliCmdQueue()
787 while (!m_CmdQueue.empty())
789 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
791 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
793 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
794 #if SOURCE_ENGINE == SE_DOTA
795 engine->ClientCommand(pPlayer->GetEdict(), "%s", pFake->cmd.c_str());
797 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
805 bool CHalfLife2::IsLANServer()
807 sv_lan = icvar->FindVar("sv_lan");
814 return (sv_lan->GetInt() != 0);
817 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
819 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
820 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
822 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
827 Assert(_heapchk() == _HEAPOK);
830 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
834 // load file into a null-terminated buffer
835 int fileSize = filesystem->Size(f);
836 char *buffer = (char *)MemAllocScratch(fileSize + 1);
840 filesystem->Read(buffer, fileSize, f); // read into local buffer
842 buffer[fileSize] = 0; // null terminate file as EOF
844 filesystem->Close( f ); // close file after reading
846 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
854 return kv->LoadFromFile(filesystem, resourceName, pathID);
858 void CHalfLife2::PushCommandStack(const CCommand *cmd)
860 CachedCommandInfo info;
863 #if SOURCE_ENGINE <= SE_DARKMESSIAH
864 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
867 m_CommandStack.push(info);
870 const CCommand *CHalfLife2::PeekCommandStack()
872 if (m_CommandStack.empty())
877 return m_CommandStack.front().args;
880 void CHalfLife2::PopCommandStack()
882 m_CommandStack.pop();
885 const char *CHalfLife2::CurrentCommandName()
887 #if SOURCE_ENGINE >= SE_ORANGEBOX
888 return m_CommandStack.front().args->Arg(0);
890 return m_CommandStack.front().cmd;
894 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
896 DelayedKickInfo kick;
898 kick.client = client;
899 kick.userid = userid;
900 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
902 m_DelayedKicks.push(kick);
905 void CHalfLife2::ProcessDelayedKicks()
907 while (!m_DelayedKicks.empty())
909 DelayedKickInfo info = m_DelayedKicks.first();
910 m_DelayedKicks.pop();
912 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
913 if (player == NULL || player->GetUserId() != info.userid)
918 player->Kick(info.buffer);
922 edict_t *CHalfLife2::EdictOfIndex(int index)
924 return ::PEntityOfEntIndex(index);
927 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
929 return ::IndexOfEdict(pEnt);
932 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
939 int index = hndl.GetEntryIndex();
941 edict_t *pStoredEdict;
942 CBaseEntity *pStoredEntity;
944 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
949 if (pStoredEdict == NULL || pStoredEntity == NULL)
954 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
961 if (pSE->GetRefEHandle() != hndl)
969 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
971 IServerEntity *pEntOther = pEnt->GetIServerEntity();
973 if (pEntOther == NULL)
981 const char *CHalfLife2::GetCurrentMap()
983 return STRING(gpGlobals->mapname);
986 void CHalfLife2::ServerCommand(const char *buffer)
988 engine->ServerCommand(buffer);
991 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
993 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
994 CBaseHandle hndl = pUnknown->GetRefEHandle();
995 return (hndl.ToInt() | (1<<31));
998 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
1000 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1005 CEntInfo *pInfo = NULL;
1007 if (entRef & (1<<31))
1009 /* Proper ent reference */
1010 int hndlValue = entRef & ~(1<<31);
1011 CBaseHandle hndl(hndlValue);
1013 pInfo = LookupEntity(hndl.GetEntryIndex());
1014 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
1021 /* Old style index only */
1022 pInfo = LookupEntity(entRef);
1030 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
1033 return pUnk->GetBaseEntity();
1040 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
1042 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
1044 // Make sure that our index is within the bounds of the global ent array
1045 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
1050 if (!g_EntList || entInfoOffset == -1)
1052 /* Attempt to use engine interface instead */
1053 static CEntInfo tempInfo;
1054 tempInfo.m_pNext = NULL;
1055 tempInfo.m_pPrev = NULL;
1057 edict_t *pEdict = PEntityOfEntIndex(entIndex);
1064 IServerUnknown *pUnk = pEdict->GetUnknown();
1071 tempInfo.m_pEntity = pUnk;
1072 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
1077 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
1078 return &pArray[entIndex];
1082 SERIAL_MASK = 0x7fff (15 bits)
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);
1088 Top 5 bits of a handle are unused.
1089 Bit 31 - Our 'reference' flag indicator
1092 cell_t CHalfLife2::IndexToReference(int entIndex)
1094 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
1097 return INVALID_EHANDLE_INDEX;
1100 return EntityToReference(pEnt);
1103 int CHalfLife2::ReferenceToIndex(cell_t entRef)
1105 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1107 return INVALID_EHANDLE_INDEX;
1110 if (entRef & (1<<31))
1112 /* Proper ent reference */
1113 int hndlValue = entRef & ~(1<<31);
1114 CBaseHandle hndl(hndlValue);
1116 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
1118 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
1120 return INVALID_EHANDLE_INDEX;
1123 return hndl.GetEntryIndex();
1129 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
1131 if (pEntity == NULL)
1133 return INVALID_EHANDLE_INDEX;
1136 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1137 CBaseHandle hndl = pUnknown->GetRefEHandle();
1139 if (hndl == INVALID_EHANDLE_INDEX)
1141 return INVALID_EHANDLE_INDEX;
1144 if (hndl.GetEntryIndex() >= MAX_EDICTS)
1146 return (hndl.ToInt() | (1<<31));
1150 return hndl.GetEntryIndex();
1154 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
1156 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1158 return INVALID_EHANDLE_INDEX;
1161 int hndlValue = entRef & ~(1<<31);
1162 CBaseHandle hndl(hndlValue);
1164 if (hndl.GetEntryIndex() < MAX_EDICTS)
1166 return hndl.GetEntryIndex();
1172 void *CHalfLife2::GetGlobalEntityList()
1177 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1179 return prop->GetOffset();
1182 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
1184 if (pEdict == NULL || pEdict->IsFree())
1189 IServerUnknown *pUnk = pEdict->GetUnknown();
1195 CBaseEntity * pEntity = pUnk->GetBaseEntity();
1197 if (pEntity == NULL)
1202 return GetEntityClassname(pEntity);
1205 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
1207 static int offset = -1;
1210 CBaseEntity *pGetterEnt = ReferenceToEntity(0);
1211 datamap_t *pMap = GetDataMap(pGetterEnt);
1212 typedescription_t *pDesc = FindInDataMap(pMap, "m_iClassname");
1213 offset = GetTypeDescOffs(pDesc);
1216 return *(const char **)(((unsigned char *)pEntity) + offset);
1219 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1220 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
1222 static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
1223 if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
1226 static size_t helperCmdLen = strlen(pHelperCmd->GetName());
1228 CUtlVector<CUtlString> results;
1229 pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
1230 if (results.Count() == 0)
1233 // Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
1234 // so skip ahead to start of map path/name
1236 // Like the engine, we're only going to deal with the first match.
1238 strncopy(outFullname, &results[0][helperCmdLen + 1], size);
1244 bool CHalfLife2::IsMapValid(const char *map)
1246 if (!map || !map[0])
1249 bool ret = engine->IsMapValid(map);
1250 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1253 static char szFuzzyName[PLATFORM_MAX_PATH];
1254 if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
1256 ret = engine->IsMapValid(szFuzzyName);