CModHandler.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. * CModHandler.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "filesystem/Filesystem.h"
  12. #include "VCMI_Lib.h"
  13. #include "JsonNode.h"
  14. class CModHandler;
  15. class CModIndentifier;
  16. class CModInfo;
  17. class JsonNode;
  18. class IHandlerBase;
  19. /// class that stores all object identifiers strings and maps them to numeric ID's
  20. /// if possible, objects ID's should be in format <type>.<name>, camelCase e.g. "creature.grandElf"
  21. class CIdentifierStorage
  22. {
  23. enum ELoadingState
  24. {
  25. LOADING,
  26. FINALIZING,
  27. FINISHED
  28. };
  29. struct ObjectCallback // entry created on ID request
  30. {
  31. std::string localScope; /// scope from which this ID was requested
  32. std::string remoteScope; /// scope in which this object must be found
  33. std::string type; /// type, e.g. creature, faction, hero, etc
  34. std::string name; /// string ID
  35. std::function<void(si32)> callback;
  36. bool optional;
  37. ObjectCallback(std::string localScope, std::string remoteScope,
  38. std::string type, std::string name,
  39. const std::function<void(si32)> & callback,
  40. bool optional);
  41. };
  42. struct ObjectData // entry created on ID registration
  43. {
  44. si32 id;
  45. std::string scope; /// scope in which this ID located
  46. bool operator==(const ObjectData & other) const
  47. {
  48. return id == other.id && scope == other.scope;
  49. }
  50. template <typename Handler> void serialize(Handler &h, const int version)
  51. {
  52. h & id;
  53. h & scope;
  54. }
  55. };
  56. std::multimap<std::string, ObjectData> registeredObjects;
  57. std::vector<ObjectCallback> scheduledRequests;
  58. ELoadingState state;
  59. /// Check if identifier can be valid (camelCase, point as separator)
  60. void checkIdentifier(std::string & ID);
  61. void requestIdentifier(ObjectCallback callback);
  62. bool resolveIdentifier(const ObjectCallback & callback);
  63. std::vector<ObjectData> getPossibleIdentifiers(const ObjectCallback & callback);
  64. public:
  65. CIdentifierStorage();
  66. virtual ~CIdentifierStorage();
  67. /// request identifier for specific object name.
  68. /// Function callback will be called during ID resolution phase of loading
  69. void requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback);
  70. ///fullName = [remoteScope:]type.name
  71. void requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)> & callback);
  72. void requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback);
  73. void requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback);
  74. /// try to request ID. If ID with such name won't be loaded, callback function will not be called
  75. void tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback);
  76. void tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback);
  77. /// get identifier immediately. If identifier is not know and not silent call will result in error message
  78. boost::optional<si32> getIdentifier(std::string scope, std::string type, std::string name, bool silent = false);
  79. boost::optional<si32> getIdentifier(std::string type, const JsonNode & name, bool silent = false);
  80. boost::optional<si32> getIdentifier(const JsonNode & name, bool silent = false);
  81. boost::optional<si32> getIdentifier(std::string scope, std::string fullName, bool silent = false);
  82. /// registers new object
  83. void registerObject(std::string scope, std::string type, std::string name, si32 identifier);
  84. /// called at the very end of loading to check for any missing ID's
  85. void finalize();
  86. template <typename Handler> void serialize(Handler &h, const int version)
  87. {
  88. h & registeredObjects;
  89. h & state;
  90. }
  91. };
  92. /// internal type to handle loading of one data type (e.g. artifacts, creatures)
  93. class DLL_LINKAGE ContentTypeHandler
  94. {
  95. public:
  96. struct ModInfo
  97. {
  98. /// mod data from this mod and for this mod
  99. JsonNode modData;
  100. /// mod data for this mod from other mods (patches)
  101. JsonNode patches;
  102. };
  103. /// handler to which all data will be loaded
  104. IHandlerBase * handler;
  105. std::string objectName;
  106. /// contains all loaded H3 data
  107. std::vector<JsonNode> originalData;
  108. std::map<std::string, ModInfo> modData;
  109. ContentTypeHandler(IHandlerBase * handler, std::string objectName);
  110. /// local version of methods in ContentHandler
  111. /// returns true if loading was successful
  112. bool preloadModData(std::string modName, std::vector<std::string> fileList, bool validate);
  113. bool loadMod(std::string modName, bool validate);
  114. void loadCustom();
  115. void afterLoadFinalization();
  116. };
  117. /// class used to load all game data into handlers. Used only during loading
  118. class DLL_LINKAGE CContentHandler
  119. {
  120. /// preloads all data from fileList as data from modName.
  121. bool preloadModData(std::string modName, JsonNode modConfig, bool validate);
  122. /// actually loads data in mod
  123. bool loadMod(std::string modName, bool validate);
  124. std::map<std::string, ContentTypeHandler> handlers;
  125. public:
  126. CContentHandler();
  127. void init();
  128. /// preloads all data from fileList as data from modName.
  129. void preloadData(CModInfo & mod);
  130. /// actually loads data in mod
  131. void load(CModInfo & mod);
  132. void loadCustom();
  133. /// all data was loaded, time for final validation / integration
  134. void afterLoadFinalization();
  135. const ContentTypeHandler & operator[] (const std::string & name) const;
  136. };
  137. typedef std::string TModID;
  138. class DLL_LINKAGE CModInfo
  139. {
  140. public:
  141. enum EValidationStatus
  142. {
  143. PENDING,
  144. FAILED,
  145. PASSED
  146. };
  147. struct Version
  148. {
  149. int major = 0;
  150. int minor = 0;
  151. int patch = 0;
  152. Version() = default;
  153. Version(int mj, int mi, int p): major(mj), minor(mi), patch(p) {}
  154. static Version GameVersion();
  155. static Version fromString(std::string from);
  156. std::string toString() const;
  157. bool compatible(const Version & other, bool checkMinor = false, bool checkPatch = false) const;
  158. bool isNull() const;
  159. template <typename Handler> void serialize(Handler &h, const int version)
  160. {
  161. h & major;
  162. h & minor;
  163. h & patch;
  164. }
  165. };
  166. /// identifier, identical to name of folder with mod
  167. std::string identifier;
  168. /// human-readable strings
  169. std::string name;
  170. std::string description;
  171. /// version of the mod
  172. Version version;
  173. /// vcmi versions compatible with the mod
  174. Version vcmiCompatibleMin, vcmiCompatibleMax;
  175. /// list of mods that should be loaded before this one
  176. std::set <TModID> dependencies;
  177. /// list of mods that can't be used in the same time as this one
  178. std::set <TModID> conflicts;
  179. /// CRC-32 checksum of the mod
  180. ui32 checksum;
  181. /// true if mod is enabled
  182. bool enabled;
  183. EValidationStatus validation;
  184. JsonNode config;
  185. CModInfo();
  186. CModInfo(std::string identifier, const JsonNode & local, const JsonNode & config);
  187. JsonNode saveLocalData() const;
  188. void updateChecksum(ui32 newChecksum);
  189. static std::string getModDir(std::string name);
  190. static std::string getModFile(std::string name);
  191. private:
  192. void loadLocalData(const JsonNode & data);
  193. };
  194. class DLL_LINKAGE CModHandler
  195. {
  196. std::map <TModID, CModInfo> allMods;
  197. std::vector <TModID> activeMods;//active mods, in order in which they were loaded
  198. CModInfo coreMod;
  199. void loadConfigFromFile(std::string name);
  200. bool hasCircularDependency(TModID mod, std::set <TModID> currentList = std::set <TModID>()) const;
  201. //returns false if mod list is incorrect and prints error to console. Possible errors are:
  202. // - missing dependency mod
  203. // - conflicting mod in load order
  204. // - circular dependencies
  205. bool checkDependencies(const std::vector <TModID> & input) const;
  206. /**
  207. * 1. Set apart mods with resolved dependencies from mods which have unresolved dependencies
  208. * 2. Sort resolved mods using topological algorithm
  209. * 3. Log all problem mods and their unresolved dependencies
  210. *
  211. * @param modsToResolve list of valid mod IDs (checkDependencies returned true - TODO: Clarify it.)
  212. * @return a vector of the topologically sorted resolved mods: child nodes (dependent mods) have greater index than parents
  213. */
  214. std::vector <TModID> validateAndSortDependencies(std::vector <TModID> modsToResolve) const;
  215. std::vector<std::string> getModList(std::string path);
  216. void loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods);
  217. void loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods);
  218. public:
  219. class DLL_LINKAGE Incompatibility: public std::exception
  220. {
  221. public:
  222. using StringPair = std::pair<const std::string, const std::string>;
  223. using ModList = std::list<StringPair>;
  224. Incompatibility(ModList && _missingMods):
  225. missingMods(std::move(_missingMods))
  226. {
  227. std::ostringstream _ss;
  228. for(auto & m : missingMods)
  229. _ss << m.first << ' ' << m.second << std::endl;
  230. message = _ss.str();
  231. }
  232. const char * what() const noexcept override
  233. {
  234. return message.c_str();
  235. }
  236. private:
  237. //list of mods required to load the game
  238. // first: mod name
  239. // second: mod version
  240. const ModList missingMods;
  241. std::string message;
  242. };
  243. CIdentifierStorage identifiers;
  244. std::shared_ptr<CContentHandler> content; //(!)Do not serialize
  245. /// receives list of available mods and trying to load mod.json from all of them
  246. void initializeConfig();
  247. void loadMods(bool onlyEssential = false);
  248. void loadModFilesystems();
  249. std::set<TModID> getModDependencies(TModID modId, bool & isModFound);
  250. /// returns list of all (active) mods
  251. std::vector<std::string> getAllMods();
  252. std::vector<std::string> getActiveMods();
  253. /// load content from all available mods
  254. void load();
  255. void afterLoad(bool onlyEssential);
  256. struct DLL_LINKAGE hardcodedFeatures
  257. {
  258. JsonNode data;
  259. int CREEP_SIZE; // neutral stacks won't grow beyond this number
  260. int WEEKLY_GROWTH; //percent
  261. int NEUTRAL_STACK_EXP;
  262. int MAX_BUILDING_PER_TURN;
  263. bool DWELLINGS_ACCUMULATE_CREATURES;
  264. bool ALL_CREATURES_GET_DOUBLE_MONTHS;
  265. int MAX_HEROES_AVAILABLE_PER_PLAYER;
  266. int MAX_HEROES_ON_MAP_PER_PLAYER;
  267. bool WINNING_HERO_WITH_NO_TROOPS_RETREATS;
  268. bool BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE;
  269. bool NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS;
  270. template <typename Handler> void serialize(Handler &h, const int version)
  271. {
  272. h & data;
  273. h & CREEP_SIZE;
  274. h & WEEKLY_GROWTH;
  275. h & NEUTRAL_STACK_EXP;
  276. h & MAX_BUILDING_PER_TURN;
  277. h & DWELLINGS_ACCUMULATE_CREATURES;
  278. h & ALL_CREATURES_GET_DOUBLE_MONTHS;
  279. h & MAX_HEROES_AVAILABLE_PER_PLAYER;
  280. h & MAX_HEROES_ON_MAP_PER_PLAYER;
  281. h & WINNING_HERO_WITH_NO_TROOPS_RETREATS;
  282. h & BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE;
  283. h & NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS;
  284. }
  285. } settings;
  286. struct DLL_LINKAGE gameModules
  287. {
  288. bool STACK_EXP;
  289. bool STACK_ARTIFACT;
  290. bool COMMANDERS;
  291. bool MITHRIL;
  292. template <typename Handler> void serialize(Handler &h, const int version)
  293. {
  294. h & STACK_EXP;
  295. h & STACK_ARTIFACT;
  296. h & COMMANDERS;
  297. h & MITHRIL;
  298. }
  299. } modules;
  300. CModHandler();
  301. virtual ~CModHandler();
  302. static std::string normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier);
  303. static void parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier);
  304. static std::string makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier);
  305. template <typename Handler> void serialize(Handler &h, const int version)
  306. {
  307. if(h.saving)
  308. {
  309. h & activeMods;
  310. for(const auto & m : activeMods)
  311. h & allMods[m].version;
  312. }
  313. else
  314. {
  315. loadMods();
  316. std::vector<TModID> newActiveMods;
  317. h & newActiveMods;
  318. Incompatibility::ModList missingMods;
  319. for(auto & m : newActiveMods)
  320. {
  321. CModInfo::Version mver;
  322. h & mver;
  323. if(allMods.count(m) && (allMods[m].version.isNull() || mver.isNull() || allMods[m].version.compatible(mver)))
  324. allMods[m].enabled = true;
  325. else
  326. missingMods.emplace_back(m, mver.toString());
  327. }
  328. if(!missingMods.empty())
  329. throw Incompatibility(std::move(missingMods));
  330. std::swap(activeMods, newActiveMods);
  331. }
  332. h & settings;
  333. h & modules;
  334. h & identifiers;
  335. }
  336. };