Linux/Mac build fix.
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 #define TIER0_NAME "tier0.dll"
46 #define VSTDLIB_NAME "vstdlib.dll"
47 #elif defined __APPLE__
48 #define TIER0_NAME "libtier0.dylib"
49 #define VSTDLIB_NAME "libvstdlib.dylib"
50 #elif defined __linux__
51 #define TIER0_NAME LIB_PREFIX "tier0" LIB_SUFFIX
52 #define VSTDLIB_NAME LIB_PREFIX "vstdlib" LIB_SUFFIX
56 ConVar *sv_lan = NULL;
58 static void *g_EntList = NULL;
59 static int entInfoOffset = -1;
64 int HashFunction<datamap_t *>(datamap_t * const &k)
66 return reinterpret_cast<int>(k);
70 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
76 CHalfLife2::CHalfLife2()
78 m_pClasses = sm_trie_create();
81 CHalfLife2::~CHalfLife2()
83 sm_trie_destroy(m_pClasses);
85 List<DataTableInfo *>::iterator iter;
87 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
95 THash<datamap_t *, DataMapTrie>::iterator h_iter;
96 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
100 sm_trie_destroy(h_iter->val.trie);
101 h_iter->val.trie = NULL;
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 g_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
182 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
184 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
190 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
195 if (!g_pGameConf->GetOffset("gEntList", &offset))
197 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
201 g_EntList = *reinterpret_cast<void **>(addr + offset);
206 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
210 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
212 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
217 void CHalfLife2::InitCommandLine()
219 char path[PLATFORM_MAX_PATH];
222 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
224 if (!g_LibSys.IsPathFile(path))
226 g_Logger.LogError("Could not find path for: " TIER0_NAME);
230 ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
231 m_pGetCommandLine = (GetCommandLine)lib->GetSymbolAddress("CommandLine_Tier0");
233 /* '_Tier0' dropped on Alien Swarm version */
234 if (m_pGetCommandLine == NULL)
236 m_pGetCommandLine = (GetCommandLine)lib->GetSymbolAddress("CommandLine");
239 if (m_pGetCommandLine == NULL)
241 /* We probably have a Ship engine. */
243 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
244 if (!g_LibSys.IsPathFile(path))
246 g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
250 if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
252 g_Logger.LogError("Could not load %s: %s", path, error);
256 m_pGetCommandLine = (GetCommandLine)lib->GetSymbolAddress("CommandLine");
258 if (m_pGetCommandLine == NULL)
260 g_Logger.LogError("Could not locate any command line functionality");
267 ICommandLine *CHalfLife2::GetValveCommandLine()
269 if (!m_pGetCommandLine)
272 return m_pGetCommandLine();
275 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
276 bool CHalfLife2::IsOriginalEngine()
278 return is_original_engine;
282 #if SOURCE_ENGINE != SE_DARKMESSIAH
283 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
285 return engine->GetChangeAccessor( (const edict_t *)this );
289 bool UTIL_FindInSendTable(SendTable *pTable,
291 sm_sendprop_info_t *info,
295 int props = pTable->GetNumProps();
298 for (int i=0; i<props; i++)
300 prop = pTable->GetProp(i);
301 pname = prop->GetName();
302 if (pname && strcmp(name, pname) == 0)
305 info->actual_offset = offset + info->prop->GetOffset();
308 if (prop->GetDataTable())
310 if (UTIL_FindInSendTable(prop->GetDataTable(),
313 offset + prop->GetOffset())
324 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name)
328 for (int i=0; i<pMap->dataNumFields; i++)
330 if (pMap->dataDesc[i].fieldName == NULL)
334 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
336 return &(pMap->dataDesc[i]);
338 if (pMap->dataDesc[i].td)
340 typedescription_t *_td;
341 if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name)) != NULL)
347 pMap = pMap->baseMap;
353 ServerClass *CHalfLife2::FindServerClass(const char *classname)
355 DataTableInfo *pInfo = _FindServerClass(classname);
365 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
367 DataTableInfo *pInfo = NULL;
369 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
371 ServerClass *sc = gamedll->GetAllServerClasses();
374 if (strcmp(classname, sc->GetName()) == 0)
376 pInfo = new DataTableInfo;
378 sm_trie_insert(m_pClasses, classname, pInfo);
379 m_Tables.push_back(pInfo);
393 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
395 DataTableInfo *pInfo;
396 sm_sendprop_info_t *prop;
398 if ((pInfo = _FindServerClass(classname)) == NULL)
403 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
405 sm_sendprop_info_t temp_info;
407 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
412 pInfo->lookup.insert(offset, temp_info);
423 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
425 sm_sendprop_info_t info;
427 if (!FindSendPropInfo(classname, offset, &info))
435 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
437 typedescription_t *td = NULL;
438 DataMapTrie &val = m_Maps[pMap];
442 val.trie = sm_trie_create();
444 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
446 if ((td = UTIL_FindInDataMap(pMap, offset)) != NULL)
448 sm_trie_insert(val.trie, offset, td);
455 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
457 #if SOURCE_ENGINE != SE_DARKMESSIAH
458 if (g_pSharedChangeInfo != NULL)
462 pEdict->StateChanged(offset);
466 pEdict->StateChanged();
472 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
476 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
478 bf_write *pBitBuf = NULL;
479 cell_t players[] = {client};
481 if (dest == HUD_PRINTTALK)
483 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
485 /* Use SayText user message instead */
486 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
489 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
491 if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
496 pBitBuf->WriteByte(0);
497 pBitBuf->WriteString(buffer);
498 pBitBuf->WriteByte(1);
500 g_UserMsgs.EndMessage();
506 if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
511 pBitBuf->WriteByte(dest);
512 pBitBuf->WriteString(msg);
514 g_UserMsgs.EndMessage();
519 bool CHalfLife2::HintTextMsg(int client, const char *msg)
521 bf_write *pBitBuf = NULL;
522 cell_t players[] = {client};
524 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
529 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
530 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
532 pBitBuf->WriteByte(1);
534 pBitBuf->WriteString(msg);
535 g_UserMsgs.EndMessage();
540 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
542 bf_write *pBitBuf = NULL;
544 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
549 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
550 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
552 pBitBuf->WriteByte(1);
554 pBitBuf->WriteString(msg);
555 g_UserMsgs.EndMessage();
560 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
562 bf_write *pBitBuf = NULL;
563 KeyValues *SubKey = NULL;
565 cell_t players[] = {client};
567 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
574 SubKey = data->GetFirstSubKey();
578 SubKey = SubKey->GetNextKey();
580 SubKey = data->GetFirstSubKey();
583 pBitBuf->WriteString(name);
584 pBitBuf->WriteByte((show) ? 1 : 0);
585 pBitBuf->WriteByte(count);
588 pBitBuf->WriteString(SubKey->GetName());
589 pBitBuf->WriteString(SubKey->GetString());
590 SubKey = SubKey->GetNextKey();
592 g_UserMsgs.EndMessage();
597 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
599 DelayedFakeCliCmd *pFake;
601 if (m_FreeCmds.empty())
603 pFake = new DelayedFakeCliCmd;
605 pFake = m_FreeCmds.front();
609 pFake->client = client;
610 pFake->userid = userid;
611 pFake->cmd.assign(cmd);
613 m_CmdQueue.push(pFake);
616 void CHalfLife2::ProcessFakeCliCmdQueue()
618 while (!m_CmdQueue.empty())
620 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
622 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
624 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
625 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
632 bool CHalfLife2::IsLANServer()
634 sv_lan = icvar->FindVar("sv_lan");
641 return (sv_lan->GetInt() != 0);
644 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
646 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
647 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
649 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
654 Assert(_heapchk() == _HEAPOK);
657 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
661 // load file into a null-terminated buffer
662 int fileSize = filesystem->Size(f);
663 char *buffer = (char *)MemAllocScratch(fileSize + 1);
667 filesystem->Read(buffer, fileSize, f); // read into local buffer
669 buffer[fileSize] = 0; // null terminate file as EOF
671 filesystem->Close( f ); // close file after reading
673 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
681 return kv->LoadFromFile(filesystem, resourceName, pathID);
685 void CHalfLife2::PushCommandStack(const CCommand *cmd)
687 CachedCommandInfo info;
690 #if SOURCE_ENGINE <= SE_DARKMESSIAH
691 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
694 m_CommandStack.push(info);
697 const CCommand *CHalfLife2::PeekCommandStack()
699 if (m_CommandStack.empty())
704 return m_CommandStack.front().args;
707 void CHalfLife2::PopCommandStack()
709 m_CommandStack.pop();
712 const char *CHalfLife2::CurrentCommandName()
714 #if SOURCE_ENGINE >= SE_ORANGEBOX
715 return m_CommandStack.front().args->Arg(0);
717 return m_CommandStack.front().cmd;
721 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
723 DelayedKickInfo kick;
725 kick.client = client;
726 kick.userid = userid;
727 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
729 m_DelayedKicks.push(kick);
732 void CHalfLife2::ProcessDelayedKicks()
734 while (!m_DelayedKicks.empty())
736 DelayedKickInfo info = m_DelayedKicks.first();
737 m_DelayedKicks.pop();
739 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
740 if (player == NULL || player->GetUserId() != info.userid)
745 player->Kick(info.buffer);
749 edict_t *CHalfLife2::EdictOfIndex(int index)
751 return ::PEntityOfEntIndex(index);
754 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
756 return ::IndexOfEdict(pEnt);
759 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
766 int index = hndl.GetEntryIndex();
768 edict_t *pStoredEdict;
769 CBaseEntity *pStoredEntity;
771 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
776 if (pStoredEdict == NULL || pStoredEntity == NULL)
781 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
788 if (pSE->GetRefEHandle() != hndl)
796 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
798 IServerEntity *pEntOther = pEnt->GetIServerEntity();
800 if (pEntOther == NULL)
808 const char *CHalfLife2::GetCurrentMap()
810 return STRING(gpGlobals->mapname);
813 void CHalfLife2::ServerCommand(const char *buffer)
815 engine->ServerCommand(buffer);
818 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
820 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
821 CBaseHandle hndl = pUnknown->GetRefEHandle();
822 return (hndl.ToInt() | (1<<31));
825 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
827 CEntInfo *pInfo = NULL;
829 if (entRef & (1<<31))
831 /* Proper ent reference */
832 int hndlValue = entRef & ~(1<<31);
833 CBaseHandle hndl(hndlValue);
835 pInfo = LookupEntity(hndl.GetEntryIndex());
836 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
843 /* Old style index only */
844 pInfo = LookupEntity(entRef);
852 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
855 return pUnk->GetBaseEntity();
862 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
864 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
866 // Make sure that our index is within the bounds of the global ent array
867 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
872 if (!g_EntList || entInfoOffset == -1)
874 /* Attempt to use engine interface instead */
875 static CEntInfo tempInfo;
876 tempInfo.m_pNext = NULL;
877 tempInfo.m_pPrev = NULL;
879 edict_t *pEdict = PEntityOfEntIndex(entIndex);
886 IServerUnknown *pUnk = pEdict->GetUnknown();
893 tempInfo.m_pEntity = pUnk;
894 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
899 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
900 return &pArray[entIndex];
904 SERIAL_MASK = 0x7fff (15 bits)
906 #define MAX_EDICT_BITS 11
907 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
908 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
910 Top 5 bits of a handle are unused.
911 Bit 31 - Our 'reference' flag indicator
914 cell_t CHalfLife2::IndexToReference(int entIndex)
916 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
919 return INVALID_EHANDLE_INDEX;
922 return EntityToReference(pEnt);
925 int CHalfLife2::ReferenceToIndex(cell_t entRef)
927 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
929 return INVALID_EHANDLE_INDEX;
932 if (entRef & (1<<31))
934 /* Proper ent reference */
935 int hndlValue = entRef & ~(1<<31);
936 CBaseHandle hndl(hndlValue);
938 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
940 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
942 return INVALID_EHANDLE_INDEX;
945 return hndl.GetEntryIndex();
951 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
955 return INVALID_EHANDLE_INDEX;
958 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
959 CBaseHandle hndl = pUnknown->GetRefEHandle();
961 if (hndl.GetEntryIndex() >= MAX_EDICTS)
963 return (hndl.ToInt() | (1<<31));
967 return hndl.GetEntryIndex();
971 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
973 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
975 return INVALID_EHANDLE_INDEX;
978 int hndlValue = entRef & ~(1<<31);
979 CBaseHandle hndl(hndlValue);
981 if (hndl.GetEntryIndex() < MAX_EDICTS)
983 return hndl.GetEntryIndex();
989 void *CHalfLife2::GetGlobalEntityList()
994 int CHalfLife2::GetSendPropOffset(SendProp *prop)
996 return prop->GetOffset();