CModHandler.cpp 35 KB

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