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 "GameConfigs.h"
39 #include <compat_wrappers.h>
43 ConVar *sv_lan = NULL;
45 static void *g_EntList = NULL;
46 static int entInfoOffset = -1;
51 int HashFunction<datamap_t *>(datamap_t * const &k)
53 return reinterpret_cast<int>(k);
57 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
63 CHalfLife2::CHalfLife2()
65 m_pClasses = sm_trie_create();
68 CHalfLife2::~CHalfLife2()
70 sm_trie_destroy(m_pClasses);
72 List<DataTableInfo *>::iterator iter;
74 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
82 THash<datamap_t *, DataMapTrie>::iterator h_iter;
83 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
87 sm_trie_destroy(h_iter->val.trie);
88 h_iter->val.trie = NULL;
95 #if SOURCE_ENGINE != SE_DARKMESSIAH
96 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
99 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
100 bool is_original_engine = false;
103 void CHalfLife2::OnSourceModStartup(bool late)
105 #if SOURCE_ENGINE != SE_DARKMESSIAH
107 /* The Ship currently is the only known game to use an older version of the engine */
108 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
109 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
111 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
114 is_original_engine = true;
116 else if (g_pSharedChangeInfo == NULL)
118 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
123 void CHalfLife2::OnSourceModAllInitialized()
125 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
126 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
127 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
128 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
129 g_ShareSys.AddInterface(NULL, this);
132 void CHalfLife2::OnSourceModAllInitialized_Post()
135 #ifdef PLATFORM_WINDOWS
138 /* gEntList and/or g_pEntityList */
139 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
141 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
146 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
149 if (!g_pGameConf->GetOffset("gEntList", &offset))
151 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
154 g_EntList = *reinterpret_cast<void **>(addr + offset);
155 #elif defined PLATFORM_LINUX
156 /* gEntList and/or g_pEntityList */
157 if (!g_pGameConf->GetMemSig("gEntList", (void **)&addr))
159 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
164 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
167 g_EntList = reinterpret_cast<void *>(addr);
170 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
172 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
177 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
178 bool CHalfLife2::IsOriginalEngine()
180 return is_original_engine;
184 #if SOURCE_ENGINE != SE_DARKMESSIAH
185 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
187 return engine->GetChangeAccessor( (const edict_t *)this );
191 bool UTIL_FindInSendTable(SendTable *pTable,
193 sm_sendprop_info_t *info,
197 int props = pTable->GetNumProps();
200 for (int i=0; i<props; i++)
202 prop = pTable->GetProp(i);
203 pname = prop->GetName();
204 if (pname && strcmp(name, pname) == 0)
207 info->actual_offset = offset + info->prop->GetOffset();
210 if (prop->GetDataTable())
212 if (UTIL_FindInSendTable(prop->GetDataTable(),
215 offset + prop->GetOffset())
226 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name)
230 for (int i=0; i<pMap->dataNumFields; i++)
232 if (pMap->dataDesc[i].fieldName == NULL)
236 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
238 return &(pMap->dataDesc[i]);
240 if (pMap->dataDesc[i].td)
242 typedescription_t *_td;
243 if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name)) != NULL)
249 pMap = pMap->baseMap;
255 ServerClass *CHalfLife2::FindServerClass(const char *classname)
257 DataTableInfo *pInfo = _FindServerClass(classname);
267 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
269 DataTableInfo *pInfo = NULL;
271 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
273 ServerClass *sc = gamedll->GetAllServerClasses();
276 if (strcmp(classname, sc->GetName()) == 0)
278 pInfo = new DataTableInfo;
280 sm_trie_insert(m_pClasses, classname, pInfo);
281 m_Tables.push_back(pInfo);
295 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
297 DataTableInfo *pInfo;
298 sm_sendprop_info_t *prop;
300 if ((pInfo = _FindServerClass(classname)) == NULL)
305 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
307 sm_sendprop_info_t temp_info;
309 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
314 pInfo->lookup.insert(offset, temp_info);
325 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
327 sm_sendprop_info_t info;
329 if (!FindSendPropInfo(classname, offset, &info))
337 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
339 typedescription_t *td = NULL;
340 DataMapTrie &val = m_Maps[pMap];
344 val.trie = sm_trie_create();
346 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
348 if ((td = UTIL_FindInDataMap(pMap, offset)) != NULL)
350 sm_trie_insert(val.trie, offset, td);
357 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
359 #if SOURCE_ENGINE != SE_DARKMESSIAH
360 if (g_pSharedChangeInfo != NULL)
362 #if SOURCE_ENGINE != SE_LEFT4DEAD2
365 pEdict->StateChanged(offset);
370 pEdict->StateChanged();
376 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
380 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
382 bf_write *pBitBuf = NULL;
383 cell_t players[] = {client};
385 if (dest == HUD_PRINTTALK)
387 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
389 /* Use SayText user message instead */
390 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
393 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
395 if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
400 pBitBuf->WriteByte(0);
401 pBitBuf->WriteString(buffer);
402 pBitBuf->WriteByte(1);
404 g_UserMsgs.EndMessage();
410 if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
415 pBitBuf->WriteByte(dest);
416 pBitBuf->WriteString(msg);
418 g_UserMsgs.EndMessage();
423 bool CHalfLife2::HintTextMsg(int client, const char *msg)
425 bf_write *pBitBuf = NULL;
426 cell_t players[] = {client};
428 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
433 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
434 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
436 pBitBuf->WriteByte(1);
438 pBitBuf->WriteString(msg);
439 g_UserMsgs.EndMessage();
444 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
446 bf_write *pBitBuf = NULL;
448 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
453 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
454 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
456 pBitBuf->WriteByte(1);
458 pBitBuf->WriteString(msg);
459 g_UserMsgs.EndMessage();
464 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
466 bf_write *pBitBuf = NULL;
467 KeyValues *SubKey = NULL;
469 cell_t players[] = {client};
471 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
478 SubKey = data->GetFirstSubKey();
482 SubKey = SubKey->GetNextKey();
484 SubKey = data->GetFirstSubKey();
487 pBitBuf->WriteString(name);
488 pBitBuf->WriteByte((show) ? 1 : 0);
489 pBitBuf->WriteByte(count);
492 pBitBuf->WriteString(SubKey->GetName());
493 pBitBuf->WriteString(SubKey->GetString());
494 SubKey = SubKey->GetNextKey();
496 g_UserMsgs.EndMessage();
501 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
503 DelayedFakeCliCmd *pFake;
505 if (m_FreeCmds.empty())
507 pFake = new DelayedFakeCliCmd;
509 pFake = m_FreeCmds.front();
513 pFake->client = client;
514 pFake->userid = userid;
515 pFake->cmd.assign(cmd);
517 m_CmdQueue.push(pFake);
520 void CHalfLife2::ProcessFakeCliCmdQueue()
522 while (!m_CmdQueue.empty())
524 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
526 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
528 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
529 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
536 bool CHalfLife2::IsLANServer()
538 sv_lan = icvar->FindVar("sv_lan");
545 return (sv_lan->GetInt() != 0);
548 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
550 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
551 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
553 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
558 Assert(_heapchk() == _HEAPOK);
561 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
565 // load file into a null-terminated buffer
566 int fileSize = filesystem->Size(f);
567 char *buffer = (char *)MemAllocScratch(fileSize + 1);
571 filesystem->Read(buffer, fileSize, f); // read into local buffer
573 buffer[fileSize] = 0; // null terminate file as EOF
575 filesystem->Close( f ); // close file after reading
577 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
585 return kv->LoadFromFile(filesystem, resourceName, pathID);
589 void CHalfLife2::PushCommandStack(const CCommand *cmd)
591 CachedCommandInfo info;
594 #if SOURCE_ENGINE <= SE_DARKMESSIAH
595 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
598 m_CommandStack.push(info);
601 const CCommand *CHalfLife2::PeekCommandStack()
603 if (m_CommandStack.empty())
608 return m_CommandStack.front().args;
611 void CHalfLife2::PopCommandStack()
613 m_CommandStack.pop();
616 const char *CHalfLife2::CurrentCommandName()
618 #if SOURCE_ENGINE >= SE_ORANGEBOX
619 return m_CommandStack.front().args->Arg(0);
621 return m_CommandStack.front().cmd;
625 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
627 DelayedKickInfo kick;
629 kick.client = client;
630 kick.userid = userid;
631 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
633 m_DelayedKicks.push(kick);
636 void CHalfLife2::ProcessDelayedKicks()
638 while (!m_DelayedKicks.empty())
640 DelayedKickInfo info = m_DelayedKicks.first();
641 m_DelayedKicks.pop();
643 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
644 if (player == NULL || player->GetUserId() != info.userid)
649 player->Kick(info.buffer);
653 edict_t *CHalfLife2::EdictOfIndex(int index)
655 return ::PEntityOfEntIndex(index);
658 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
660 return ::IndexOfEdict(pEnt);
663 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
670 int index = hndl.GetEntryIndex();
672 edict_t *pStoredEdict;
673 CBaseEntity *pStoredEntity;
675 pStoredEdict = GetEntity(index, &pStoredEntity);
677 if (pStoredEdict == NULL || pStoredEntity == NULL)
682 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
689 if (pSE->GetRefEHandle() != hndl)
697 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
699 IServerEntity *pEntOther = pEnt->GetIServerEntity();
701 if (pEntOther == NULL)
709 const char *CHalfLife2::GetCurrentMap()
711 return STRING(gpGlobals->mapname);
714 void CHalfLife2::ServerCommand(const char *buffer)
716 engine->ServerCommand(buffer);
719 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
721 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
722 CBaseHandle hndl = pUnknown->GetRefEHandle();
723 return (hndl.ToInt() | (1<<31));
726 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
728 CEntInfo *pInfo = NULL;
730 if (entRef & (1<<31))
732 /* Proper ent reference */
733 int hndlValue = entRef & ~(1<<31);
734 CBaseHandle hndl(hndlValue);
736 pInfo = LookupEntity(hndl.GetEntryIndex());
737 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
744 /* Old style index only */
745 pInfo = LookupEntity(entRef);
753 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
756 return pUnk->GetBaseEntity();
763 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
765 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
767 if (!g_EntList || entInfoOffset == -1)
769 /* Attempt to use engine interface instead */
770 static CEntInfo tempInfo;
771 tempInfo.m_pNext = NULL;
772 tempInfo.m_pPrev = NULL;
774 edict_t *pEdict = PEntityOfEntIndex(entIndex);
781 IServerUnknown *pUnk = pEdict->GetUnknown();
788 tempInfo.m_pEntity = pUnk;
789 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
794 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
795 return &pArray[entIndex];
799 SERIAL_MASK = 0x7fff (15 bits)
801 #define MAX_EDICT_BITS 11
802 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
803 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
805 Top 5 bits of a handle are unused.
806 Bit 31 - Our 'reference' flag indicator
809 cell_t CHalfLife2::IndexToReference(int entIndex)
811 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
814 return INVALID_EHANDLE_INDEX;
817 return EntityToReference(pEnt);
820 int CHalfLife2::ReferenceToIndex(cell_t entRef)
822 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
824 return INVALID_EHANDLE_INDEX;
827 if (entRef & (1<<31))
829 /* Proper ent reference */
830 int hndlValue = entRef & ~(1<<31);
831 CBaseHandle hndl(hndlValue);
833 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
835 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
837 return INVALID_EHANDLE_INDEX;
840 return hndl.GetEntryIndex();
846 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
850 return INVALID_EHANDLE_INDEX;
853 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
854 CBaseHandle hndl = pUnknown->GetRefEHandle();
856 if (hndl.GetEntryIndex() >= MAX_EDICTS)
858 return (hndl.ToInt() | (1<<31));
862 return hndl.GetEntryIndex();
866 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
868 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
870 return INVALID_EHANDLE_INDEX;
873 int hndlValue = entRef & ~(1<<31);
874 CBaseHandle hndl(hndlValue);
876 if (hndl.GetEntryIndex() < MAX_EDICTS)
878 return hndl.GetEntryIndex();
884 void *CHalfLife2::GetGlobalEntityList()