CModHandler.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. #include "StdInc.h"
  2. #include "CModHandler.h"
  3. #include "CDefObjInfoHandler.h"
  4. #include "JsonNode.h"
  5. #include "filesystem/CResourceLoader.h"
  6. #include "filesystem/ISimpleResourceLoader.h"
  7. #include "CCreatureHandler.h"
  8. #include "CArtHandler.h"
  9. #include "CTownHandler.h"
  10. #include "CHeroHandler.h"
  11. #include "CObjectHandler.h"
  12. #include "StringConstants.h"
  13. #include "CStopWatch.h"
  14. #include "IHandlerBase.h"
  15. /*
  16. * CModHandler.cpp, part of VCMI engine
  17. *
  18. * Authors: listed in file AUTHORS in main folder
  19. *
  20. * License: GNU General Public License v2.0 or later
  21. * Full text of license available in license.txt file, in main folder
  22. *
  23. */
  24. void CIdentifierStorage::checkIdentifier(std::string & ID)
  25. {
  26. if (boost::algorithm::ends_with(ID, "."))
  27. logGlobal->warnStream() << "BIG WARNING: identifier " << ID << " seems to be broken!";
  28. else
  29. {
  30. size_t pos = 0;
  31. do
  32. {
  33. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  34. {
  35. logGlobal->warnStream() << "Warning: identifier " << ID << " is not in camelCase!";
  36. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  37. }
  38. pos = ID.find('.', pos);
  39. }
  40. while(pos++ != std::string::npos);
  41. }
  42. }
  43. void CIdentifierStorage::requestIdentifier(std::string name, const boost::function<void(si32)> & callback)
  44. {
  45. checkIdentifier(name);
  46. // old version with immediate callback posibility. Can't be used for some cases
  47. /* auto iter = registeredObjects.find(name);
  48. if (iter != registeredObjects.end())
  49. callback(iter->second); //already registered - trigger callback immediately
  50. else
  51. {
  52. if(boost::algorithm::starts_with(name, "primSkill."))
  53. logGlobal->warnStream() << "incorrect primSkill name requested";
  54. missingObjects[name].push_back(callback); // queue callback
  55. }*/
  56. missingObjects[name].push_back(callback); // queue callback
  57. }
  58. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  59. {
  60. //TODO: use scope
  61. std::string fullID = type + '.' + name;
  62. checkIdentifier(fullID);
  63. // do not allow to register same object twice
  64. assert(registeredObjects.find(fullID) == registeredObjects.end());
  65. registeredObjects[fullID] = identifier;
  66. // old version with immediate callback posibility. Can't be used for some cases
  67. /*auto iter = missingObjects.find(fullID);
  68. if (iter != missingObjects.end())
  69. {
  70. //call all awaiting callbacks
  71. BOOST_FOREACH(auto function, iter->second)
  72. {
  73. function(identifier);
  74. }
  75. missingObjects.erase(iter);
  76. }*/
  77. }
  78. void CIdentifierStorage::finalize()
  79. {
  80. for (auto it = missingObjects.begin(); it!= missingObjects.end();)
  81. {
  82. auto object = registeredObjects.find(it->first);
  83. if (object != registeredObjects.end())
  84. {
  85. BOOST_FOREACH(auto function, it->second)
  86. {
  87. function(object->second);
  88. }
  89. it = missingObjects.erase(it);
  90. }
  91. else
  92. it++;
  93. }
  94. // print list of missing objects and crash
  95. // in future should try to do some cleanup (like returning all id's as 0)
  96. if (!missingObjects.empty())
  97. {
  98. BOOST_FOREACH(auto object, missingObjects)
  99. {
  100. logGlobal->errorStream() << "Error: object " << object.first << " was not found!";
  101. }
  102. BOOST_FOREACH(auto object, registeredObjects)
  103. {
  104. logGlobal->traceStream() << object.first << " -> " << object.second;
  105. }
  106. logGlobal->errorStream() << "All known identifiers were dumped into log file";
  107. }
  108. assert(missingObjects.empty());
  109. }
  110. CContentHandler::ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, size_t size, std::string objectName):
  111. handler(handler),
  112. objectName(objectName),
  113. originalData(handler->loadLegacyData(size))
  114. {
  115. }
  116. void CContentHandler::ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList)
  117. {
  118. JsonNode data = JsonUtils::assembleFromFiles(fileList);
  119. ModInfo & modInfo = modData[modName];
  120. BOOST_FOREACH(auto entry, data.Struct())
  121. {
  122. size_t colon = entry.first.find(':');
  123. if (colon == std::string::npos)
  124. {
  125. // normal object, local to this mod
  126. modInfo.modData[entry.first].swap(entry.second);
  127. }
  128. else
  129. {
  130. std::string remoteName = entry.first.substr(0, colon);
  131. std::string objectName = entry.first.substr(colon + 1);
  132. // patching this mod? Send warning and continue - this situation can be handled normally
  133. if (remoteName == modName)
  134. logGlobal->warnStream() << "Redundant namespace definition for " << objectName;
  135. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  136. JsonUtils::merge(remoteConf, entry.second);
  137. }
  138. }
  139. }
  140. void CContentHandler::ContentTypeHandler::loadMod(std::string modName)
  141. {
  142. ModInfo & modInfo = modData[modName];
  143. // apply patches
  144. if (!modInfo.patches.isNull())
  145. JsonUtils::merge(modInfo.modData, modInfo.patches);
  146. BOOST_FOREACH(auto entry, modInfo.modData.Struct())
  147. {
  148. const std::string & name = entry.first;
  149. JsonNode & data = entry.second;
  150. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  151. {
  152. // try to add H3 object data
  153. size_t index = data["index"].Float();
  154. if (originalData.size() > index)
  155. {
  156. JsonUtils::merge(originalData[index], data);
  157. JsonUtils::validate(originalData[index], "vcmi:" + objectName, name);
  158. handler->loadObject(modName, name, originalData[index], index);
  159. originalData[index].clear(); // do not use same data twice (same ID)
  160. continue;
  161. }
  162. }
  163. // normal new object
  164. JsonUtils::validate(data, "vcmi:" + objectName, name);
  165. handler->loadObject(modName, name, data);
  166. }
  167. }
  168. CContentHandler::CContentHandler()
  169. {
  170. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, GameConstants::F_NUMBER * 2, "heroClass")));
  171. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, GameConstants::ARTIFACTS_QUANTITY, "artifact")));
  172. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, GameConstants::CREATURES_COUNT, "creature")));
  173. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, GameConstants::F_NUMBER, "faction")));
  174. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, GameConstants::HEROES_QUANTITY, "hero")));
  175. //TODO: spells, bonuses, something else?
  176. }
  177. void CContentHandler::preloadModData(std::string modName, JsonNode modConfig)
  178. {
  179. BOOST_FOREACH(auto & handler, handlers)
  180. {
  181. handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >());
  182. }
  183. }
  184. void CContentHandler::loadMod(std::string modName)
  185. {
  186. BOOST_FOREACH(auto & handler, handlers)
  187. {
  188. handler.second.loadMod(modName);
  189. }
  190. }
  191. CModHandler::CModHandler()
  192. {
  193. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  194. {
  195. identifiers.registerObject("core", "resource", GameConstants::RESOURCE_NAMES[i], i);
  196. }
  197. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  198. identifiers.registerObject("core", "primSkill", PrimarySkill::names[i], i);
  199. loadConfigFromFile ("defaultMods");
  200. }
  201. void CModHandler::loadConfigFromFile (std::string name)
  202. {
  203. const JsonNode config(ResourceID("config/" + name + ".json"));
  204. const JsonNode & hardcodedFeatures = config["hardcodedFeatures"];
  205. settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float();
  206. settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float();
  207. settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float();
  208. settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float();
  209. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  210. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  211. const JsonNode & gameModules = config["modules"];
  212. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  213. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  214. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  215. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  216. }
  217. // currentList is passed by value to get current list of depending mods
  218. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  219. {
  220. const CModInfo & mod = allMods.at(modID);
  221. // Mod already present? We found a loop
  222. if (vstd::contains(currentList, modID))
  223. {
  224. logGlobal->errorStream() << "Error: Circular dependency detected! Printing dependency list:";
  225. logGlobal->errorStream() << "\t" << mod.name << " -> ";
  226. return true;
  227. }
  228. currentList.insert(modID);
  229. // recursively check every dependency of this mod
  230. BOOST_FOREACH(const TModID & dependency, mod.dependencies)
  231. {
  232. if (hasCircularDependency(dependency, currentList))
  233. {
  234. logGlobal->errorStream() << "\t" << mod.name << " ->\n"; // conflict detected, print dependency list
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  241. {
  242. BOOST_FOREACH(const TModID & id, input)
  243. {
  244. const CModInfo & mod = allMods.at(id);
  245. BOOST_FOREACH(const TModID & dep, mod.dependencies)
  246. {
  247. if (!vstd::contains(input, dep))
  248. {
  249. logGlobal->errorStream() << "Error: Mod " << mod.name << " requires missing " << dep << "!";
  250. return false;
  251. }
  252. }
  253. BOOST_FOREACH(const TModID & conflicting, mod.conflicts)
  254. {
  255. if (vstd::contains(input, conflicting))
  256. {
  257. logGlobal->errorStream() << "Error: Mod " << mod.name << " conflicts with " << allMods.at(conflicting).name << "!";
  258. return false;
  259. }
  260. }
  261. if (hasCircularDependency(id))
  262. return false;
  263. }
  264. return true;
  265. }
  266. std::vector <TModID> CModHandler::resolveDependencies(std::vector <TModID> input) const
  267. {
  268. // Topological sort algorithm
  269. // May not be the fastest one but VCMI does not needs any speed here
  270. // Unless user have dozens of mods with complex dependencies this code should be fine
  271. // first - sort input to have input strictly based on name (and not on hashmap or anything else)
  272. boost::range::sort(input);
  273. std::vector <TModID> output;
  274. output.reserve(input.size());
  275. std::set <TModID> resolvedMods;
  276. // Check if all mod dependencies are resolved (moved to resolvedMods)
  277. auto isResolved = [&](const CModInfo mod) -> bool
  278. {
  279. BOOST_FOREACH(const TModID & dependency, mod.dependencies)
  280. {
  281. if (!vstd::contains(resolvedMods, dependency))
  282. return false;
  283. }
  284. return true;
  285. };
  286. while (!input.empty())
  287. {
  288. std::set <TModID> toResolve; // list of mods resolved on this iteration
  289. for (auto it = input.begin(); it != input.end();)
  290. {
  291. if (isResolved(allMods.at(*it)))
  292. {
  293. toResolve.insert(*it);
  294. output.push_back(*it);
  295. it = input.erase(it);
  296. continue;
  297. }
  298. it++;
  299. }
  300. resolvedMods.insert(toResolve.begin(), toResolve.end());
  301. }
  302. return output;
  303. }
  304. void CModHandler::initialize(std::vector<std::string> availableMods)
  305. {
  306. std::string confName = "config/modSettings.json";
  307. JsonNode modConfig;
  308. // Porbably new install. Create initial configuration
  309. if (!CResourceHandler::get()->existsResource(ResourceID(confName)))
  310. CResourceHandler::get()->createResource(confName);
  311. else
  312. modConfig = JsonNode(ResourceID(confName));
  313. const JsonNode & modList = modConfig["activeMods"];
  314. JsonNode resultingList;
  315. std::vector <TModID> detectedMods;
  316. BOOST_FOREACH(std::string name, availableMods)
  317. {
  318. boost::to_lower(name);
  319. std::string modFileName = "mods/" + name + "/mod.json";
  320. if (CResourceHandler::get()->existsResource(ResourceID(modFileName)))
  321. {
  322. const JsonNode config = JsonNode(ResourceID(modFileName));
  323. if (config.isNull())
  324. continue;
  325. if (!modList[name].isNull() && modList[name].Bool() == false )
  326. {
  327. resultingList[name].Bool() = false;
  328. continue; // disabled mod
  329. }
  330. resultingList[name].Bool() = true;
  331. CModInfo & mod = allMods[name];
  332. mod.identifier = name;
  333. mod.name = config["name"].String();
  334. mod.description = config["description"].String();
  335. mod.dependencies = config["depends"].convertTo<std::set<std::string> >();
  336. mod.conflicts = config["conflicts"].convertTo<std::set<std::string> >();
  337. detectedMods.push_back(name);
  338. }
  339. else
  340. logGlobal->warnStream() << "\t\t Directory " << name << " does not contains VCMI mod";
  341. }
  342. if (!checkDependencies(detectedMods))
  343. {
  344. logGlobal->errorStream() << "Critical error: failed to load mods! Exiting...";
  345. exit(1);
  346. }
  347. activeMods = resolveDependencies(detectedMods);
  348. modConfig["activeMods"] = resultingList;
  349. CResourceHandler::get()->createResource("CONFIG/modSettings.json");
  350. std::ofstream file(CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::trunc);
  351. file << modConfig;
  352. }
  353. std::vector<std::string> CModHandler::getActiveMods()
  354. {
  355. return activeMods;
  356. }
  357. template<typename Handler>
  358. void CModHandler::handleData(Handler handler, const JsonNode & source, std::string listName, std::string schemaName)
  359. {
  360. JsonNode config = JsonUtils::assembleFromFiles(source[listName].convertTo<std::vector<std::string> >());
  361. BOOST_FOREACH(auto & entry, config.Struct())
  362. {
  363. if (!entry.second.isNull()) // may happens if mod removed object by setting json entry to null
  364. {
  365. JsonUtils::validate(entry.second, schemaName, entry.first);
  366. handler->load(entry.first, entry.second);
  367. }
  368. }
  369. }
  370. void CModHandler::loadGameContent()
  371. {
  372. CStopWatch timer, totalTime;
  373. CContentHandler content;
  374. logGlobal->infoStream() << "\tInitializing content hander: " << timer.getDiff() << " ms";
  375. // first - load virtual "core" mod tht contains all data
  376. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  377. content.preloadModData("core", JsonNode(ResourceID("config/gameConfig.json")));
  378. logGlobal->infoStream() << "\tParsing original game data: " << timer.getDiff() << " ms";
  379. BOOST_FOREACH(const TModID & modName, activeMods)
  380. {
  381. logGlobal->infoStream() << "\t\t" << allMods[modName].name;
  382. std::string modFileName = "mods/" + modName + "/mod.json";
  383. const JsonNode config = JsonNode(ResourceID(modFileName));
  384. JsonUtils::validate(config, "vcmi:mod", modName);
  385. content.preloadModData(modName, config);
  386. }
  387. logGlobal->infoStream() << "\tParsing mod data: " << timer.getDiff() << " ms";
  388. content.loadMod("core");
  389. logGlobal->infoStream() << "\tLoading original game data: " << timer.getDiff() << " ms";
  390. BOOST_FOREACH(const TModID & modName, activeMods)
  391. {
  392. content.loadMod(modName);
  393. logGlobal->infoStream() << "\t\t" << allMods[modName].name;
  394. }
  395. logGlobal->infoStream() << "\tLoading mod data: " << timer.getDiff() << "ms";
  396. logGlobal->infoStream() << "\tDone loading data";
  397. VLC->creh->loadCrExpBon();
  398. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  399. identifiers.finalize();
  400. logGlobal->infoStream() << "\tAll game content loaded in " << totalTime.getDiff() << " ms";
  401. }
  402. void CModHandler::reload()
  403. {
  404. {
  405. //recreate adventure map defs
  406. assert(!VLC->dobjinfo->gobjs[Obj::MONSTER].empty()); //make sure that at least some def info was found
  407. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::MONSTER].begin()->second;
  408. BOOST_FOREACH(auto & crea, VLC->creh->creatures)
  409. {
  410. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::MONSTER], crea->idNumber)) // no obj info for this type
  411. {
  412. CGDefInfo * info = new CGDefInfo(*baseInfo);
  413. info->subid = crea->idNumber;
  414. info->name = crea->advMapDef;
  415. VLC->dobjinfo->gobjs[Obj::MONSTER][crea->idNumber] = info;
  416. }
  417. }
  418. }
  419. {
  420. assert(!VLC->dobjinfo->gobjs[Obj::ARTIFACT].empty());
  421. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::ARTIFACT].begin()->second;
  422. BOOST_FOREACH(auto & art, VLC->arth->artifacts)
  423. {
  424. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::ARTIFACT], art->id)) // no obj info for this type
  425. {
  426. CGDefInfo * info = new CGDefInfo(*baseInfo);
  427. info->subid = art->id;
  428. info->name = art->advMapDef;
  429. VLC->dobjinfo->gobjs[Obj::ARTIFACT][art->id] = info;
  430. }
  431. }
  432. }
  433. {
  434. assert(!VLC->dobjinfo->gobjs[Obj::TOWN].empty()); //make sure that at least some def info was found
  435. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::TOWN].begin()->second;
  436. auto & townInfos = VLC->dobjinfo->gobjs[Obj::TOWN];
  437. BOOST_FOREACH(auto & faction, VLC->townh->factions)
  438. {
  439. TFaction index = faction->index;
  440. CTown * town = faction->town;
  441. if (town)
  442. {
  443. auto & cientInfo = town->clientInfo;
  444. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::TOWN], index)) // no obj info for this type
  445. {
  446. CGDefInfo * info = new CGDefInfo(*baseInfo);
  447. info->subid = index;
  448. townInfos[index] = info;
  449. }
  450. townInfos[index]->name = cientInfo.advMapCastle;
  451. VLC->dobjinfo->villages[index] = new CGDefInfo(*townInfos[index]);
  452. VLC->dobjinfo->villages[index]->name = cientInfo.advMapVillage;
  453. VLC->dobjinfo->capitols[index] = new CGDefInfo(*townInfos[index]);
  454. VLC->dobjinfo->capitols[index]->name = cientInfo.advMapCapitol;
  455. for (int i = 0; i < town->dwellings.size(); ++i)
  456. {
  457. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][i]; //get same blockmap as first dwelling of tier i
  458. BOOST_FOREACH (auto cre, town->creatures[i]) //both unupgraded and upgraded get same dwelling
  459. {
  460. CGDefInfo * info = new CGDefInfo(*baseInfo);
  461. info->subid = cre;
  462. info->name = town->dwellings[i];
  463. VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][cre] = info;
  464. VLC->objh->cregens[cre] = cre; //map of dwelling -> creature id
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }