2
0

CModHandler.cpp 34 KB

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