CModHandler.cpp 37 KB

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