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 "logic_bridge.h"
44 ConVar *sv_lan = NULL;
46 static void *g_EntList = NULL;
47 static int entInfoOffset = -1;
52 int HashFunction<datamap_t *>(datamap_t * const &k)
54 return reinterpret_cast<int>(k);
58 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
64 CHalfLife2::CHalfLife2()
66 m_pClasses = sm_trie_create();
69 CHalfLife2::~CHalfLife2()
71 sm_trie_destroy(m_pClasses);
73 List<DataTableInfo *>::iterator iter;
75 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
83 THash<datamap_t *, DataMapTrie>::iterator h_iter;
84 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
88 sm_trie_destroy(h_iter->val.trie);
89 h_iter->val.trie = NULL;
96 #if SOURCE_ENGINE != SE_DARKMESSIAH
97 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
100 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
101 bool is_original_engine = false;
104 void CHalfLife2::OnSourceModStartup(bool late)
106 #if SOURCE_ENGINE != SE_DARKMESSIAH
108 /* The Ship currently is the only known game to use an older version of the engine */
109 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
110 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
112 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
115 is_original_engine = true;
117 else if (g_pSharedChangeInfo == NULL)
119 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
124 void CHalfLife2::OnSourceModAllInitialized()
126 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
127 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
128 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
129 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
130 g_ShareSys.AddInterface(NULL, this);
133 void CHalfLife2::OnSourceModAllInitialized_Post()
136 #ifdef PLATFORM_WINDOWS
139 /* gEntList and/or g_pEntityList */
140 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
142 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
147 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
150 if (!g_pGameConf->GetOffset("gEntList", &offset))
152 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
155 g_EntList = *reinterpret_cast<void **>(addr + offset);
156 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
157 /* gEntList and/or g_pEntityList */
158 if (!g_pGameConf->GetMemSig("gEntList", (void **)&addr))
160 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
165 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
168 g_EntList = reinterpret_cast<void *>(addr);
171 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
173 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
178 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
179 bool CHalfLife2::IsOriginalEngine()
181 return is_original_engine;
185 #if SOURCE_ENGINE != SE_DARKMESSIAH
186 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
188 return engine->GetChangeAccessor( (const edict_t *)this );
192 bool UTIL_FindInSendTable(SendTable *pTable,
194 sm_sendprop_info_t *info,
198 int props = pTable->GetNumProps();
201 for (int i=0; i<props; i++)
203 prop = pTable->GetProp(i);
204 pname = prop->GetName();
205 if (pname && strcmp(name, pname) == 0)
208 info->actual_offset = offset + info->prop->GetOffset();
211 if (prop->GetDataTable())
213 if (UTIL_FindInSendTable(prop->GetDataTable(),
216 offset + prop->GetOffset())
227 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name)
231 for (int i=0; i<pMap->dataNumFields; i++)
233 if (pMap->dataDesc[i].fieldName == NULL)
237 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
239 return &(pMap->dataDesc[i]);
241 if (pMap->dataDesc[i].td)
243 typedescription_t *_td;
244 if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name)) != NULL)
250 pMap = pMap->baseMap;
256 ServerClass *CHalfLife2::FindServerClass(const char *classname)
258 DataTableInfo *pInfo = _FindServerClass(classname);
268 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
270 DataTableInfo *pInfo = NULL;
272 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
274 ServerClass *sc = gamedll->GetAllServerClasses();
277 if (strcmp(classname, sc->GetName()) == 0)
279 pInfo = new DataTableInfo;
281 sm_trie_insert(m_pClasses, classname, pInfo);
282 m_Tables.push_back(pInfo);
296 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
298 DataTableInfo *pInfo;
299 sm_sendprop_info_t *prop;
301 if ((pInfo = _FindServerClass(classname)) == NULL)
306 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
308 sm_sendprop_info_t temp_info;
310 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
315 pInfo->lookup.insert(offset, temp_info);
326 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
328 sm_sendprop_info_t info;
330 if (!FindSendPropInfo(classname, offset, &info))
338 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
340 typedescription_t *td = NULL;
341 DataMapTrie &val = m_Maps[pMap];
345 val.trie = sm_trie_create();
347 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
349 if ((td = UTIL_FindInDataMap(pMap, offset)) != NULL)
351 sm_trie_insert(val.trie, offset, td);
358 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
360 #if SOURCE_ENGINE != SE_DARKMESSIAH
361 if (g_pSharedChangeInfo != NULL)
365 pEdict->StateChanged(offset);
369 pEdict->StateChanged();
375 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
379 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
381 bf_write *pBitBuf = NULL;
382 cell_t players[] = {client};
384 if (dest == HUD_PRINTTALK)
386 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
388 /* Use SayText user message instead */
389 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
392 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
394 if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
399 pBitBuf->WriteByte(0);
400 pBitBuf->WriteString(buffer);
401 pBitBuf->WriteByte(1);
403 g_UserMsgs.EndMessage();
409 if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
414 pBitBuf->WriteByte(dest);
415 pBitBuf->WriteString(msg);
417 g_UserMsgs.EndMessage();
422 bool CHalfLife2::HintTextMsg(int client, const char *msg)
424 bf_write *pBitBuf = NULL;
425 cell_t players[] = {client};
427 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
432 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
433 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
435 pBitBuf->WriteByte(1);
437 pBitBuf->WriteString(msg);
438 g_UserMsgs.EndMessage();
443 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
445 bf_write *pBitBuf = NULL;
447 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
452 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
453 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
455 pBitBuf->WriteByte(1);
457 pBitBuf->WriteString(msg);
458 g_UserMsgs.EndMessage();
463 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
465 bf_write *pBitBuf = NULL;
466 KeyValues *SubKey = NULL;
468 cell_t players[] = {client};
470 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
477 SubKey = data->GetFirstSubKey();
481 SubKey = SubKey->GetNextKey();
483 SubKey = data->GetFirstSubKey();
486 pBitBuf->WriteString(name);
487 pBitBuf->WriteByte((show) ? 1 : 0);
488 pBitBuf->WriteByte(count);
491 pBitBuf->WriteString(SubKey->GetName());
492 pBitBuf->WriteString(SubKey->GetString());
493 SubKey = SubKey->GetNextKey();
495 g_UserMsgs.EndMessage();
500 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
502 DelayedFakeCliCmd *pFake;
504 if (m_FreeCmds.empty())
506 pFake = new DelayedFakeCliCmd;
508 pFake = m_FreeCmds.front();
512 pFake->client = client;
513 pFake->userid = userid;
514 pFake->cmd.assign(cmd);
516 m_CmdQueue.push(pFake);
519 void CHalfLife2::ProcessFakeCliCmdQueue()
521 while (!m_CmdQueue.empty())
523 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
525 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
527 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
528 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
535 bool CHalfLife2::IsLANServer()
537 sv_lan = icvar->FindVar("sv_lan");
544 return (sv_lan->GetInt() != 0);
547 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
549 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
550 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
552 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
557 Assert(_heapchk() == _HEAPOK);
560 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
564 // load file into a null-terminated buffer
565 int fileSize = filesystem->Size(f);
566 char *buffer = (char *)MemAllocScratch(fileSize + 1);
570 filesystem->Read(buffer, fileSize, f); // read into local buffer
572 buffer[fileSize] = 0; // null terminate file as EOF
574 filesystem->Close( f ); // close file after reading
576 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
584 return kv->LoadFromFile(filesystem, resourceName, pathID);
588 void CHalfLife2::PushCommandStack(const CCommand *cmd)
590 CachedCommandInfo info;
593 #if SOURCE_ENGINE <= SE_DARKMESSIAH
594 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
597 m_CommandStack.push(info);
600 const CCommand *CHalfLife2::PeekCommandStack()
602 if (m_CommandStack.empty())
607 return m_CommandStack.front().args;
610 void CHalfLife2::PopCommandStack()
612 m_CommandStack.pop();
615 const char *CHalfLife2::CurrentCommandName()
617 #if SOURCE_ENGINE >= SE_ORANGEBOX
618 return m_CommandStack.front().args->Arg(0);
620 return m_CommandStack.front().cmd;
624 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
626 DelayedKickInfo kick;
628 kick.client = client;
629 kick.userid = userid;
630 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
632 m_DelayedKicks.push(kick);
635 void CHalfLife2::ProcessDelayedKicks()
637 while (!m_DelayedKicks.empty())
639 DelayedKickInfo info = m_DelayedKicks.first();
640 m_DelayedKicks.pop();
642 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
643 if (player == NULL || player->GetUserId() != info.userid)
648 player->Kick(info.buffer);
652 edict_t *CHalfLife2::EdictOfIndex(int index)
654 return ::PEntityOfEntIndex(index);
657 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
659 return ::IndexOfEdict(pEnt);
662 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
669 int index = hndl.GetEntryIndex();
671 edict_t *pStoredEdict;
672 CBaseEntity *pStoredEntity;
674 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
679 if (pStoredEdict == NULL || pStoredEntity == NULL)
684 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
691 if (pSE->GetRefEHandle() != hndl)
699 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
701 IServerEntity *pEntOther = pEnt->GetIServerEntity();
703 if (pEntOther == NULL)
711 const char *CHalfLife2::GetCurrentMap()
713 return STRING(gpGlobals->mapname);
716 void CHalfLife2::ServerCommand(const char *buffer)
718 engine->ServerCommand(buffer);
721 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
723 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
724 CBaseHandle hndl = pUnknown->GetRefEHandle();
725 return (hndl.ToInt() | (1<<31));
728 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
730 CEntInfo *pInfo = NULL;
732 if (entRef & (1<<31))
734 /* Proper ent reference */
735 int hndlValue = entRef & ~(1<<31);
736 CBaseHandle hndl(hndlValue);
738 pInfo = LookupEntity(hndl.GetEntryIndex());
739 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
746 /* Old style index only */
747 pInfo = LookupEntity(entRef);
755 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
758 return pUnk->GetBaseEntity();
765 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
767 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
769 if (!g_EntList || entInfoOffset == -1)
771 /* Attempt to use engine interface instead */
772 static CEntInfo tempInfo;
773 tempInfo.m_pNext = NULL;
774 tempInfo.m_pPrev = NULL;
776 edict_t *pEdict = PEntityOfEntIndex(entIndex);
783 IServerUnknown *pUnk = pEdict->GetUnknown();
790 tempInfo.m_pEntity = pUnk;
791 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
796 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
797 return &pArray[entIndex];
801 SERIAL_MASK = 0x7fff (15 bits)
803 #define MAX_EDICT_BITS 11
804 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
805 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
807 Top 5 bits of a handle are unused.
808 Bit 31 - Our 'reference' flag indicator
811 cell_t CHalfLife2::IndexToReference(int entIndex)
813 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
816 return INVALID_EHANDLE_INDEX;
819 return EntityToReference(pEnt);
822 int CHalfLife2::ReferenceToIndex(cell_t entRef)
824 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
826 return INVALID_EHANDLE_INDEX;
829 if (entRef & (1<<31))
831 /* Proper ent reference */
832 int hndlValue = entRef & ~(1<<31);
833 CBaseHandle hndl(hndlValue);
835 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
837 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
839 return INVALID_EHANDLE_INDEX;
842 return hndl.GetEntryIndex();
848 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
852 return INVALID_EHANDLE_INDEX;
855 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
856 CBaseHandle hndl = pUnknown->GetRefEHandle();
858 if (hndl.GetEntryIndex() >= MAX_EDICTS)
860 return (hndl.ToInt() | (1<<31));
864 return hndl.GetEntryIndex();
868 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
870 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
872 return INVALID_EHANDLE_INDEX;
875 int hndlValue = entRef & ~(1<<31);
876 CBaseHandle hndl(hndlValue);
878 if (hndl.GetEntryIndex() < MAX_EDICTS)
880 return hndl.GetEntryIndex();
886 void *CHalfLife2::GetGlobalEntityList()
891 int CHalfLife2::GetSendPropOffset(SendProp *prop)
893 return prop->GetOffset();