CModHandler.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. /*
  2. * CModHandler.cpp, 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. #include "StdInc.h"
  11. #include "CModHandler.h"
  12. #include "mapObjects/CObjectClassesHandler.h"
  13. #include "filesystem/FileStream.h"
  14. #include "filesystem/AdapterLoaders.h"
  15. #include "filesystem/CFilesystemLoader.h"
  16. #include "CCreatureHandler.h"
  17. #include "CArtHandler.h"
  18. #include "CTownHandler.h"
  19. #include "CHeroHandler.h"
  20. #include "mapObjects/CObjectHandler.h"
  21. #include "StringConstants.h"
  22. #include "CStopWatch.h"
  23. #include "IHandlerBase.h"
  24. #include "spells/CSpellHandler.h"
  25. #include "CSkillHandler.h"
  26. #include "ScriptHandler.h"
  27. #include "BattleFieldHandler.h"
  28. #include "ObstacleHandler.h"
  29. #include <vstd/StringUtils.h>
  30. CIdentifierStorage::CIdentifierStorage():
  31. state(LOADING)
  32. {
  33. }
  34. CIdentifierStorage::~CIdentifierStorage()
  35. {
  36. }
  37. void CIdentifierStorage::checkIdentifier(std::string & ID)
  38. {
  39. if (boost::algorithm::ends_with(ID, "."))
  40. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  41. else
  42. {
  43. size_t pos = 0;
  44. do
  45. {
  46. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  47. {
  48. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  49. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  50. }
  51. pos = ID.find('.', pos);
  52. }
  53. while(pos++ != std::string::npos);
  54. }
  55. }
  56. CIdentifierStorage::ObjectCallback::ObjectCallback(
  57. std::string localScope, std::string remoteScope, std::string type,
  58. std::string name, const std::function<void(si32)> & callback,
  59. bool optional):
  60. localScope(localScope),
  61. remoteScope(remoteScope),
  62. type(type),
  63. name(name),
  64. callback(callback),
  65. optional(optional)
  66. {}
  67. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  68. {
  69. checkIdentifier(callback.type);
  70. checkIdentifier(callback.name);
  71. assert(!callback.localScope.empty());
  72. if (state != FINISHED) // enqueue request if loading is still in progress
  73. scheduledRequests.push_back(callback);
  74. else // execute immediately for "late" requests
  75. resolveIdentifier(callback);
  76. }
  77. void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  78. {
  79. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  80. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, false));
  81. }
  82. void CIdentifierStorage::requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)>& callback)
  83. {
  84. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  85. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  86. requestIdentifier(ObjectCallback(scope, scopeAndFullName.first, typeAndName.first, typeAndName.second, callback, false));
  87. }
  88. void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  89. {
  90. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  91. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, false));
  92. }
  93. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  94. {
  95. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  96. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  97. requestIdentifier(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, callback, false));
  98. }
  99. void CIdentifierStorage::tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  100. {
  101. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  102. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, true));
  103. }
  104. void CIdentifierStorage::tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  105. {
  106. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  107. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, true));
  108. }
  109. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string type, std::string name, bool silent)
  110. {
  111. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  112. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  113. if (idList.size() == 1)
  114. return idList.front().id;
  115. if (!silent)
  116. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  117. return boost::optional<si32>();
  118. }
  119. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string type, const JsonNode & name, bool silent)
  120. {
  121. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  122. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  123. if (idList.size() == 1)
  124. return idList.front().id;
  125. if (!silent)
  126. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  127. return boost::optional<si32>();
  128. }
  129. boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
  130. {
  131. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  132. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  133. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  134. if (idList.size() == 1)
  135. return idList.front().id;
  136. if (!silent)
  137. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), pair2.first, name.meta);
  138. return boost::optional<si32>();
  139. }
  140. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string fullName, bool silent)
  141. {
  142. auto pair = vstd::splitStringToPair(fullName, ':'); // remoteScope:<type.name>
  143. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  144. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  145. if (idList.size() == 1)
  146. return idList.front().id;
  147. if (!silent)
  148. logMod->error("Failed to resolve identifier %s of type %s from mod %s", fullName, pair2.first, scope);
  149. return boost::optional<si32>();
  150. }
  151. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  152. {
  153. ObjectData data;
  154. data.scope = scope;
  155. data.id = identifier;
  156. std::string fullID = type + '.' + name;
  157. checkIdentifier(fullID);
  158. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  159. if(!vstd::containsMapping(registeredObjects, mapping))
  160. {
  161. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  162. registeredObjects.insert(mapping);
  163. }
  164. }
  165. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request)
  166. {
  167. std::set<std::string> allowedScopes;
  168. bool isValidScope = true;
  169. if (request.remoteScope.empty())
  170. {
  171. // normally ID's from all required mods, own mod and virtual "core" mod are allowed
  172. if(request.localScope != "core" && !request.localScope.empty())
  173. {
  174. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  175. if(!isValidScope)
  176. return std::vector<ObjectData>();
  177. }
  178. allowedScopes.insert(request.localScope);
  179. allowedScopes.insert("core");
  180. }
  181. else
  182. {
  183. //...unless destination mod was specified explicitly
  184. //note: getModDependencies does not work for "core" by design
  185. //for map format support core mod has access to any mod
  186. //TODO: better solution for access from map?
  187. if(request.localScope == "core" || request.localScope == "")
  188. {
  189. allowedScopes.insert(request.remoteScope);
  190. }
  191. else
  192. {
  193. // allow only available to all core mod or dependencies
  194. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  195. if(!isValidScope)
  196. return std::vector<ObjectData>();
  197. if(request.remoteScope == "core" || request.remoteScope == request.localScope || myDeps.count(request.remoteScope))
  198. allowedScopes.insert(request.remoteScope);
  199. }
  200. }
  201. std::string fullID = request.type + '.' + request.name;
  202. auto entries = registeredObjects.equal_range(fullID);
  203. if (entries.first != entries.second)
  204. {
  205. std::vector<ObjectData> locatedIDs;
  206. for (auto it = entries.first; it != entries.second; it++)
  207. {
  208. if (vstd::contains(allowedScopes, it->second.scope))
  209. {
  210. locatedIDs.push_back(it->second);
  211. }
  212. }
  213. return locatedIDs;
  214. }
  215. return std::vector<ObjectData>();
  216. }
  217. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  218. {
  219. auto identifiers = getPossibleIdentifiers(request);
  220. if (identifiers.size() == 1) // normally resolved ID
  221. {
  222. request.callback(identifiers.front().id);
  223. return true;
  224. }
  225. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  226. {
  227. return true;
  228. }
  229. // error found. Try to generate some debug info
  230. if (identifiers.size() == 0)
  231. logMod->error("Unknown identifier!");
  232. else
  233. logMod->error("Ambiguous identifier request!");
  234. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  235. for (auto id : identifiers)
  236. {
  237. logMod->error("\tID is available in mod %s", id.scope);
  238. }
  239. return false;
  240. }
  241. void CIdentifierStorage::finalize()
  242. {
  243. state = FINALIZING;
  244. bool errorsFound = false;
  245. //Note: we may receive new requests during resolution phase -> end may change -> range for can't be used
  246. for(auto it = scheduledRequests.begin(); it != scheduledRequests.end(); it++)
  247. {
  248. errorsFound |= !resolveIdentifier(*it);
  249. }
  250. if (errorsFound)
  251. {
  252. for(auto object : registeredObjects)
  253. {
  254. logMod->trace("%s : %s -> %d", object.second.scope, object.first, object.second.id);
  255. }
  256. logMod->error("All known identifiers were dumped into log file");
  257. }
  258. assert(errorsFound == false);
  259. state = FINISHED;
  260. }
  261. ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
  262. handler(handler),
  263. objectName(objectName),
  264. originalData(handler->loadLegacyData((size_t)VLC->modh->settings.data["textData"][objectName].Float()))
  265. {
  266. for(auto & node : originalData)
  267. {
  268. node.setMeta("core");
  269. }
  270. }
  271. bool ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList, bool validate)
  272. {
  273. bool result;
  274. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  275. data.setMeta(modName);
  276. ModInfo & modInfo = modData[modName];
  277. for(auto entry : data.Struct())
  278. {
  279. size_t colon = entry.first.find(':');
  280. if (colon == std::string::npos)
  281. {
  282. // normal object, local to this mod
  283. modInfo.modData[entry.first].swap(entry.second);
  284. }
  285. else
  286. {
  287. std::string remoteName = entry.first.substr(0, colon);
  288. std::string objectName = entry.first.substr(colon + 1);
  289. // patching this mod? Send warning and continue - this situation can be handled normally
  290. if (remoteName == modName)
  291. logMod->warn("Redundant namespace definition for %s", objectName);
  292. logMod->trace("Patching object %s (%s) from %s", objectName, remoteName, modName);
  293. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  294. JsonUtils::merge(remoteConf, entry.second);
  295. }
  296. }
  297. return result;
  298. }
  299. bool ContentTypeHandler::loadMod(std::string modName, bool validate)
  300. {
  301. ModInfo & modInfo = modData[modName];
  302. bool result = true;
  303. auto performValidate = [&,this](JsonNode & data, const std::string & name){
  304. handler->beforeValidate(data);
  305. if (validate)
  306. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  307. };
  308. // apply patches
  309. if (!modInfo.patches.isNull())
  310. JsonUtils::merge(modInfo.modData, modInfo.patches);
  311. for(auto & entry : modInfo.modData.Struct())
  312. {
  313. const std::string & name = entry.first;
  314. JsonNode & data = entry.second;
  315. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  316. {
  317. // try to add H3 object data
  318. size_t index = static_cast<size_t>(data["index"].Float());
  319. if(originalData.size() > index)
  320. {
  321. logMod->trace("found original data in loadMod(%s) at index %d", name, index);
  322. JsonUtils::merge(originalData[index], data);
  323. std::swap(originalData[index], data);
  324. originalData[index].clear(); // do not use same data twice (same ID)
  325. }
  326. else
  327. {
  328. logMod->warn("no original data in loadMod(%s) at index %d", name, index);
  329. }
  330. performValidate(data, name);
  331. handler->loadObject(modName, name, data, index);
  332. }
  333. else
  334. {
  335. // normal new object
  336. logMod->trace("no index in loadMod(%s)", name);
  337. performValidate(data,name);
  338. handler->loadObject(modName, name, data);
  339. }
  340. }
  341. return result;
  342. }
  343. void ContentTypeHandler::loadCustom()
  344. {
  345. handler->loadCustom();
  346. }
  347. void ContentTypeHandler::afterLoadFinalization()
  348. {
  349. handler->afterLoadFinalization();
  350. }
  351. CContentHandler::CContentHandler()
  352. {
  353. }
  354. void CContentHandler::init()
  355. {
  356. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  357. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  358. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  359. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  360. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  361. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  362. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  363. handlers.insert(std::make_pair("skills", ContentTypeHandler(VLC->skillh, "skill")));
  364. handlers.insert(std::make_pair("templates", ContentTypeHandler((IHandlerBase *)VLC->tplh, "template")));
  365. #if SCRIPTING_ENABLED
  366. handlers.insert(std::make_pair("scripts", ContentTypeHandler(VLC->scriptHandler, "script")));
  367. #endif
  368. handlers.insert(std::make_pair("battlefields", ContentTypeHandler(VLC->battlefieldsHandler, "battlefield")));
  369. handlers.insert(std::make_pair("obstacles", ContentTypeHandler(VLC->obstacleHandler, "obstacle")));
  370. //TODO: any other types of moddables?
  371. }
  372. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  373. {
  374. bool result = true;
  375. for(auto & handler : handlers)
  376. {
  377. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  378. }
  379. return result;
  380. }
  381. bool CContentHandler::loadMod(std::string modName, bool validate)
  382. {
  383. bool result = true;
  384. for(auto & handler : handlers)
  385. {
  386. result &= handler.second.loadMod(modName, validate);
  387. }
  388. return result;
  389. }
  390. void CContentHandler::loadCustom()
  391. {
  392. for(auto & handler : handlers)
  393. {
  394. handler.second.loadCustom();
  395. }
  396. }
  397. void CContentHandler::afterLoadFinalization()
  398. {
  399. for(auto & handler : handlers)
  400. {
  401. handler.second.afterLoadFinalization();
  402. }
  403. }
  404. void CContentHandler::preloadData(CModInfo & mod)
  405. {
  406. bool validate = (mod.validation != CModInfo::PASSED);
  407. // print message in format [<8-symbols checksum>] <modname>
  408. logMod->info("\t\t[%08x]%s", mod.checksum, mod.name);
  409. if (validate && mod.identifier != "core")
  410. {
  411. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  412. mod.validation = CModInfo::FAILED;
  413. }
  414. if (!preloadModData(mod.identifier, mod.config, validate))
  415. mod.validation = CModInfo::FAILED;
  416. }
  417. void CContentHandler::load(CModInfo & mod)
  418. {
  419. bool validate = (mod.validation != CModInfo::PASSED);
  420. if (!loadMod(mod.identifier, validate))
  421. mod.validation = CModInfo::FAILED;
  422. if (validate)
  423. {
  424. if (mod.validation != CModInfo::FAILED)
  425. logMod->info("\t\t[DONE] %s", mod.name);
  426. else
  427. logMod->error("\t\t[FAIL] %s", mod.name);
  428. }
  429. else
  430. logMod->info("\t\t[SKIP] %s", mod.name);
  431. }
  432. const ContentTypeHandler & CContentHandler::operator[](const std::string & name) const
  433. {
  434. return handlers.at(name);
  435. }
  436. static JsonNode loadModSettings(std::string path)
  437. {
  438. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  439. {
  440. return JsonNode(ResourceID(path, EResType::TEXT));
  441. }
  442. // Probably new install. Create initial configuration
  443. CResourceHandler::get("local")->createResource(path);
  444. return JsonNode();
  445. }
  446. JsonNode addMeta(JsonNode config, std::string meta)
  447. {
  448. config.setMeta(meta);
  449. return config;
  450. }
  451. CModInfo::Version CModInfo::Version::GameVersion()
  452. {
  453. return Version(GameConstants::VCMI_VERSION_MAJOR, GameConstants::VCMI_VERSION_MINOR, GameConstants::VCMI_VERSION_PATCH);
  454. }
  455. CModInfo::Version CModInfo::Version::fromString(std::string from)
  456. {
  457. int major = 0, minor = 0, patch = 0;
  458. try
  459. {
  460. auto pointPos = from.find('.');
  461. major = std::stoi(from.substr(0, pointPos));
  462. if(pointPos != std::string::npos)
  463. {
  464. from = from.substr(pointPos + 1);
  465. pointPos = from.find('.');
  466. minor = std::stoi(from.substr(0, pointPos));
  467. if(pointPos != std::string::npos)
  468. patch = std::stoi(from.substr(pointPos + 1));
  469. }
  470. }
  471. catch(const std::invalid_argument & e)
  472. {
  473. return Version();
  474. }
  475. return Version(major, minor, patch);
  476. }
  477. std::string CModInfo::Version::toString() const
  478. {
  479. return std::to_string(major) + '.' + std::to_string(minor) + '.' + std::to_string(patch);
  480. }
  481. bool CModInfo::Version::compatible(const Version & other, bool checkMinor, bool checkPatch) const
  482. {
  483. return (major == other.major &&
  484. (!checkMinor || minor >= other.minor) &&
  485. (!checkPatch || minor > other.minor || (minor == other.minor && patch >= other.patch)));
  486. }
  487. bool CModInfo::Version::isNull() const
  488. {
  489. return major == 0 && minor == 0 && patch == 0;
  490. }
  491. CModInfo::CModInfo():
  492. checksum(0),
  493. enabled(false),
  494. validation(PENDING)
  495. {
  496. }
  497. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  498. identifier(identifier),
  499. name(config["name"].String()),
  500. description(config["description"].String()),
  501. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  502. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  503. checksum(0),
  504. enabled(false),
  505. validation(PENDING),
  506. config(addMeta(config, identifier))
  507. {
  508. version = Version::fromString(config["version"].String());
  509. if(!config["compatibility"].isNull())
  510. {
  511. vcmiCompatibleMin = Version::fromString(config["compatibility"]["min"].String());
  512. vcmiCompatibleMax = Version::fromString(config["compatibility"]["max"].String());
  513. }
  514. loadLocalData(local);
  515. }
  516. JsonNode CModInfo::saveLocalData() const
  517. {
  518. std::ostringstream stream;
  519. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  520. JsonNode conf;
  521. conf["active"].Bool() = enabled;
  522. conf["validated"].Bool() = validation != FAILED;
  523. conf["checksum"].String() = stream.str();
  524. return conf;
  525. }
  526. std::string CModInfo::getModDir(std::string name)
  527. {
  528. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  529. }
  530. std::string CModInfo::getModFile(std::string name)
  531. {
  532. return getModDir(name) + "/mod.json";
  533. }
  534. void CModInfo::updateChecksum(ui32 newChecksum)
  535. {
  536. // comment-out next line to force validation of all mods ignoring checksum
  537. if (newChecksum != checksum)
  538. {
  539. checksum = newChecksum;
  540. validation = PENDING;
  541. }
  542. }
  543. void CModInfo::loadLocalData(const JsonNode & data)
  544. {
  545. bool validated = false;
  546. enabled = true;
  547. checksum = 0;
  548. if (data.getType() == JsonNode::JsonType::DATA_BOOL)
  549. {
  550. enabled = data.Bool();
  551. }
  552. if (data.getType() == JsonNode::JsonType::DATA_STRUCT)
  553. {
  554. enabled = data["active"].Bool();
  555. validated = data["validated"].Bool();
  556. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  557. }
  558. //check compatibility
  559. bool wasEnabled = enabled;
  560. enabled = enabled && (vcmiCompatibleMin.isNull() || Version::GameVersion().compatible(vcmiCompatibleMin));
  561. enabled = enabled && (vcmiCompatibleMax.isNull() || vcmiCompatibleMax.compatible(Version::GameVersion()));
  562. if(wasEnabled && !enabled)
  563. logGlobal->warn("Mod %s is incompatible with current version of VCMI and cannot be enabled", name);
  564. if (enabled)
  565. validation = validated ? PASSED : PENDING;
  566. else
  567. validation = validated ? PASSED : FAILED;
  568. }
  569. CModHandler::CModHandler() : content(std::make_shared<CContentHandler>())
  570. {
  571. modules.COMMANDERS = false;
  572. modules.STACK_ARTIFACT = false;
  573. modules.STACK_EXP = false;
  574. modules.MITHRIL = false;
  575. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  576. {
  577. identifiers.registerObject("core", "resource", GameConstants::RESOURCE_NAMES[i], i);
  578. }
  579. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  580. {
  581. identifiers.registerObject("core", "primSkill", PrimarySkill::names[i], i);
  582. identifiers.registerObject("core", "primarySkill", PrimarySkill::names[i], i);
  583. }
  584. }
  585. CModHandler::~CModHandler()
  586. {
  587. }
  588. void CModHandler::loadConfigFromFile (std::string name)
  589. {
  590. std::string paths;
  591. for(auto& p : CResourceHandler::get()->getResourceNames(ResourceID("config/" + name)))
  592. {
  593. paths += p.string() + ", ";
  594. }
  595. paths = paths.substr(0, paths.size() - 2);
  596. logMod->debug("Loading hardcoded features settings from [%s], result:", paths);
  597. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  598. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  599. settings.MAX_HEROES_AVAILABLE_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Integer());
  600. logMod->debug("\tMAX_HEROES_AVAILABLE_PER_PLAYER\t%d", settings.MAX_HEROES_AVAILABLE_PER_PLAYER);
  601. settings.MAX_HEROES_ON_MAP_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Integer());
  602. logMod->debug("\tMAX_HEROES_ON_MAP_PER_PLAYER\t%d", settings.MAX_HEROES_ON_MAP_PER_PLAYER);
  603. settings.CREEP_SIZE = static_cast<int>(hardcodedFeatures["CREEP_SIZE"].Integer());
  604. logMod->debug("\tCREEP_SIZE\t%d", settings.CREEP_SIZE);
  605. settings.WEEKLY_GROWTH = static_cast<int>(hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Integer());
  606. logMod->debug("\tWEEKLY_GROWTH\t%d", settings.WEEKLY_GROWTH);
  607. settings.NEUTRAL_STACK_EXP = static_cast<int>(hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Integer());
  608. logMod->debug("\tNEUTRAL_STACK_EXP\t%d", settings.NEUTRAL_STACK_EXP);
  609. settings.MAX_BUILDING_PER_TURN = static_cast<int>(hardcodedFeatures["MAX_BUILDING_PER_TURN"].Integer());
  610. logMod->debug("\tMAX_BUILDING_PER_TURN\t%d", settings.MAX_BUILDING_PER_TURN);
  611. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  612. logMod->debug("\tDWELLINGS_ACCUMULATE_CREATURES\t%d", static_cast<int>(settings.DWELLINGS_ACCUMULATE_CREATURES));
  613. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  614. logMod->debug("\tALL_CREATURES_GET_DOUBLE_MONTHS\t%d", static_cast<int>(settings.ALL_CREATURES_GET_DOUBLE_MONTHS));
  615. settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS = hardcodedFeatures["WINNING_HERO_WITH_NO_TROOPS_RETREATS"].Bool();
  616. logMod->debug("\tWINNING_HERO_WITH_NO_TROOPS_RETREATS\t%d", static_cast<int>(settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS));
  617. settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE = hardcodedFeatures["BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE"].Bool();
  618. logMod->debug("\tBLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE\t%d", static_cast<int>(settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE));
  619. settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS = hardcodedFeatures["NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS"].Bool();
  620. logMod->debug("\tNO_RANDOM_SPECIAL_WEEKS_AND_MONTHS\t%d", static_cast<int>(settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS));
  621. const JsonNode & gameModules = settings.data["modules"];
  622. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  623. logMod->debug("\tSTACK_EXP\t%d", static_cast<int>(modules.STACK_EXP));
  624. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  625. logMod->debug("\tSTACK_ARTIFACT\t%d", static_cast<int>(modules.STACK_ARTIFACT));
  626. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  627. logMod->debug("\tCOMMANDERS\t%d", static_cast<int>(modules.COMMANDERS));
  628. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  629. logMod->debug("\tMITHRIL\t%d", static_cast<int>(modules.MITHRIL));
  630. }
  631. // currentList is passed by value to get current list of depending mods
  632. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  633. {
  634. const CModInfo & mod = allMods.at(modID);
  635. // Mod already present? We found a loop
  636. if (vstd::contains(currentList, modID))
  637. {
  638. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  639. logMod->error("\t%s -> ", mod.name);
  640. return true;
  641. }
  642. currentList.insert(modID);
  643. // recursively check every dependency of this mod
  644. for(const TModID & dependency : mod.dependencies)
  645. {
  646. if (hasCircularDependency(dependency, currentList))
  647. {
  648. logMod->error("\t%s ->\n", mod.name); // conflict detected, print dependency list
  649. return true;
  650. }
  651. }
  652. return false;
  653. }
  654. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  655. {
  656. for(const TModID & id : input)
  657. {
  658. const CModInfo & mod = allMods.at(id);
  659. for(const TModID & dep : mod.dependencies)
  660. {
  661. if(!vstd::contains(input, dep))
  662. {
  663. logMod->error("Error: Mod %s requires missing %s!", mod.name, dep);
  664. return false;
  665. }
  666. }
  667. for(const TModID & conflicting : mod.conflicts)
  668. {
  669. if(vstd::contains(input, conflicting))
  670. {
  671. logMod->error("Error: Mod %s conflicts with %s!", mod.name, allMods.at(conflicting).name);
  672. return false;
  673. }
  674. }
  675. if(hasCircularDependency(id))
  676. return false;
  677. }
  678. return true;
  679. }
  680. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  681. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  682. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  683. {
  684. // Topological sort algorithm.
  685. // TODO: Investigate possible ways to improve performance.
  686. boost::range::sort(modsToResolve); // Sort mods per name
  687. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  688. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  689. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  690. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  691. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  692. {
  693. if(mod.dependencies.size() > resolvedModIDs.size())
  694. return CModInfo::PENDING;
  695. for(const TModID & dependency : mod.dependencies)
  696. {
  697. if(!vstd::contains(resolvedModIDs, dependency))
  698. return CModInfo::PENDING;
  699. }
  700. return CModInfo::PASSED;
  701. };
  702. while(true)
  703. {
  704. std::set <TModID> resolvedOnCurrentTreeLevel;
  705. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  706. {
  707. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  708. {
  709. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  710. sortedValidMods.push_back(*it);
  711. it = modsToResolve.erase(it);
  712. continue;
  713. }
  714. it++;
  715. }
  716. if(resolvedOnCurrentTreeLevel.size())
  717. {
  718. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  719. continue;
  720. }
  721. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  722. break;
  723. }
  724. // Left mods have unresolved dependencies, output all to log.
  725. for(const auto & brokenModID : modsToResolve)
  726. {
  727. const CModInfo & brokenMod = allMods.at(brokenModID);
  728. for(const TModID & dependency : brokenMod.dependencies)
  729. {
  730. if(!vstd::contains(resolvedModIDs, dependency))
  731. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.name, dependency);
  732. }
  733. }
  734. return sortedValidMods;
  735. }
  736. std::vector<std::string> CModHandler::getModList(std::string path)
  737. {
  738. std::string modDir = boost::to_upper_copy(path + "MODS/");
  739. size_t depth = boost::range::count(modDir, '/');
  740. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  741. {
  742. if (id.getType() != EResType::DIRECTORY)
  743. return false;
  744. if (!boost::algorithm::starts_with(id.getName(), modDir))
  745. return false;
  746. if (boost::range::count(id.getName(), '/') != depth )
  747. return false;
  748. return true;
  749. });
  750. //storage for found mods
  751. std::vector<std::string> foundMods;
  752. for (auto & entry : list)
  753. {
  754. std::string name = entry.getName();
  755. name.erase(0, modDir.size()); //Remove path prefix
  756. if (!name.empty())
  757. foundMods.push_back(name);
  758. }
  759. return foundMods;
  760. }
  761. void CModHandler::loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods)
  762. {
  763. for(std::string modName : getModList(path))
  764. loadOneMod(modName, parent, modSettings, enableMods);
  765. }
  766. void CModHandler::loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods)
  767. {
  768. boost::to_lower(modName);
  769. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  770. if(CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  771. {
  772. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  773. if (!parent.empty()) // this is submod, add parent to dependencies
  774. mod.dependencies.insert(parent);
  775. allMods[modFullName] = mod;
  776. if (mod.enabled && enableMods)
  777. activeMods.push_back(modFullName);
  778. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.enabled);
  779. }
  780. }
  781. void CModHandler::loadMods(bool onlyEssential)
  782. {
  783. JsonNode modConfig;
  784. if(onlyEssential)
  785. {
  786. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  787. }
  788. else
  789. {
  790. modConfig = loadModSettings("config/modSettings.json");
  791. loadMods("", "", modConfig["activeMods"], true);
  792. }
  793. coreMod = CModInfo("core", modConfig["core"], JsonNode(ResourceID("config/gameConfig.json")));
  794. coreMod.name = "Original game files";
  795. }
  796. std::vector<std::string> CModHandler::getAllMods()
  797. {
  798. std::vector<std::string> modlist;
  799. for (auto & entry : allMods)
  800. modlist.push_back(entry.first);
  801. return modlist;
  802. }
  803. std::vector<std::string> CModHandler::getActiveMods()
  804. {
  805. return activeMods;
  806. }
  807. static JsonNode genDefaultFS()
  808. {
  809. // default FS config for mods: directory "Content" that acts as H3 root directory
  810. JsonNode defaultFS;
  811. defaultFS[""].Vector().resize(2);
  812. defaultFS[""].Vector()[0]["type"].String() = "zip";
  813. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  814. defaultFS[""].Vector()[1]["type"].String() = "dir";
  815. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  816. return defaultFS;
  817. }
  818. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  819. {
  820. static const JsonNode defaultFS = genDefaultFS();
  821. if (!conf["filesystem"].isNull())
  822. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  823. else
  824. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  825. }
  826. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  827. {
  828. boost::crc_32_type modChecksum;
  829. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  830. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  831. // second - add mod.json into checksum because filesystem does not contains this file
  832. // FIXME: remove workaround for core mod
  833. if (modName != "core")
  834. {
  835. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  836. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  837. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  838. }
  839. // third - add all detected text files from this mod into checksum
  840. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  841. {
  842. return resID.getType() == EResType::TEXT &&
  843. ( boost::starts_with(resID.getName(), "DATA") ||
  844. boost::starts_with(resID.getName(), "CONFIG"));
  845. });
  846. for (const ResourceID & file : files)
  847. {
  848. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  849. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  850. }
  851. return modChecksum.checksum();
  852. }
  853. void CModHandler::loadModFilesystems()
  854. {
  855. activeMods = validateAndSortDependencies(activeMods);
  856. coreMod.updateChecksum(calculateModChecksum("core", CResourceHandler::get("core")));
  857. for(std::string & modName : activeMods)
  858. {
  859. CModInfo & mod = allMods[modName];
  860. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  861. }
  862. }
  863. std::set<TModID> CModHandler::getModDependencies(TModID modId, bool & isModFound)
  864. {
  865. auto it = allMods.find(modId);
  866. isModFound = (it != allMods.end());
  867. if(isModFound)
  868. return it->second.dependencies;
  869. logMod->error("Mod not found: '%s'", modId);
  870. return std::set<TModID>();
  871. }
  872. void CModHandler::initializeConfig()
  873. {
  874. loadConfigFromFile("defaultMods.json");
  875. }
  876. void CModHandler::load()
  877. {
  878. CStopWatch totalTime, timer;
  879. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  880. content->init();
  881. for(const TModID & modName : activeMods)
  882. {
  883. logMod->trace("Generating checksum for %s", modName);
  884. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  885. }
  886. // first - load virtual "core" mod that contains all data
  887. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  888. content->preloadData(coreMod);
  889. for(const TModID & modName : activeMods)
  890. content->preloadData(allMods[modName]);
  891. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  892. content->load(coreMod);
  893. for(const TModID & modName : activeMods)
  894. content->load(allMods[modName]);
  895. #if SCRIPTING_ENABLED
  896. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  897. #endif
  898. content->loadCustom();
  899. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  900. VLC->creh->loadCrExpBon();
  901. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  902. identifiers.finalize();
  903. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  904. content->afterLoadFinalization();
  905. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  906. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  907. }
  908. void CModHandler::afterLoad(bool onlyEssential)
  909. {
  910. JsonNode modSettings;
  911. for (auto & modEntry : allMods)
  912. {
  913. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  914. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  915. }
  916. modSettings["core"] = coreMod.saveLocalData();
  917. if(!onlyEssential)
  918. {
  919. FileStream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::out | std::ofstream::trunc);
  920. file << modSettings.toJson();
  921. }
  922. }
  923. std::string CModHandler::normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier)
  924. {
  925. auto p = vstd::splitStringToPair(identifier, ':');
  926. if(p.first.empty())
  927. p.first = scope;
  928. if(p.first == remoteScope)
  929. p.first.clear();
  930. return p.first.empty() ? p.second : p.first + ":" + p.second;
  931. }
  932. void CModHandler::parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier)
  933. {
  934. auto p = vstd::splitStringToPair(fullIdentifier, ':');
  935. scope = p.first;
  936. auto p2 = vstd::splitStringToPair(p.second, '.');
  937. if(p2.first != "")
  938. {
  939. type = p2.first;
  940. identifier = p2.second;
  941. }
  942. else
  943. {
  944. type = p.second;
  945. identifier = "";
  946. }
  947. }
  948. std::string CModHandler::makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier)
  949. {
  950. if(type == "")
  951. logGlobal->error("Full identifier (%s %s) requires type name", scope, identifier);
  952. std::string actualScope = scope;
  953. std::string actualName = identifier;
  954. //ignore scope if identifier is scoped
  955. auto scopeAndName = vstd::splitStringToPair(identifier, ':');
  956. if(scopeAndName.first != "")
  957. {
  958. actualScope = scopeAndName.first;
  959. actualName = scopeAndName.second;
  960. }
  961. if(actualScope == "")
  962. {
  963. return actualName == "" ? type : type + "." + actualName;
  964. }
  965. else
  966. {
  967. return actualName == "" ? actualScope+ ":" + type : actualScope + ":" + type + "." + actualName;
  968. }
  969. }