CModHandler.cpp 32 KB

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