2
0

CModHandler.cpp 33 KB

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