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"
45 typedef ICommandLine *(*FakeGetCommandLine)();
48 #define TIER0_NAME "tier0.dll"
49 #define VSTDLIB_NAME "vstdlib.dll"
50 #elif defined __APPLE__
51 #define TIER0_NAME "libtier0.dylib"
52 #define VSTDLIB_NAME "libvstdlib.dylib"
53 #elif defined __linux__
54 #if SOURCE_ENGINE >= SE_CSS
55 #define TIER0_NAME "libtier0.so"
56 #define VSTDLIB_NAME "libvstdlib.so"
58 #define TIER0_NAME "tier0_i486.so"
59 #define VSTDLIB_NAME "vstdlib_i486.so"
64 ConVar *sv_lan = NULL;
66 static void *g_EntList = NULL;
67 static int entInfoOffset = -1;
72 int HashFunction<datamap_t *>(datamap_t * const &k)
74 return reinterpret_cast<int>(k);
78 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
84 CHalfLife2::CHalfLife2()
86 m_pClasses = sm_trie_create();
89 CHalfLife2::~CHalfLife2()
91 sm_trie_destroy(m_pClasses);
93 List<DataTableInfo *>::iterator iter;
95 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
103 THash<datamap_t *, DataMapTrie>::iterator h_iter;
104 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
106 if (h_iter->val.trie)
108 sm_trie_destroy(h_iter->val.trie);
109 h_iter->val.trie = NULL;
116 #if SOURCE_ENGINE != SE_DARKMESSIAH
117 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
120 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
121 bool is_original_engine = false;
124 void CHalfLife2::OnSourceModStartup(bool late)
126 #if SOURCE_ENGINE != SE_DARKMESSIAH
128 /* The Ship currently is the only known game to use an older version of the engine */
129 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
130 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
132 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
135 is_original_engine = true;
137 else if (g_pSharedChangeInfo == NULL)
139 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
144 void CHalfLife2::OnSourceModAllInitialized()
146 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
147 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
148 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
149 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
150 g_ShareSys.AddInterface(NULL, this);
153 void CHalfLife2::OnSourceModAllInitialized_Post()
155 InitLogicalEntData();
159 void CHalfLife2::InitLogicalEntData()
164 * gEntList and/or g_pEntityList
166 * First try to lookup pointer directly for platforms with symbols.
167 * If symbols aren't present (Windows or stripped Linux/Mac),
168 * attempt find via LevelShutdown + offset
170 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
172 #if !defined PLATFORM_WINDOWS
175 // Key exists so notify if lookup fails, but try other method.
176 g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
181 g_EntList = reinterpret_cast<void *>(addr);
182 #if !defined PLATFORM_WINDOWS
190 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
192 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
198 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
203 if (!g_pGameConf->GetOffset("gEntList", &offset))
205 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
209 g_EntList = *reinterpret_cast<void **>(addr + offset);
214 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
218 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
220 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
225 void CHalfLife2::InitCommandLine()
227 char path[PLATFORM_MAX_PATH];
230 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
232 if (!g_LibSys.IsPathFile(path))
234 g_Logger.LogError("Could not find path for: " TIER0_NAME);
238 ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
239 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
241 /* '_Tier0' dropped on Alien Swarm version */
242 if (m_pGetCommandLine == NULL)
244 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
247 if (m_pGetCommandLine == NULL)
249 /* We probably have a Ship engine. */
251 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
252 if (!g_LibSys.IsPathFile(path))
254 g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
258 if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
260 g_Logger.LogError("Could not load %s: %s", path, error);
264 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
266 if (m_pGetCommandLine == NULL)
268 g_Logger.LogError("Could not locate any command line functionality");
275 ICommandLine *CHalfLife2::GetValveCommandLine()
277 if (!m_pGetCommandLine)
280 return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
283 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
284 bool CHalfLife2::IsOriginalEngine()
286 return is_original_engine;
290 #if SOURCE_ENGINE != SE_DARKMESSIAH
291 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
293 return engine->GetChangeAccessor( (const edict_t *)this );
297 bool UTIL_FindInSendTable(SendTable *pTable,
299 sm_sendprop_info_t *info,
303 int props = pTable->GetNumProps();
306 for (int i=0; i<props; i++)
308 prop = pTable->GetProp(i);
309 pname = prop->GetName();
310 if (pname && strcmp(name, pname) == 0)
313 info->actual_offset = offset + info->prop->GetOffset();
316 if (prop->GetDataTable())
318 if (UTIL_FindInSendTable(prop->GetDataTable(),
321 offset + prop->GetOffset())
332 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name)
336 for (int i=0; i<pMap->dataNumFields; i++)
338 if (pMap->dataDesc[i].fieldName == NULL)
342 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
344 return &(pMap->dataDesc[i]);
346 if (pMap->dataDesc[i].td)
348 typedescription_t *_td;
349 if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name)) != NULL)
355 pMap = pMap->baseMap;
361 ServerClass *CHalfLife2::FindServerClass(const char *classname)
363 DataTableInfo *pInfo = _FindServerClass(classname);
373 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
375 DataTableInfo *pInfo = NULL;
377 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
379 ServerClass *sc = gamedll->GetAllServerClasses();
382 if (strcmp(classname, sc->GetName()) == 0)
384 pInfo = new DataTableInfo;
386 sm_trie_insert(m_pClasses, classname, pInfo);
387 m_Tables.push_back(pInfo);
401 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
403 DataTableInfo *pInfo;
404 sm_sendprop_info_t *prop;
406 if ((pInfo = _FindServerClass(classname)) == NULL)
411 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
413 sm_sendprop_info_t temp_info;
415 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
420 pInfo->lookup.insert(offset, temp_info);
431 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
433 sm_sendprop_info_t info;
435 if (!FindSendPropInfo(classname, offset, &info))
443 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
445 typedescription_t *td = NULL;
446 DataMapTrie &val = m_Maps[pMap];
450 val.trie = sm_trie_create();
452 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
454 if ((td = UTIL_FindInDataMap(pMap, offset)) != NULL)
456 sm_trie_insert(val.trie, offset, td);
463 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
465 #if SOURCE_ENGINE != SE_DARKMESSIAH
466 if (g_pSharedChangeInfo != NULL)
470 pEdict->StateChanged(offset);
474 pEdict->StateChanged();
480 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
484 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
486 bf_write *pBitBuf = NULL;
487 cell_t players[] = {client};
489 if (dest == HUD_PRINTTALK)
491 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
493 /* Use SayText user message instead */
494 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
497 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
499 if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
504 pBitBuf->WriteByte(0);
505 pBitBuf->WriteString(buffer);
506 pBitBuf->WriteByte(1);
508 g_UserMsgs.EndMessage();
514 if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
519 pBitBuf->WriteByte(dest);
520 pBitBuf->WriteString(msg);
522 g_UserMsgs.EndMessage();
527 bool CHalfLife2::HintTextMsg(int client, const char *msg)
529 bf_write *pBitBuf = NULL;
530 cell_t players[] = {client};
532 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
537 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
538 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
540 pBitBuf->WriteByte(1);
542 pBitBuf->WriteString(msg);
543 g_UserMsgs.EndMessage();
548 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
550 bf_write *pBitBuf = NULL;
552 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
557 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
558 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
560 pBitBuf->WriteByte(1);
562 pBitBuf->WriteString(msg);
563 g_UserMsgs.EndMessage();
568 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
570 bf_write *pBitBuf = NULL;
571 KeyValues *SubKey = NULL;
573 cell_t players[] = {client};
575 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
582 SubKey = data->GetFirstSubKey();
586 SubKey = SubKey->GetNextKey();
588 SubKey = data->GetFirstSubKey();
591 pBitBuf->WriteString(name);
592 pBitBuf->WriteByte((show) ? 1 : 0);
593 pBitBuf->WriteByte(count);
596 pBitBuf->WriteString(SubKey->GetName());
597 pBitBuf->WriteString(SubKey->GetString());
598 SubKey = SubKey->GetNextKey();
600 g_UserMsgs.EndMessage();
605 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
607 DelayedFakeCliCmd *pFake;
609 if (m_FreeCmds.empty())
611 pFake = new DelayedFakeCliCmd;
613 pFake = m_FreeCmds.front();
617 pFake->client = client;
618 pFake->userid = userid;
619 pFake->cmd.assign(cmd);
621 m_CmdQueue.push(pFake);
624 void CHalfLife2::ProcessFakeCliCmdQueue()
626 while (!m_CmdQueue.empty())
628 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
630 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
632 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
633 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
640 bool CHalfLife2::IsLANServer()
642 sv_lan = icvar->FindVar("sv_lan");
649 return (sv_lan->GetInt() != 0);
652 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
654 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
655 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
657 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
662 Assert(_heapchk() == _HEAPOK);
665 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
669 // load file into a null-terminated buffer
670 int fileSize = filesystem->Size(f);
671 char *buffer = (char *)MemAllocScratch(fileSize + 1);
675 filesystem->Read(buffer, fileSize, f); // read into local buffer
677 buffer[fileSize] = 0; // null terminate file as EOF
679 filesystem->Close( f ); // close file after reading
681 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
689 return kv->LoadFromFile(filesystem, resourceName, pathID);
693 void CHalfLife2::PushCommandStack(const CCommand *cmd)
695 CachedCommandInfo info;
698 #if SOURCE_ENGINE <= SE_DARKMESSIAH
699 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
702 m_CommandStack.push(info);
705 const CCommand *CHalfLife2::PeekCommandStack()
707 if (m_CommandStack.empty())
712 return m_CommandStack.front().args;
715 void CHalfLife2::PopCommandStack()
717 m_CommandStack.pop();
720 const char *CHalfLife2::CurrentCommandName()
722 #if SOURCE_ENGINE >= SE_ORANGEBOX
723 return m_CommandStack.front().args->Arg(0);
725 return m_CommandStack.front().cmd;
729 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
731 DelayedKickInfo kick;
733 kick.client = client;
734 kick.userid = userid;
735 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
737 m_DelayedKicks.push(kick);
740 void CHalfLife2::ProcessDelayedKicks()
742 while (!m_DelayedKicks.empty())
744 DelayedKickInfo info = m_DelayedKicks.first();
745 m_DelayedKicks.pop();
747 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
748 if (player == NULL || player->GetUserId() != info.userid)
753 player->Kick(info.buffer);
757 edict_t *CHalfLife2::EdictOfIndex(int index)
759 return ::PEntityOfEntIndex(index);
762 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
764 return ::IndexOfEdict(pEnt);
767 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
774 int index = hndl.GetEntryIndex();
776 edict_t *pStoredEdict;
777 CBaseEntity *pStoredEntity;
779 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
784 if (pStoredEdict == NULL || pStoredEntity == NULL)
789 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
796 if (pSE->GetRefEHandle() != hndl)
804 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
806 IServerEntity *pEntOther = pEnt->GetIServerEntity();
808 if (pEntOther == NULL)
816 const char *CHalfLife2::GetCurrentMap()
818 return STRING(gpGlobals->mapname);
821 void CHalfLife2::ServerCommand(const char *buffer)
823 engine->ServerCommand(buffer);
826 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
828 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
829 CBaseHandle hndl = pUnknown->GetRefEHandle();
830 return (hndl.ToInt() | (1<<31));
833 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
835 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
840 CEntInfo *pInfo = NULL;
842 if (entRef & (1<<31))
844 /* Proper ent reference */
845 int hndlValue = entRef & ~(1<<31);
846 CBaseHandle hndl(hndlValue);
848 pInfo = LookupEntity(hndl.GetEntryIndex());
849 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
856 /* Old style index only */
857 pInfo = LookupEntity(entRef);
865 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
868 return pUnk->GetBaseEntity();
875 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
877 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
879 // Make sure that our index is within the bounds of the global ent array
880 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
885 if (!g_EntList || entInfoOffset == -1)
887 /* Attempt to use engine interface instead */
888 static CEntInfo tempInfo;
889 tempInfo.m_pNext = NULL;
890 tempInfo.m_pPrev = NULL;
892 edict_t *pEdict = PEntityOfEntIndex(entIndex);
899 IServerUnknown *pUnk = pEdict->GetUnknown();
906 tempInfo.m_pEntity = pUnk;
907 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
912 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
913 return &pArray[entIndex];
917 SERIAL_MASK = 0x7fff (15 bits)
919 #define MAX_EDICT_BITS 11
920 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
921 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
923 Top 5 bits of a handle are unused.
924 Bit 31 - Our 'reference' flag indicator
927 cell_t CHalfLife2::IndexToReference(int entIndex)
929 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
932 return INVALID_EHANDLE_INDEX;
935 return EntityToReference(pEnt);
938 int CHalfLife2::ReferenceToIndex(cell_t entRef)
940 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
942 return INVALID_EHANDLE_INDEX;
945 if (entRef & (1<<31))
947 /* Proper ent reference */
948 int hndlValue = entRef & ~(1<<31);
949 CBaseHandle hndl(hndlValue);
951 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
953 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
955 return INVALID_EHANDLE_INDEX;
958 return hndl.GetEntryIndex();
964 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
968 return INVALID_EHANDLE_INDEX;
971 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
972 CBaseHandle hndl = pUnknown->GetRefEHandle();
974 if (hndl.GetEntryIndex() >= MAX_EDICTS)
976 return (hndl.ToInt() | (1<<31));
980 return hndl.GetEntryIndex();
984 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
986 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
988 return INVALID_EHANDLE_INDEX;
991 int hndlValue = entRef & ~(1<<31);
992 CBaseHandle hndl(hndlValue);
994 if (hndl.GetEntryIndex() < MAX_EDICTS)
996 return hndl.GetEntryIndex();
1002 void *CHalfLife2::GetGlobalEntityList()
1007 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1009 return prop->GetOffset();