Added support for Dark Messiah engine and game. (no bug, r=me).
The development of this feature would not be possible without the support of the following people from the game's community:
Dylan Riggs, Carl Pettengill, Ed Moreland, and Christian.
4 * ======================================================
6 * Copyright (C) 2004-2008 AlliedModders LLC and authors.
8 * ======================================================
10 * This software is provided 'as-is', without any express or implied warranty.
11 * In no event will the authors be held liable for any damages arising from
12 * the use of this software.
14 * Permission is granted to anyone to use this software for any purpose,
15 * including commercial applications, and to alter it and redistribute it
16 * freely, subject to the following restrictions:
18 * 1. The origin of this software must not be misrepresented; you must not
19 * claim that you wrote the original software. If you use this software in a
20 * product, an acknowledgment in the product documentation would be
21 * appreciated but is not required.
22 * 2. Altered source versions must be plainly marked as such, and must not be
23 * misrepresented as being the original software.
24 * 3. This notice may not be removed or altered from any source distribution.
30 #include "../metamod_oslink.h"
31 #include <sourcehook.h>
34 #include <tier0/icommandline.h>
35 #include <tier1/utldict.h>
36 #include <sh_vector.h>
37 #include <sh_string.h>
38 #include "../metamod_util.h"
39 #include "provider_ep2.h"
41 #include "metamod_console.h"
42 #include "vsp_listener.h"
43 #include <filesystem.h>
47 typedef void (*CONPRINTF_FUNC)(const char *, ...);
53 UsrMsgInfo(int s, const char *t) : size(s), name(t)
61 #if SOURCE_ENGINE == SE_DARKMESSIAH
63 DLL_IMPORT ICommandLine *CommandLine();
67 bool CacheUserMessages();
68 #if SOURCE_ENGINE >= SE_ORANGEBOX
69 void ClientCommand(edict_t *pEdict, const CCommand &args);
70 void LocalCommand_Meta(const CCommand &args);
72 void ClientCommand(edict_t *pEdict);
73 void LocalCommand_Meta();
76 void _ServerCommand();
78 static bool usermsgs_extracted = false;
79 static CVector<UsrMsgInfo> usermsgs_list;
80 static VSPListener g_VspListener;
81 static BaseProvider g_Ep1Provider;
82 static List<ConCommandBase *> conbases_unreg;
85 IFileSystem *baseFs = NULL;
86 IServerGameDLL *server = NULL;
87 IVEngineServer *engine = NULL;
88 IServerGameClients *gameclients = NULL;
89 IMetamodSourceProvider *provider = &g_Ep1Provider;
90 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
92 #if SOURCE_ENGINE >= SE_ORANGEBOX
93 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
95 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
98 bool AssumeUserMessages()
105 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
107 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
114 void BaseProvider::ConsolePrint(const char *str)
116 #if SOURCE_ENGINE >= SE_ORANGEBOX
123 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
124 CreateInterfaceFn serverFactory)
126 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
129 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
132 #if SOURCE_ENGINE >= SE_ORANGEBOX
133 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
135 icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
139 DisplayError("Could not find ICvar! Metamod cannot load.");
144 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
147 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
150 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
153 mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
157 #if SOURCE_ENGINE >= SE_ORANGEBOX
161 g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
163 if ((usermsgs_extracted = CacheUserMessages()) == false)
165 usermsgs_extracted = AssumeUserMessages();
168 #if SOURCE_ENGINE == SE_DARKMESSIAH
169 if (!g_SMConVarAccessor.InitConCommandBaseList())
171 /* This is very unlikely considering it's old engine */
172 mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
173 mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
179 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
183 void BaseProvider::Notify_DLLShutdown_Pre()
185 g_SMConVarAccessor.RemoveMetamodCommands();
187 #if SOURCE_ENGINE == SE_DARKMESSIAH
188 if (g_Metamod.IsLoadedAsGameDLL())
190 icvar->UnlinkVariables(FCVAR_GAMEDLL);
195 bool BaseProvider::IsRemotePrintingAvailable()
200 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
202 engine->ClientPrintf(client, message);
205 void BaseProvider::ServerCommand(const char *cmd)
207 engine->ServerCommand(cmd);
210 const char *BaseProvider::GetConVarString(ConVar *convar)
217 return convar->GetString();
220 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
222 convar->SetValue(str);
225 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
227 return pCommand->IsCommand();
231 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
233 return (build == SOURCE_ENGINE_ORIGINAL
234 || build == SOURCE_ENGINE_EPISODEONE);
237 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
239 if (key[0] == '-' || key[0] == '+')
241 return CommandLine()->ParmValue(key, defval);
246 if ((val = icvar->GetCommandLineValue(key)) == NULL)
257 int BaseProvider::TryServerGameDLL(const char *iface)
259 if (strncmp(iface, "ServerGameDLL", 13) != 0)
264 return atoi(&iface[13]);
267 bool BaseProvider::LogMessage(const char *buffer)
274 engine->LogPrint(buffer);
279 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
281 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
283 if (hook == ProvidedHook_LevelInit)
285 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
287 else if (hook == ProvidedHook_LevelShutdown)
289 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
291 else if (hook == ProvidedHook_GameInit)
293 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
298 return (mfi.thisptroffs >= 0);
301 void BaseProvider::DisplayError(const char *fmt, ...)
307 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
313 void BaseProvider::DisplayWarning(const char *fmt, ...)
319 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
325 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
327 return &g_SMConVarAccessor;
330 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
332 return g_SMConVarAccessor.Register(pCommand);
335 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
337 return g_SMConVarAccessor.Unregister(pCommand);
340 int BaseProvider::GetUserMessageCount()
342 if (!usermsgs_extracted)
347 return (int)usermsgs_list.size();
350 int BaseProvider::FindUserMessage(const char *name, int *size)
352 for (size_t i = 0; i < usermsgs_list.size(); i++)
354 if (usermsgs_list[i].name.compare(name) == 0)
358 *size = usermsgs_list[i].size;
367 const char *BaseProvider::GetUserMessage(int index, int *size)
369 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
376 *size = usermsgs_list[index].size;
379 return usermsgs_list[index].name.c_str();
382 const char *BaseProvider::GetGameDescription()
384 return server->GetGameDescription();
387 int BaseProvider::DetermineSourceEngine(const char *game)
389 #if SOURCE_ENGINE == SE_LEFT4DEAD
390 return SOURCE_ENGINE_LEFT4DEAD;
391 #elif SOURCE_ENGINE == SE_ORANGEBOX
392 return SOURCE_ENGINE_ORANGEBOX;
394 return SOURCE_ENGINE_DARKMESSIAH;
398 ConVar *BaseProvider::CreateConVar(const char *name,
404 if (flags & ConVarFlag_Notify)
406 newflags |= FCVAR_NOTIFY;
408 if (flags & ConVarFlag_SpOnly)
410 newflags |= FCVAR_SPONLY;
413 ConVar *pVar = new ConVar(name, defval, newflags, help);
415 g_SMConVarAccessor.RegisterConCommandBase(pVar);
420 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
427 g_VspListener.SetLoadable(true);
428 return &g_VspListener;
431 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
439 const char *plugin_file, *p_alias;
441 pValues = new KeyValues("Metamod Plugin");
443 if (!pValues->LoadFromFile(baseFs, file))
445 pValues->deleteThis();
449 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
451 pValues->deleteThis();
455 UTIL_Format(path, path_len, "%s", plugin_file);
457 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
459 UTIL_Format(alias, alias_len, "%s", p_alias);
463 UTIL_Format(alias, alias_len, "");
466 pValues->deleteThis();
471 #if SOURCE_ENGINE >= SE_ORANGEBOX
472 class GlobCommand : public IMetamodSourceCommandInfo
475 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
479 unsigned int GetArgCount()
481 return m_cmd->ArgC() - 1;
484 const char *GetArg(unsigned int num)
486 return m_cmd->Arg(num);
489 const char *GetArgString()
491 return m_cmd->ArgS();
494 const CCommand *m_cmd;
497 class GlobCommand : public IMetamodSourceCommandInfo
500 unsigned int GetArgCount()
502 return engine->Cmd_Argc() - 1;
505 const char *GetArg(unsigned int num)
507 return engine->Cmd_Argv(num);
510 const char *GetArgString()
512 return engine->Cmd_Args();
517 #if SOURCE_ENGINE >= SE_ORANGEBOX
518 void LocalCommand_Meta(const CCommand &args)
520 GlobCommand cmd(&args);
522 void LocalCommand_Meta()
529 #if SOURCE_ENGINE >= SE_ORANGEBOX
530 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
532 GlobCommand cmd(&_cmd);
534 void ClientCommand(edict_t *pEdict)
538 if (strcmp(cmd.GetArg(0), "meta") == 0)
540 Command_ClientMeta(pEdict, &cmd);
541 RETURN_META(MRES_SUPERCEDE);
544 RETURN_META(MRES_IGNORED);
547 //////////////////////////////////////////////////////////////////////
548 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
549 // Signatures necessary in finding the pointer to the CUtlDict that //
550 // stores user message information. //
551 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
552 // message indices. This is our answer to it. Yuck! <:-( //
553 //////////////////////////////////////////////////////////////////////
555 /* General Windows sig */
556 #define MSGCLASS_SIGLEN 7
557 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
558 #define MSGCLASS_OFFS 2
560 /* Dystopia Windows hack */
561 #define MSGCLASS2_SIGLEN 16
562 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
563 #define MSGCLASS2_OFFS 11
565 /* Windows frame pointer sig */
566 #define MSGCLASS3_SIGLEN 18
567 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
568 #define MSGCLASS3_OFFS 13
569 #elif defined OS_LINUX
570 /* No frame pointer sig */
571 #define MSGCLASS_SIGLEN 14
572 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
573 #define MSGCLASS_OFFS 9
575 /* Frame pointer sig */
576 #define MSGCLASS2_SIGLEN 16
577 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
578 #define MSGCLASS2_OFFS 11
587 typedef CUtlDict<UserMessage *, int> UserMsgDict;
589 /* This is the ugliest function in all of MM:S */
590 bool CacheUserMessages()
592 UserMsgDict *dict = NULL;
594 /* Get address of original GetUserMessageInfo() */
595 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
597 /* Oh dear, we have a relative jump on our hands
598 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
600 if (*vfunc == '\xE9')
602 /* Get address from displacement...
604 * Add 5 because it's relative to next instruction:
605 * Opcode <1 byte> + 32-bit displacement <4 bytes>
607 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
610 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
612 /* Get address of CUserMessages instance */
613 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
615 /* Get address of CUserMessages::m_UserMessages */
616 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
618 else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
621 /* If we get here, the code is possibly inlined like in Dystopia */
623 /* Get the address of the CUtlRBTree */
624 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
626 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
627 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
628 #elif defined OS_LINUX
629 /* Get address of CUserMessages instance */
630 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
632 /* Get address of CUserMessages::m_UserMessages */
633 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
637 else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
639 /* Get address of CUserMessages instance */
640 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
642 /* Get address of CUserMessages::m_UserMessages */
643 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
647 #if !defined OS_WIN32
651 if (GetFileOfAddress(vfunc, path, sizeof(path)))
653 void *handle = dlopen(path, RTLD_NOW);
656 void *addr = dlsym(handle, "usermessages");
661 dict = (UserMsgDict *)*(void **)addr;
670 int msg_count = dict->Count();
672 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
673 if (msg_count < 0 || msg_count > 255)
681 /* Cache messages in our CUtlDict */
682 for (int i = 0; i < msg_count; i++)
684 msg = dict->Element(i);
685 u_msg.name = msg->name;
686 u_msg.size = msg->size;
687 usermsgs_list.push_back(u_msg);