2 * vim: set ts=4 sw=4 tw=99 noet :
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_SDK2013 || 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 void **g_pEntInfoList = NULL;
78 static int entInfoOffset = -1;
80 static CEntInfo *EntInfoArray()
82 if (g_EntList != NULL)
84 return (CEntInfo *)((intp)g_EntList + entInfoOffset);
86 else if (g_pEntInfoList)
88 return *(CEntInfo **)g_pEntInfoList;
94 CHalfLife2::CHalfLife2()
99 CHalfLife2::~CHalfLife2()
101 for (NameHashSet<DataTableInfo *>::iterator iter = m_Classes.iter(); !iter.empty(); iter.next())
104 for (DataTableMap::iterator iter = m_Maps.iter(); !iter.empty(); iter.next())
108 #if SOURCE_ENGINE != SE_DARKMESSIAH
109 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
112 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
113 bool is_original_engine = false;
116 void CHalfLife2::OnSourceModStartup(bool late)
118 #if SOURCE_ENGINE != SE_DARKMESSIAH
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)
124 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
127 is_original_engine = true;
129 else if (g_pSharedChangeInfo == NULL)
131 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
136 void CHalfLife2::OnSourceModAllInitialized()
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 sharesys->AddInterface(NULL, this);
145 void CHalfLife2::OnSourceModAllInitialized_Post()
147 InitLogicalEntData();
151 void CHalfLife2::InitLogicalEntData()
156 * gEntList and/or g_pEntityList
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
162 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
164 #if !defined PLATFORM_WINDOWS
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");
173 g_EntList = reinterpret_cast<void *>(addr);
174 #if !defined PLATFORM_WINDOWS
181 if (g_pGameConf->GetMemSig("LevelShutdown", (void **) &addr) && addr)
184 if (!g_pGameConf->GetOffset("gEntList", &offset))
186 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
190 g_EntList = *reinterpret_cast<void **>(addr + offset);
195 // If we have g_EntList from either of the above methods, make sure we can get the offset from it to EntInfo as well
196 if (g_EntList && !g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
198 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
203 // If we don't have g_EntList or have it but don't know where EntInfo is on it, use fallback.
204 if (!g_EntList || entInfoOffset == -1)
206 g_pGameConf->GetAddress("EntInfosPtr", (void **)&g_pEntInfoList);
209 if (!g_EntList && !g_pEntInfoList)
211 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
216 void CHalfLife2::InitCommandLine()
220 if (!is_original_engine)
222 ke::AutoPtr<ILibrary> lib(g_LibSys.OpenLibrary(TIER0_NAME, error, sizeof(error)));
225 g_Logger.LogError("Could not load %s: %s", TIER0_NAME, error);
229 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
231 /* '_Tier0' dropped on Alien Swarm version */
232 if (m_pGetCommandLine == NULL)
234 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
239 ke::AutoPtr<ILibrary> lib(g_LibSys.OpenLibrary(VSTDLIB_NAME, error, sizeof(error)));
242 g_Logger.LogError("Could not load %s: %s", VSTDLIB_NAME, error);
246 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
249 if (m_pGetCommandLine == NULL)
251 g_Logger.LogError("Could not locate any command line functionality");
255 ICommandLine *CHalfLife2::GetValveCommandLine()
257 if (!m_pGetCommandLine)
260 return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
263 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
264 bool CHalfLife2::IsOriginalEngine()
266 return is_original_engine;
270 #if SOURCE_ENGINE != SE_DARKMESSIAH
271 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
273 #if SOURCE_ENGINE == SE_DOTA
274 return engine->GetChangeAccessor( IndexOfEdict((const edict_t *)this) );
276 return engine->GetChangeAccessor( (const edict_t *)this );
281 bool UTIL_FindInSendTable(SendTable *pTable,
283 sm_sendprop_info_t *info,
287 int props = pTable->GetNumProps();
290 for (int i=0; i<props; i++)
292 prop = pTable->GetProp(i);
293 pname = prop->GetName();
294 if (pname && strcmp(name, pname) == 0)
297 info->actual_offset = offset + info->prop->GetOffset();
300 if (prop->GetDataTable())
302 if (UTIL_FindInSendTable(prop->GetDataTable(),
305 offset + prop->GetOffset())
316 bool UTIL_FindDataMapInfo(datamap_t *pMap, const char *name, sm_datatable_info_t *pDataTable)
320 for (int i = 0; i < pMap->dataNumFields; ++i)
322 if (pMap->dataDesc[i].fieldName == NULL)
326 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
328 pDataTable->prop = &(pMap->dataDesc[i]);
329 pDataTable->actual_offset = GetTypeDescOffs(pDataTable->prop);
332 if (pMap->dataDesc[i].td == NULL || !UTIL_FindDataMapInfo(pMap->dataDesc[i].td, name, pDataTable))
337 pDataTable->actual_offset += GetTypeDescOffs(&(pMap->dataDesc[i]));
341 pMap = pMap->baseMap;
347 ServerClass *CHalfLife2::FindServerClass(const char *classname)
349 DataTableInfo *pInfo = _FindServerClass(classname);
357 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
359 DataTableInfo *pInfo = NULL;
360 if (!m_Classes.retrieve(classname, &pInfo))
362 ServerClass *sc = gamedll->GetAllServerClasses();
365 if (strcmp(classname, sc->GetName()) == 0)
367 pInfo = new DataTableInfo(sc);
368 m_Classes.insert(classname, pInfo);
380 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
382 DataTableInfo *pInfo;
383 sm_sendprop_info_t *prop;
385 if ((pInfo = _FindServerClass(classname)) == NULL)
390 if (!pInfo->lookup.retrieve(offset, info))
392 sm_sendprop_info_t temp_info;
394 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
399 pInfo->lookup.insert(offset, temp_info);
406 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
408 sm_sendprop_info_t info;
410 if (!FindSendPropInfo(classname, offset, &info))
418 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
420 sm_datatable_info_t dt_info;
422 if (!(this->FindDataMapInfo(pMap, offset, &dt_info)))
430 bool CHalfLife2::FindDataMapInfo(datamap_t *pMap, const char *offset, sm_datatable_info_t *pDataTable)
432 DataTableMap::Insert i = m_Maps.findForAdd(pMap);
434 m_Maps.add(i, pMap, new DataMapCache());
436 DataMapCache *cache = i->value;
438 sm_datatable_info_t *pNewTable;
439 if (!cache->retrieve(offset, pDataTable))
441 if (!UTIL_FindDataMapInfo(pMap, offset, pDataTable))
443 cache->insert(offset, *pDataTable);
449 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
451 #if SOURCE_ENGINE != SE_DARKMESSIAH
452 if (g_pSharedChangeInfo != NULL)
456 pEdict->StateChanged(offset);
460 pEdict->StateChanged();
466 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
470 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
472 #ifndef USE_PROTOBUF_USERMESSAGES
473 bf_write *pBitBuf = NULL;
475 cell_t players[] = {client};
477 if (dest == HUD_PRINTTALK)
479 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
481 /* Use SayText user message instead */
482 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
485 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
487 #if SOURCE_ENGINE == SE_DOTA
488 CUserMsg_SayText *pMsg;
489 if ((pMsg = (CUserMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
495 pMsg->set_text(buffer);
496 pMsg->set_chat(false);
497 #elif SOURCE_ENGINE == SE_CSGO
498 CCSUsrMsg_SayText *pMsg;
499 if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
504 pMsg->set_ent_idx(0);
505 pMsg->set_text(buffer);
506 pMsg->set_chat(false);
508 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
513 pBitBuf->WriteByte(0);
514 pBitBuf->WriteString(buffer);
515 pBitBuf->WriteByte(1);
518 g_UserMsgs.EndMessage();
524 #if SOURCE_ENGINE == SE_DOTA
525 CUserMsg_TextMsg *pMsg;
526 if ((pMsg = (CUserMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
531 pMsg->set_dest(dest);
532 pMsg->add_param(msg);
537 #elif SOURCE_ENGINE == SE_CSGO
538 CCSUsrMsg_TextMsg *pMsg;
539 if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
544 // Client tries to read all 5 'params' and will crash if less
545 pMsg->set_msg_dst(dest);
546 pMsg->add_params(msg);
547 pMsg->add_params("");
548 pMsg->add_params("");
549 pMsg->add_params("");
550 pMsg->add_params("");
552 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
557 pBitBuf->WriteByte(dest);
558 pBitBuf->WriteString(msg);
561 g_UserMsgs.EndMessage();
566 bool CHalfLife2::HintTextMsg(int client, const char *msg)
568 cell_t players[] = {client};
570 #if SOURCE_ENGINE == SE_DOTA
571 CUserMsg_HintText *pMsg;
572 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
577 pMsg->set_message(msg);
578 #elif SOURCE_ENGINE == SE_CSGO
579 CCSUsrMsg_HintText *pMsg;
580 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
587 bf_write *pBitBuf = NULL;
589 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
594 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
595 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
597 pBitBuf->WriteByte(1);
599 pBitBuf->WriteString(msg);
601 g_UserMsgs.EndMessage();
606 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
608 #if SOURCE_ENGINE == SE_DOTA
609 CUserMsg_HintText *pMsg;
610 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
615 pMsg->set_message(msg);
616 #elif SOURCE_ENGINE == SE_CSGO
617 CCSUsrMsg_HintText *pMsg;
618 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
625 bf_write *pBitBuf = NULL;
627 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
632 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
633 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
635 pBitBuf->WriteByte(1);
637 pBitBuf->WriteString(msg);
640 g_UserMsgs.EndMessage();
645 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
647 KeyValues *SubKey = NULL;
649 cell_t players[] = {client};
651 #if SOURCE_ENGINE == SE_DOTA
652 CUserMsg_VGUIMenu *pMsg;
653 if ((pMsg = (CUserMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
657 #elif SOURCE_ENGINE == SE_CSGO
658 CCSUsrMsg_VGUIMenu *pMsg;
659 if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
664 bf_write *pBitBuf = NULL;
665 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
673 SubKey = data->GetFirstSubKey();
677 SubKey = SubKey->GetNextKey();
679 SubKey = data->GetFirstSubKey();
682 #if SOURCE_ENGINE == SE_DOTA
683 pMsg->set_name(name);
684 pMsg->set_show(show);
688 CUserMsg_VGUIMenu_Keys *key = pMsg->add_keys();
689 key->set_name(SubKey->GetName());
690 key->set_value(SubKey->GetString());
691 SubKey = SubKey->GetNextKey();
693 #elif SOURCE_ENGINE == SE_CSGO
694 pMsg->set_name(name);
695 pMsg->set_show(show);
699 CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
700 key->set_name(SubKey->GetName());
701 key->set_str(SubKey->GetString());
702 SubKey = SubKey->GetNextKey();
705 pBitBuf->WriteString(name);
706 pBitBuf->WriteByte((show) ? 1 : 0);
707 pBitBuf->WriteByte(count);
710 pBitBuf->WriteString(SubKey->GetName());
711 pBitBuf->WriteString(SubKey->GetString());
712 SubKey = SubKey->GetNextKey();
716 g_UserMsgs.EndMessage();
721 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
723 DelayedFakeCliCmd *pFake;
725 if (m_FreeCmds.empty())
727 pFake = new DelayedFakeCliCmd;
729 pFake = m_FreeCmds.front();
733 pFake->client = client;
734 pFake->userid = userid;
735 pFake->cmd.assign(cmd);
737 m_CmdQueue.push(pFake);
740 void CHalfLife2::ProcessFakeCliCmdQueue()
742 while (!m_CmdQueue.empty())
744 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
746 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
748 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
749 #if SOURCE_ENGINE == SE_DOTA
750 engine->ClientCommand(pPlayer->GetIndex(), "%s", pFake->cmd.c_str());
752 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
760 bool CHalfLife2::IsLANServer()
762 sv_lan = icvar->FindVar("sv_lan");
769 return (sv_lan->GetInt() != 0);
772 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
774 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
775 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
777 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
782 Assert(_heapchk() == _HEAPOK);
785 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
789 // load file into a null-terminated buffer
790 int fileSize = filesystem->Size(f);
791 char *buffer = (char *)MemAllocScratch(fileSize + 1);
795 filesystem->Read(buffer, fileSize, f); // read into local buffer
797 buffer[fileSize] = 0; // null terminate file as EOF
799 filesystem->Close( f ); // close file after reading
801 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
809 return kv->LoadFromFile(filesystem, resourceName, pathID);
813 void CHalfLife2::PushCommandStack(const CCommand *cmd)
815 CachedCommandInfo info;
818 #if SOURCE_ENGINE <= SE_DARKMESSIAH
819 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
822 m_CommandStack.push(info);
825 const CCommand *CHalfLife2::PeekCommandStack()
827 if (m_CommandStack.empty())
832 return m_CommandStack.front().args;
835 void CHalfLife2::PopCommandStack()
837 m_CommandStack.pop();
840 const char *CHalfLife2::CurrentCommandName()
842 #if SOURCE_ENGINE >= SE_ORANGEBOX
843 return m_CommandStack.front().args->Arg(0);
845 return m_CommandStack.front().cmd;
849 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
851 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
852 if (!pPlayer || !pPlayer->IsConnected() || pPlayer->IsInKickQueue())
857 pPlayer->MarkAsBeingKicked();
859 DelayedKickInfo kick;
861 kick.client = client;
862 kick.userid = userid;
863 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
865 m_DelayedKicks.push(kick);
868 void CHalfLife2::ProcessDelayedKicks()
870 while (!m_DelayedKicks.empty())
872 DelayedKickInfo info = m_DelayedKicks.first();
873 m_DelayedKicks.pop();
875 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
876 if (player == NULL || player->GetUserId() != info.userid)
881 player->Kick(info.buffer);
885 edict_t *CHalfLife2::EdictOfIndex(int index)
887 return ::PEntityOfEntIndex(index);
890 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
892 return ::IndexOfEdict(pEnt);
895 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
902 int index = hndl.GetEntryIndex();
904 edict_t *pStoredEdict;
905 CBaseEntity *pStoredEntity;
907 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
912 if (pStoredEdict == NULL || pStoredEntity == NULL)
917 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
924 if (pSE->GetRefEHandle() != hndl)
932 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
934 IServerEntity *pEntOther = pEnt->GetIServerEntity();
936 if (pEntOther == NULL)
944 const char *CHalfLife2::GetCurrentMap()
946 return STRING(gpGlobals->mapname);
949 void CHalfLife2::ServerCommand(const char *buffer)
951 engine->ServerCommand(buffer);
954 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
956 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
957 CBaseHandle hndl = pUnknown->GetRefEHandle();
958 return (hndl.ToInt() | (1<<31));
961 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
963 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
968 CEntInfo *pInfo = NULL;
970 if (entRef & (1<<31))
972 /* Proper ent reference */
973 int hndlValue = entRef & ~(1<<31);
974 CBaseHandle hndl(hndlValue);
976 pInfo = LookupEntity(hndl.GetEntryIndex());
977 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
984 /* Old style index only */
985 pInfo = LookupEntity(entRef);
993 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
996 return pUnk->GetBaseEntity();
1003 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
1005 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
1007 // Make sure that our index is within the bounds of the global ent array
1008 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
1013 CEntInfo *entInfos = EntInfoArray();
1017 /* Attempt to use engine interface instead */
1018 static CEntInfo tempInfo;
1019 tempInfo.m_pNext = NULL;
1020 tempInfo.m_pPrev = NULL;
1022 edict_t *pEdict = PEntityOfEntIndex(entIndex);
1029 IServerUnknown *pUnk = pEdict->GetUnknown();
1036 tempInfo.m_pEntity = pUnk;
1037 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
1042 return &entInfos[entIndex];
1046 SERIAL_MASK = 0x7fff (15 bits)
1048 #define MAX_EDICT_BITS 11
1049 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
1050 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
1052 Top 5 bits of a handle are unused.
1053 Bit 31 - Our 'reference' flag indicator
1056 cell_t CHalfLife2::IndexToReference(int entIndex)
1058 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
1061 return INVALID_EHANDLE_INDEX;
1064 return EntityToReference(pEnt);
1067 int CHalfLife2::ReferenceToIndex(cell_t entRef)
1069 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1071 return INVALID_EHANDLE_INDEX;
1074 if (entRef & (1<<31))
1076 /* Proper ent reference */
1077 int hndlValue = entRef & ~(1<<31);
1078 CBaseHandle hndl(hndlValue);
1080 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
1082 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
1084 return INVALID_EHANDLE_INDEX;
1087 return hndl.GetEntryIndex();
1093 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
1095 if (pEntity == NULL)
1097 return INVALID_EHANDLE_INDEX;
1100 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1101 CBaseHandle hndl = pUnknown->GetRefEHandle();
1103 if (hndl == INVALID_EHANDLE_INDEX)
1105 return INVALID_EHANDLE_INDEX;
1108 if (hndl.GetEntryIndex() >= MAX_EDICTS)
1110 return (hndl.ToInt() | (1<<31));
1114 return hndl.GetEntryIndex();
1118 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
1120 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1122 return INVALID_EHANDLE_INDEX;
1125 int hndlValue = entRef & ~(1<<31);
1126 CBaseHandle hndl(hndlValue);
1128 if (hndl.GetEntryIndex() < MAX_EDICTS)
1130 return hndl.GetEntryIndex();
1136 void *CHalfLife2::GetGlobalEntityList()
1141 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1143 return prop->GetOffset();
1146 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
1148 if (pEdict == NULL || pEdict->IsFree())
1153 IServerUnknown *pUnk = pEdict->GetUnknown();
1159 CBaseEntity * pEntity = pUnk->GetBaseEntity();
1161 if (pEntity == NULL)
1166 return GetEntityClassname(pEntity);
1169 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
1171 static int offset = -1;
1174 CBaseEntity *pGetterEnt = ReferenceToEntity(0);
1175 datamap_t *pMap = GetDataMap(pGetterEnt);
1177 sm_datatable_info_t info;
1178 if (!FindDataMapInfo(pMap, "m_iClassname", &info))
1183 offset = info.actual_offset;
1186 return *(const char **)(((unsigned char *)pEntity) + offset);
1189 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1190 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
1192 static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
1193 if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
1196 static size_t helperCmdLen = strlen(pHelperCmd->GetName());
1198 CUtlVector<CUtlString> results;
1199 pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
1200 if (results.Count() == 0)
1203 // Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
1204 // so skip ahead to start of map path/name
1206 // Like the engine, we're only going to deal with the first match.
1208 strncopy(outFullname, &results[0][helperCmdLen + 1], size);
1214 bool CHalfLife2::IsMapValid(const char *map)
1216 if (!map || !map[0])
1219 bool ret = engine->IsMapValid(map);
1220 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1223 static char szFuzzyName[PLATFORM_MAX_PATH];
1224 if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
1226 ret = engine->IsMapValid(szFuzzyName);