mmsplugin.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /**
  2. * vim: set ts=4 sw=4 tw=99 noet :
  3. * ======================================================
  4. * TF2 Dynamic Schema Injector
  5. * Written by nosoop
  6. * ======================================================
  7. */
  8. #include <stdio.h>
  9. #include "mmsplugin.h"
  10. #include <utlmap.h>
  11. #include <utlstring.h>
  12. #include <KeyValues.h>
  13. #include <filesystem.h>
  14. #include "memscan.h"
  15. SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
  16. SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, 0, bool, char const *, char const *, char const *, char const *, bool, bool);
  17. DynSchema g_Plugin;
  18. IServerGameDLL *server = nullptr;
  19. IVEngineServer *engine = NULL;
  20. IFileSystem *filesystem = nullptr;
  21. PLUGIN_EXPOSE(DynSchema, g_Plugin);
  22. class ISchemaAttributeType;
  23. // this may need to be updated in the future
  24. class CEconItemAttributeDefinition
  25. {
  26. public:
  27. // TODO implementing ~CEconItemAttributeDefinition segfaults. not sure what's up.
  28. // ideally we implement it to match the game so InsertOrReplace is sure to work correctly
  29. /* 0x00 */ KeyValues *m_KeyValues;
  30. /* 0x04 */ unsigned short m_iIndex;
  31. /* 0x08 */ ISchemaAttributeType *m_AttributeType;
  32. /* 0x0c */ bool m_bHidden;
  33. /* 0x0d */ bool m_bForceOutputDescription;
  34. /* 0x0e */ bool m_bStoreAsInteger;
  35. /* 0x0f */ bool m_bInstanceData;
  36. /* 0x10 */ int m_iAssetClassExportType;
  37. /* 0x14 */ int m_iAssetClassBucket;
  38. /* 0x18 */ bool m_bIsSetBonus;
  39. /* 0x1c */ int m_iIsUserGenerated;
  40. /* 0x20 */ int m_iEffectType;
  41. /* 0x24 */ int m_iDescriptionFormat;
  42. /* 0x28 */ char *m_pszDescriptionString;
  43. /* 0x2c */ char *m_pszArmoryDesc;
  44. /* 0x30 */ char *m_pszName;
  45. /* 0x34 */ char *m_pszAttributeClass;
  46. /* 0x38 */ bool m_bCanAffectMarketName;
  47. /* 0x39 */ bool m_bCanAffectRecipeCompName;
  48. /* 0x3c */ int m_nTagHandle;
  49. /* 0x40 */ string_t m_iszAttributeClass;
  50. };
  51. // binary refers to 0x58 when iterating over the attribute map, so we'll refer to that value
  52. // we could also do a runtime assertion
  53. static_assert(sizeof(CEconItemAttributeDefinition) + 0x14 == 0x58, "CEconItemAttributeDefinition size mismatch");
  54. // pointer to item schema attribute map singleton
  55. using AttributeMap = CUtlMap<int, CEconItemAttributeDefinition, int>;
  56. AttributeMap *g_SchemaAttributes;
  57. using GetEconItemSchemaFn_t = uintptr_t();
  58. GetEconItemSchemaFn_t *fnGetEconItemSchema = nullptr;
  59. // https://www.unknowncheats.me/wiki/Calling_Functions_From_Injected_Library_Using_Function_Pointers_in_C%2B%2B
  60. #ifdef WIN32
  61. typedef bool (__thiscall *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  62. #elif defined(_LINUX)
  63. typedef bool (__cdecl *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  64. #endif
  65. CEconItemAttributeInitFromKV_fn fnItemAttributeInitFromKV = nullptr;
  66. const char* NATIVE_ATTRIB_DIR = "addons/sourcemod/configs/tf2nativeattribs";
  67. bool DynSchema::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
  68. {
  69. PLUGIN_SAVEVARS();
  70. GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
  71. GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
  72. GET_V_IFACE_CURRENT(GetFileSystemFactory, filesystem, IFileSystem, FILESYSTEM_INTERFACE_VERSION);
  73. SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  74. // get the base address of the server
  75. #if _WINDOWS
  76. CWinLibInfo lib(server);
  77. lib.LocatePattern("\xE8\x2A\x2A\x2A\x2A\x83\xC0\x04\xC3", 9, (void**) &fnGetEconItemSchema);
  78. lib.LocatePattern("\x55\x8B\xEC\x53\x8B\x5D\x08\x56\x8B\xF1\x8B\xCB\x57\xE8\x2A\x2A\x2A\x2A", 18, (void**) &fnItemAttributeInitFromKV);
  79. #elif _LINUX
  80. CLinuxLibInfo lib(server);
  81. lib.LocateSymbol("_ZN28CEconItemAttributeDefinition11BInitFromKVEP9KeyValuesP10CUtlVectorI10CUtlString10CUtlMemoryIS3_iEE",
  82. (void**) &fnItemAttributeInitFromKV);
  83. lib.LocateSymbol("_Z15GEconItemSchemav", (void**) &fnGetEconItemSchema);
  84. #endif
  85. if (!fnItemAttributeInitFromKV || !fnGetEconItemSchema) {
  86. META_CONPRINTF("Failed to get GEIS or BIFKV\n");
  87. return false;
  88. }
  89. // is this late enough in the MM:S load stage? we might just have to hold the function
  90. g_SchemaAttributes = reinterpret_cast<AttributeMap*>(fnGetEconItemSchema() + 0x1BC);
  91. return true;
  92. }
  93. bool DynSchema::Unload(char *error, size_t maxlen) {
  94. SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  95. return true;
  96. }
  97. /**
  98. * Initializes a CEconItemAttributeDefinition from a KeyValues definition, then inserts or
  99. * replaces the appropriate entry in the schema.
  100. */
  101. bool InsertOrReplaceAttribute(KeyValues *pAttribKV) {
  102. int attrdef = atoi(pAttribKV->GetName());
  103. if (attrdef <= 0) {
  104. return false;
  105. }
  106. // TODO only replace injected attribute if it exists
  107. // embed additional custom data into attribute KV; econdata and the like can deal with this
  108. // one could also add this data into the file itself, but this leaves less room for error
  109. pAttribKV->SetBool("injected", true);
  110. CEconItemAttributeDefinition def;
  111. fnItemAttributeInitFromKV(&def, pAttribKV, nullptr);
  112. // TODO verify that this doesn't leak, or just shrug it off
  113. g_SchemaAttributes->InsertOrReplace(attrdef, def);
  114. return true;
  115. }
  116. bool DynSchema::Hook_LevelInitPost(const char *pMapName, char const *pMapEntities,
  117. char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) {
  118. // this hook should fire shortly after the schema is (re)initialized
  119. char game_path[256];
  120. engine->GetGameDir(game_path, sizeof(game_path));
  121. char buffer[1024];
  122. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s",
  123. game_path, "addons/dynattrs/items_dynamic.txt");
  124. // always initialize attributes -- it's better than losing attributes on schema reinit
  125. // collect raw attribute keyvalue entries scattered across files
  126. KeyValues::AutoDelete rawAttributes("attributes");
  127. // read our own dynamic schema file -- this one supports other sections
  128. KeyValues::AutoDelete pKVMainConfig("DynamicSchema");
  129. if (pKVMainConfig->LoadFromFile(filesystem, buffer)) {
  130. // TODO check for devattribs folder and import KVs from there, then do a final pass
  131. KeyValues *pKVAttributes = pKVMainConfig->FindKey( "attributes" );
  132. if (pKVAttributes) {
  133. rawAttributes->RecursiveMergeKeyValues(pKVAttributes);
  134. META_CONPRINTF("Successfully injected custom schema %s\n", buffer);
  135. } else {
  136. META_CONPRINTF("Failed to inject custom schema %s\n", buffer);
  137. }
  138. }
  139. // iterate over TF2 Hidden Dev Attributes KV format
  140. // https://forums.alliedmods.net/showthread.php?t=326853
  141. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s/*", game_path, NATIVE_ATTRIB_DIR);
  142. FileFindHandle_t findHandle;
  143. const char *filename = filesystem->FindFirst(buffer, &findHandle);
  144. while (filename) {
  145. char pathbuf[1024];
  146. g_SMAPI->PathFormat(pathbuf, sizeof(pathbuf), "%s/%s/%s", game_path,
  147. NATIVE_ATTRIB_DIR, filename);
  148. if (!filesystem->FindIsDirectory(findHandle)) {
  149. KeyValues::AutoDelete nativeAttribConfig("attributes");
  150. nativeAttribConfig->LoadFromFile(filesystem, pathbuf);
  151. rawAttributes->RecursiveMergeKeyValues(nativeAttribConfig);
  152. META_CONPRINTF("Discovered custom schema %s\n", pathbuf);
  153. }
  154. filename = filesystem->FindNext(findHandle);
  155. }
  156. filesystem->FindClose(findHandle);
  157. // finally process our attributes
  158. FOR_EACH_TRUE_SUBKEY(rawAttributes, kv) {
  159. InsertOrReplaceAttribute(kv);
  160. }
  161. return true;
  162. }
  163. void DynSchema::AllPluginsLoaded() {
  164. /* This is where we'd do stuff that relies on the mod or other plugins
  165. * being initialized (for example, cvars added and events registered).
  166. */
  167. }
  168. bool DynSchema::Pause(char *error, size_t maxlen) {
  169. return true;
  170. }
  171. bool DynSchema::Unpause(char *error, size_t maxlen) {
  172. return true;
  173. }
  174. const char *DynSchema::GetLicense() {
  175. return "Proprietary";
  176. }
  177. const char *DynSchema::GetVersion() {
  178. return "1.2.0";
  179. }
  180. const char *DynSchema::GetDate() {
  181. return __DATE__;
  182. }
  183. const char *DynSchema::GetLogTag() {
  184. return "dynschema";
  185. }
  186. const char *DynSchema::GetAuthor() {
  187. return "nosoop";
  188. }
  189. const char *DynSchema::GetDescription() {
  190. return "Injects user-defined content into the game schema";
  191. }
  192. const char *DynSchema::GetName() {
  193. return "TF2 Dynamic Schema";
  194. }
  195. const char *DynSchema::GetURL() {
  196. return "https://git.csrd.science/";
  197. }