CModHandler.cpp 34 KB

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