CModHandler.h 13 KB

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