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_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;
79 CHalfLife2::CHalfLife2()
83 CHalfLife2::~CHalfLife2()
85 for (NameHashSet<DataTableInfo *>::iterator iter = m_Classes.iter(); !iter.empty(); iter.next())
88 for (DataTableMap::iterator iter = m_Maps.iter(); !iter.empty(); iter.next())
92 #if SOURCE_ENGINE != SE_DARKMESSIAH
93 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
96 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
97 bool is_original_engine = false;
100 void CHalfLife2::OnSourceModStartup(bool late)
102 #if SOURCE_ENGINE != SE_DARKMESSIAH
104 /* The Ship currently is the only known game to use an older version of the engine */
105 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
106 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
108 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
111 is_original_engine = true;
113 else if (g_pSharedChangeInfo == NULL)
115 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
120 void CHalfLife2::OnSourceModAllInitialized()
122 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
123 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
124 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
125 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
126 sharesys->AddInterface(NULL, this);
129 void CHalfLife2::OnSourceModAllInitialized_Post()
131 InitLogicalEntData();
135 void CHalfLife2::InitLogicalEntData()
140 * gEntList and/or g_pEntityList
142 * First try to lookup pointer directly for platforms with symbols.
143 * If symbols aren't present (Windows or stripped Linux/Mac),
144 * attempt find via LevelShutdown + offset
146 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
148 #if !defined PLATFORM_WINDOWS
151 // Key exists so notify if lookup fails, but try other method.
152 g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
157 g_EntList = reinterpret_cast<void *>(addr);
158 #if !defined PLATFORM_WINDOWS
166 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
168 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
174 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
179 if (!g_pGameConf->GetOffset("gEntList", &offset))
181 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
185 g_EntList = *reinterpret_cast<void **>(addr + offset);
190 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
194 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
196 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
201 void CHalfLife2::InitCommandLine()
203 char path[PLATFORM_MAX_PATH];
206 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
208 if (!g_LibSys.IsPathFile(path))
210 g_Logger.LogError("Could not find path for: " TIER0_NAME);
214 ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
215 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
217 /* '_Tier0' dropped on Alien Swarm version */
218 if (m_pGetCommandLine == NULL)
220 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
223 if (m_pGetCommandLine == NULL)
225 /* We probably have a Ship engine. */
227 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
228 if (!g_LibSys.IsPathFile(path))
230 g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
234 if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
236 g_Logger.LogError("Could not load %s: %s", path, error);
240 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
242 if (m_pGetCommandLine == NULL)
244 g_Logger.LogError("Could not locate any command line functionality");
251 ICommandLine *CHalfLife2::GetValveCommandLine()
253 if (!m_pGetCommandLine)
256 return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
259 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
260 bool CHalfLife2::IsOriginalEngine()
262 return is_original_engine;
266 #if SOURCE_ENGINE != SE_DARKMESSIAH
267 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
269 #if SOURCE_ENGINE == SE_DOTA
270 return engine->GetChangeAccessor( IndexOfEdict((const edict_t *)this) );
272 return engine->GetChangeAccessor( (const edict_t *)this );
277 bool UTIL_FindInSendTable(SendTable *pTable,
279 sm_sendprop_info_t *info,
283 int props = pTable->GetNumProps();
286 for (int i=0; i<props; i++)
288 prop = pTable->GetProp(i);
289 pname = prop->GetName();
290 if (pname && strcmp(name, pname) == 0)
293 info->actual_offset = offset + info->prop->GetOffset();
296 if (prop->GetDataTable())
298 if (UTIL_FindInSendTable(prop->GetDataTable(),
301 offset + prop->GetOffset())
312 bool UTIL_FindDataMapInfo(datamap_t *pMap, const char *name, sm_datatable_info_t *pDataTable)
316 for (int i = 0; i < pMap->dataNumFields; ++i)
318 if (pMap->dataDesc[i].fieldName == NULL)
322 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
324 pDataTable->prop = &(pMap->dataDesc[i]);
325 pDataTable->actual_offset = GetTypeDescOffs(pDataTable->prop);
328 if (pMap->dataDesc[i].td == NULL || !UTIL_FindDataMapInfo(pMap->dataDesc[i].td, name, pDataTable))
333 pDataTable->actual_offset += GetTypeDescOffs(&(pMap->dataDesc[i]));
337 pMap = pMap->baseMap;
343 ServerClass *CHalfLife2::FindServerClass(const char *classname)
345 DataTableInfo *pInfo = _FindServerClass(classname);
353 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
355 DataTableInfo *pInfo;
356 if (!m_Classes.retrieve(classname, &pInfo))
358 ServerClass *sc = gamedll->GetAllServerClasses();
361 if (strcmp(classname, sc->GetName()) == 0)
363 pInfo = new DataTableInfo(sc);
364 m_Classes.insert(classname, pInfo);
376 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
378 DataTableInfo *pInfo;
379 sm_sendprop_info_t *prop;
381 if ((pInfo = _FindServerClass(classname)) == NULL)
386 if (!pInfo->lookup.retrieve(offset, info))
388 sm_sendprop_info_t temp_info;
390 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
395 pInfo->lookup.insert(offset, temp_info);
402 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
404 sm_sendprop_info_t info;
406 if (!FindSendPropInfo(classname, offset, &info))
414 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
416 sm_datatable_info_t dt_info;
418 if (!(this->FindDataMapInfo(pMap, offset, &dt_info)))
426 bool CHalfLife2::FindDataMapInfo(datamap_t *pMap, const char *offset, sm_datatable_info_t *pDataTable)
428 DataTableMap::Insert i = m_Maps.findForAdd(pMap);
430 m_Maps.add(i, pMap, new DataMapCache());
432 DataMapCache *cache = i->value;
434 sm_datatable_info_t *pNewTable;
435 if (!cache->retrieve(offset, pDataTable))
437 if (!UTIL_FindDataMapInfo(pMap, offset, pDataTable))
439 cache->insert(offset, *pDataTable);
445 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
447 #if SOURCE_ENGINE != SE_DARKMESSIAH
448 if (g_pSharedChangeInfo != NULL)
452 pEdict->StateChanged(offset);
456 pEdict->StateChanged();
462 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
466 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
468 #ifndef USE_PROTOBUF_USERMESSAGES
469 bf_write *pBitBuf = NULL;
471 cell_t players[] = {client};
473 if (dest == HUD_PRINTTALK)
475 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
477 /* Use SayText user message instead */
478 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
481 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
483 #if SOURCE_ENGINE == SE_DOTA
484 CUserMsg_SayText *pMsg;
485 if ((pMsg = (CUserMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
491 pMsg->set_text(buffer);
492 pMsg->set_chat(false);
493 #elif SOURCE_ENGINE == SE_CSGO
494 CCSUsrMsg_SayText *pMsg;
495 if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
500 pMsg->set_ent_idx(0);
501 pMsg->set_text(buffer);
502 pMsg->set_chat(false);
504 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
509 pBitBuf->WriteByte(0);
510 pBitBuf->WriteString(buffer);
511 pBitBuf->WriteByte(1);
514 g_UserMsgs.EndMessage();
520 #if SOURCE_ENGINE == SE_DOTA
521 CUserMsg_TextMsg *pMsg;
522 if ((pMsg = (CUserMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
527 pMsg->set_dest(dest);
528 pMsg->add_param(msg);
533 #elif SOURCE_ENGINE == SE_CSGO
534 CCSUsrMsg_TextMsg *pMsg;
535 if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
540 // Client tries to read all 5 'params' and will crash if less
541 pMsg->set_msg_dst(dest);
542 pMsg->add_params(msg);
543 pMsg->add_params("");
544 pMsg->add_params("");
545 pMsg->add_params("");
546 pMsg->add_params("");
548 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
553 pBitBuf->WriteByte(dest);
554 pBitBuf->WriteString(msg);
557 g_UserMsgs.EndMessage();
562 bool CHalfLife2::HintTextMsg(int client, const char *msg)
564 cell_t players[] = {client};
566 #if SOURCE_ENGINE == SE_DOTA
567 CUserMsg_HintText *pMsg;
568 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
573 pMsg->set_message(msg);
574 #elif SOURCE_ENGINE == SE_CSGO
575 CCSUsrMsg_HintText *pMsg;
576 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
583 bf_write *pBitBuf = NULL;
585 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
590 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
591 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
593 pBitBuf->WriteByte(1);
595 pBitBuf->WriteString(msg);
597 g_UserMsgs.EndMessage();
602 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
604 #if SOURCE_ENGINE == SE_DOTA
605 CUserMsg_HintText *pMsg;
606 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
611 pMsg->set_message(msg);
612 #elif SOURCE_ENGINE == SE_CSGO
613 CCSUsrMsg_HintText *pMsg;
614 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
621 bf_write *pBitBuf = NULL;
623 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
628 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
629 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
631 pBitBuf->WriteByte(1);
633 pBitBuf->WriteString(msg);
636 g_UserMsgs.EndMessage();
641 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
643 KeyValues *SubKey = NULL;
645 cell_t players[] = {client};
647 #if SOURCE_ENGINE == SE_DOTA
648 CUserMsg_VGUIMenu *pMsg;
649 if ((pMsg = (CUserMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
653 #elif SOURCE_ENGINE == SE_CSGO
654 CCSUsrMsg_VGUIMenu *pMsg;
655 if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
660 bf_write *pBitBuf = NULL;
661 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
669 SubKey = data->GetFirstSubKey();
673 SubKey = SubKey->GetNextKey();
675 SubKey = data->GetFirstSubKey();
678 #if SOURCE_ENGINE == SE_DOTA
679 pMsg->set_name(name);
680 pMsg->set_show(show);
684 CUserMsg_VGUIMenu_Keys *key = pMsg->add_keys();
685 key->set_name(SubKey->GetName());
686 key->set_value(SubKey->GetString());
687 SubKey = SubKey->GetNextKey();
689 #elif SOURCE_ENGINE == SE_CSGO
690 pMsg->set_name(name);
691 pMsg->set_show(show);
695 CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
696 key->set_name(SubKey->GetName());
697 key->set_str(SubKey->GetString());
698 SubKey = SubKey->GetNextKey();
701 pBitBuf->WriteString(name);
702 pBitBuf->WriteByte((show) ? 1 : 0);
703 pBitBuf->WriteByte(count);
706 pBitBuf->WriteString(SubKey->GetName());
707 pBitBuf->WriteString(SubKey->GetString());
708 SubKey = SubKey->GetNextKey();
712 g_UserMsgs.EndMessage();
717 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
719 DelayedFakeCliCmd *pFake;
721 if (m_FreeCmds.empty())
723 pFake = new DelayedFakeCliCmd;
725 pFake = m_FreeCmds.front();
729 pFake->client = client;
730 pFake->userid = userid;
731 pFake->cmd.assign(cmd);
733 m_CmdQueue.push(pFake);
736 void CHalfLife2::ProcessFakeCliCmdQueue()
738 while (!m_CmdQueue.empty())
740 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
742 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
744 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
745 #if SOURCE_ENGINE == SE_DOTA
746 engine->ClientCommand(pPlayer->GetIndex(), "%s", pFake->cmd.c_str());
748 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
756 bool CHalfLife2::IsLANServer()
758 sv_lan = icvar->FindVar("sv_lan");
765 return (sv_lan->GetInt() != 0);
768 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
770 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
771 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
773 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
778 Assert(_heapchk() == _HEAPOK);
781 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
785 // load file into a null-terminated buffer
786 int fileSize = filesystem->Size(f);
787 char *buffer = (char *)MemAllocScratch(fileSize + 1);
791 filesystem->Read(buffer, fileSize, f); // read into local buffer
793 buffer[fileSize] = 0; // null terminate file as EOF
795 filesystem->Close( f ); // close file after reading
797 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
805 return kv->LoadFromFile(filesystem, resourceName, pathID);
809 void CHalfLife2::PushCommandStack(const CCommand *cmd)
811 CachedCommandInfo info;
814 #if SOURCE_ENGINE <= SE_DARKMESSIAH
815 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
818 m_CommandStack.push(info);
821 const CCommand *CHalfLife2::PeekCommandStack()
823 if (m_CommandStack.empty())
828 return m_CommandStack.front().args;
831 void CHalfLife2::PopCommandStack()
833 m_CommandStack.pop();
836 const char *CHalfLife2::CurrentCommandName()
838 #if SOURCE_ENGINE >= SE_ORANGEBOX
839 return m_CommandStack.front().args->Arg(0);
841 return m_CommandStack.front().cmd;
845 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
847 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
848 if (!pPlayer || !pPlayer->IsConnected() || pPlayer->IsInKickQueue())
853 pPlayer->MarkAsBeingKicked();
855 DelayedKickInfo kick;
857 kick.client = client;
858 kick.userid = userid;
859 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
861 m_DelayedKicks.push(kick);
864 void CHalfLife2::ProcessDelayedKicks()
866 while (!m_DelayedKicks.empty())
868 DelayedKickInfo info = m_DelayedKicks.first();
869 m_DelayedKicks.pop();
871 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
872 if (player == NULL || player->GetUserId() != info.userid)
877 player->Kick(info.buffer);
881 edict_t *CHalfLife2::EdictOfIndex(int index)
883 return ::PEntityOfEntIndex(index);
886 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
888 return ::IndexOfEdict(pEnt);
891 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
898 int index = hndl.GetEntryIndex();
900 edict_t *pStoredEdict;
901 CBaseEntity *pStoredEntity;
903 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
908 if (pStoredEdict == NULL || pStoredEntity == NULL)
913 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
920 if (pSE->GetRefEHandle() != hndl)
928 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
930 IServerEntity *pEntOther = pEnt->GetIServerEntity();
932 if (pEntOther == NULL)
940 const char *CHalfLife2::GetCurrentMap()
942 return STRING(gpGlobals->mapname);
945 void CHalfLife2::ServerCommand(const char *buffer)
947 engine->ServerCommand(buffer);
950 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
952 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
953 CBaseHandle hndl = pUnknown->GetRefEHandle();
954 return (hndl.ToInt() | (1<<31));
957 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
959 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
964 CEntInfo *pInfo = NULL;
966 if (entRef & (1<<31))
968 /* Proper ent reference */
969 int hndlValue = entRef & ~(1<<31);
970 CBaseHandle hndl(hndlValue);
972 pInfo = LookupEntity(hndl.GetEntryIndex());
973 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
980 /* Old style index only */
981 pInfo = LookupEntity(entRef);
989 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
992 return pUnk->GetBaseEntity();
999 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
1001 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
1003 // Make sure that our index is within the bounds of the global ent array
1004 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
1009 if (!g_EntList || entInfoOffset == -1)
1011 /* Attempt to use engine interface instead */
1012 static CEntInfo tempInfo;
1013 tempInfo.m_pNext = NULL;
1014 tempInfo.m_pPrev = NULL;
1016 edict_t *pEdict = PEntityOfEntIndex(entIndex);
1023 IServerUnknown *pUnk = pEdict->GetUnknown();
1030 tempInfo.m_pEntity = pUnk;
1031 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
1036 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
1037 return &pArray[entIndex];
1041 SERIAL_MASK = 0x7fff (15 bits)
1043 #define MAX_EDICT_BITS 11
1044 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
1045 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
1047 Top 5 bits of a handle are unused.
1048 Bit 31 - Our 'reference' flag indicator
1051 cell_t CHalfLife2::IndexToReference(int entIndex)
1053 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
1056 return INVALID_EHANDLE_INDEX;
1059 return EntityToReference(pEnt);
1062 int CHalfLife2::ReferenceToIndex(cell_t entRef)
1064 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1066 return INVALID_EHANDLE_INDEX;
1069 if (entRef & (1<<31))
1071 /* Proper ent reference */
1072 int hndlValue = entRef & ~(1<<31);
1073 CBaseHandle hndl(hndlValue);
1075 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
1077 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
1079 return INVALID_EHANDLE_INDEX;
1082 return hndl.GetEntryIndex();
1088 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
1090 if (pEntity == NULL)
1092 return INVALID_EHANDLE_INDEX;
1095 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1096 CBaseHandle hndl = pUnknown->GetRefEHandle();
1098 if (hndl == INVALID_EHANDLE_INDEX)
1100 return INVALID_EHANDLE_INDEX;
1103 if (hndl.GetEntryIndex() >= MAX_EDICTS)
1105 return (hndl.ToInt() | (1<<31));
1109 return hndl.GetEntryIndex();
1113 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
1115 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1117 return INVALID_EHANDLE_INDEX;
1120 int hndlValue = entRef & ~(1<<31);
1121 CBaseHandle hndl(hndlValue);
1123 if (hndl.GetEntryIndex() < MAX_EDICTS)
1125 return hndl.GetEntryIndex();
1131 void *CHalfLife2::GetGlobalEntityList()
1136 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1138 return prop->GetOffset();
1141 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
1143 if (pEdict == NULL || pEdict->IsFree())
1148 IServerUnknown *pUnk = pEdict->GetUnknown();
1154 CBaseEntity * pEntity = pUnk->GetBaseEntity();
1156 if (pEntity == NULL)
1161 return GetEntityClassname(pEntity);
1164 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
1166 static int offset = -1;
1169 CBaseEntity *pGetterEnt = ReferenceToEntity(0);
1170 datamap_t *pMap = GetDataMap(pGetterEnt);
1172 sm_datatable_info_t info;
1173 if (!FindDataMapInfo(pMap, "m_iClassname", &info))
1178 offset = info.actual_offset;
1181 return *(const char **)(((unsigned char *)pEntity) + offset);
1184 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1185 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
1187 static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
1188 if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
1191 static size_t helperCmdLen = strlen(pHelperCmd->GetName());
1193 CUtlVector<CUtlString> results;
1194 pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
1195 if (results.Count() == 0)
1198 // Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
1199 // so skip ahead to start of map path/name
1201 // Like the engine, we're only going to deal with the first match.
1203 strncopy(outFullname, &results[0][helperCmdLen + 1], size);
1209 bool CHalfLife2::IsMapValid(const char *map)
1211 if (!map || !map[0])
1214 bool ret = engine->IsMapValid(map);
1215 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1218 static char szFuzzyName[PLATFORM_MAX_PATH];
1219 if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
1221 ret = engine->IsMapValid(szFuzzyName);