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)
363 #if SOURCE_ENGINE != SE_LEFT4DEAD2
366 pEdict->StateChanged(offset);
371 pEdict->StateChanged();
377 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
381 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
383 bf_write *pBitBuf = NULL;
384 cell_t players[] = {client};
386 if (dest == HUD_PRINTTALK)
388 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
390 /* Use SayText user message instead */
391 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
394 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
396 if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
401 pBitBuf->WriteByte(0);
402 pBitBuf->WriteString(buffer);
403 pBitBuf->WriteByte(1);
405 g_UserMsgs.EndMessage();
411 if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
416 pBitBuf->WriteByte(dest);
417 pBitBuf->WriteString(msg);
419 g_UserMsgs.EndMessage();
424 bool CHalfLife2::HintTextMsg(int client, const char *msg)
426 bf_write *pBitBuf = NULL;
427 cell_t players[] = {client};
429 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
434 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
435 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
437 pBitBuf->WriteByte(1);
439 pBitBuf->WriteString(msg);
440 g_UserMsgs.EndMessage();
445 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
447 bf_write *pBitBuf = NULL;
449 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
454 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
455 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
457 pBitBuf->WriteByte(1);
459 pBitBuf->WriteString(msg);
460 g_UserMsgs.EndMessage();
465 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
467 bf_write *pBitBuf = NULL;
468 KeyValues *SubKey = NULL;
470 cell_t players[] = {client};
472 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
479 SubKey = data->GetFirstSubKey();
483 SubKey = SubKey->GetNextKey();
485 SubKey = data->GetFirstSubKey();
488 pBitBuf->WriteString(name);
489 pBitBuf->WriteByte((show) ? 1 : 0);
490 pBitBuf->WriteByte(count);
493 pBitBuf->WriteString(SubKey->GetName());
494 pBitBuf->WriteString(SubKey->GetString());
495 SubKey = SubKey->GetNextKey();
497 g_UserMsgs.EndMessage();
502 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
504 DelayedFakeCliCmd *pFake;
506 if (m_FreeCmds.empty())
508 pFake = new DelayedFakeCliCmd;
510 pFake = m_FreeCmds.front();
514 pFake->client = client;
515 pFake->userid = userid;
516 pFake->cmd.assign(cmd);
518 m_CmdQueue.push(pFake);
521 void CHalfLife2::ProcessFakeCliCmdQueue()
523 while (!m_CmdQueue.empty())
525 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
527 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
529 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
530 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
537 bool CHalfLife2::IsLANServer()
539 sv_lan = icvar->FindVar("sv_lan");
546 return (sv_lan->GetInt() != 0);
549 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
551 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
552 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
554 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
559 Assert(_heapchk() == _HEAPOK);
562 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
566 // load file into a null-terminated buffer
567 int fileSize = filesystem->Size(f);
568 char *buffer = (char *)MemAllocScratch(fileSize + 1);
572 filesystem->Read(buffer, fileSize, f); // read into local buffer
574 buffer[fileSize] = 0; // null terminate file as EOF
576 filesystem->Close( f ); // close file after reading
578 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
586 return kv->LoadFromFile(filesystem, resourceName, pathID);
590 void CHalfLife2::PushCommandStack(const CCommand *cmd)
592 CachedCommandInfo info;
595 #if SOURCE_ENGINE <= SE_DARKMESSIAH
596 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
599 m_CommandStack.push(info);
602 const CCommand *CHalfLife2::PeekCommandStack()
604 if (m_CommandStack.empty())
609 return m_CommandStack.front().args;
612 void CHalfLife2::PopCommandStack()
614 m_CommandStack.pop();
617 const char *CHalfLife2::CurrentCommandName()
619 #if SOURCE_ENGINE >= SE_ORANGEBOX
620 return m_CommandStack.front().args->Arg(0);
622 return m_CommandStack.front().cmd;
626 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
628 DelayedKickInfo kick;
630 kick.client = client;
631 kick.userid = userid;
632 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
634 m_DelayedKicks.push(kick);
637 void CHalfLife2::ProcessDelayedKicks()
639 while (!m_DelayedKicks.empty())
641 DelayedKickInfo info = m_DelayedKicks.first();
642 m_DelayedKicks.pop();
644 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
645 if (player == NULL || player->GetUserId() != info.userid)
650 player->Kick(info.buffer);
654 edict_t *CHalfLife2::EdictOfIndex(int index)
656 return ::PEntityOfEntIndex(index);
659 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
661 return ::IndexOfEdict(pEnt);
664 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
671 int index = hndl.GetEntryIndex();
673 edict_t *pStoredEdict;
674 CBaseEntity *pStoredEntity;
676 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
681 if (pStoredEdict == NULL || pStoredEntity == NULL)
686 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
693 if (pSE->GetRefEHandle() != hndl)
701 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
703 IServerEntity *pEntOther = pEnt->GetIServerEntity();
705 if (pEntOther == NULL)
713 const char *CHalfLife2::GetCurrentMap()
715 return STRING(gpGlobals->mapname);
718 void CHalfLife2::ServerCommand(const char *buffer)
720 engine->ServerCommand(buffer);
723 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
725 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
726 CBaseHandle hndl = pUnknown->GetRefEHandle();
727 return (hndl.ToInt() | (1<<31));
730 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
732 CEntInfo *pInfo = NULL;
734 if (entRef & (1<<31))
736 /* Proper ent reference */
737 int hndlValue = entRef & ~(1<<31);
738 CBaseHandle hndl(hndlValue);
740 pInfo = LookupEntity(hndl.GetEntryIndex());
741 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
748 /* Old style index only */
749 pInfo = LookupEntity(entRef);
757 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
760 return pUnk->GetBaseEntity();
767 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
769 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
771 if (!g_EntList || entInfoOffset == -1)
773 /* Attempt to use engine interface instead */
774 static CEntInfo tempInfo;
775 tempInfo.m_pNext = NULL;
776 tempInfo.m_pPrev = NULL;
778 edict_t *pEdict = PEntityOfEntIndex(entIndex);
785 IServerUnknown *pUnk = pEdict->GetUnknown();
792 tempInfo.m_pEntity = pUnk;
793 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
798 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
799 return &pArray[entIndex];
803 SERIAL_MASK = 0x7fff (15 bits)
805 #define MAX_EDICT_BITS 11
806 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
807 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
809 Top 5 bits of a handle are unused.
810 Bit 31 - Our 'reference' flag indicator
813 cell_t CHalfLife2::IndexToReference(int entIndex)
815 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
818 return INVALID_EHANDLE_INDEX;
821 return EntityToReference(pEnt);
824 int CHalfLife2::ReferenceToIndex(cell_t entRef)
826 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
828 return INVALID_EHANDLE_INDEX;
831 if (entRef & (1<<31))
833 /* Proper ent reference */
834 int hndlValue = entRef & ~(1<<31);
835 CBaseHandle hndl(hndlValue);
837 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
839 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
841 return INVALID_EHANDLE_INDEX;
844 return hndl.GetEntryIndex();
850 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
854 return INVALID_EHANDLE_INDEX;
857 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
858 CBaseHandle hndl = pUnknown->GetRefEHandle();
860 if (hndl.GetEntryIndex() >= MAX_EDICTS)
862 return (hndl.ToInt() | (1<<31));
866 return hndl.GetEntryIndex();
870 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
872 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
874 return INVALID_EHANDLE_INDEX;
877 int hndlValue = entRef & ~(1<<31);
878 CBaseHandle hndl(hndlValue);
880 if (hndl.GetEntryIndex() < MAX_EDICTS)
882 return hndl.GetEntryIndex();
888 void *CHalfLife2::GetGlobalEntityList()
893 int CHalfLife2::GetSendPropOffset(SendProp *prop)
895 return prop->GetOffset();