CTownHandler.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. /*
  2. * CTownHandler.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 "CTownHandler.h"
  12. #include "VCMI_Lib.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "JsonNode.h"
  15. #include "constants/StringConstants.h"
  16. #include "CCreatureHandler.h"
  17. #include "CHeroHandler.h"
  18. #include "CArtHandler.h"
  19. #include "GameSettings.h"
  20. #include "TerrainHandler.h"
  21. #include "spells/CSpellHandler.h"
  22. #include "filesystem/Filesystem.h"
  23. #include "bonuses/Bonus.h"
  24. #include "bonuses/Propagators.h"
  25. #include "ResourceSet.h"
  26. #include "mapObjectConstructors/AObjectTypeHandler.h"
  27. #include "mapObjectConstructors/CObjectClassesHandler.h"
  28. #include "modding/IdentifierStorage.h"
  29. #include "modding/ModScope.h"
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. const int NAMES_PER_TOWN=16; // number of town names per faction in H3 files. Json can define any number
  32. const std::map<std::string, CBuilding::EBuildMode> CBuilding::MODES =
  33. {
  34. { "normal", CBuilding::BUILD_NORMAL },
  35. { "auto", CBuilding::BUILD_AUTO },
  36. { "special", CBuilding::BUILD_SPECIAL },
  37. { "grail", CBuilding::BUILD_GRAIL }
  38. };
  39. const std::map<std::string, CBuilding::ETowerHeight> CBuilding::TOWER_TYPES =
  40. {
  41. { "low", CBuilding::HEIGHT_LOW },
  42. { "average", CBuilding::HEIGHT_AVERAGE },
  43. { "high", CBuilding::HEIGHT_HIGH },
  44. { "skyship", CBuilding::HEIGHT_SKYSHIP }
  45. };
  46. BuildingTypeUniqueID::BuildingTypeUniqueID(FactionID factionID, BuildingID buildingID ):
  47. BuildingTypeUniqueID(factionID.getNum() * 0x10000 + buildingID.getNum())
  48. {
  49. assert(factionID.getNum() >= 0);
  50. assert(factionID.getNum() < 0x10000);
  51. assert(buildingID.getNum() >= 0);
  52. assert(buildingID.getNum() < 0x10000);
  53. }
  54. BuildingID BuildingTypeUniqueID::getBuilding() const
  55. {
  56. return BuildingID(getNum() % 0x10000);
  57. }
  58. FactionID BuildingTypeUniqueID::getFaction() const
  59. {
  60. return FactionID(getNum() / 0x10000);
  61. }
  62. const BuildingTypeUniqueID CBuilding::getUniqueTypeID() const
  63. {
  64. return BuildingTypeUniqueID(town->faction->getId(), bid);
  65. }
  66. std::string CBuilding::getJsonKey() const
  67. {
  68. return modScope + ':' + identifier;
  69. }
  70. std::string CBuilding::getNameTranslated() const
  71. {
  72. return VLC->generaltexth->translate(getNameTextID());
  73. }
  74. std::string CBuilding::getDescriptionTranslated() const
  75. {
  76. return VLC->generaltexth->translate(getDescriptionTextID());
  77. }
  78. std::string CBuilding::getBaseTextID() const
  79. {
  80. return TextIdentifier("building", modScope, town->faction->identifier, identifier).get();
  81. }
  82. std::string CBuilding::getNameTextID() const
  83. {
  84. return TextIdentifier(getBaseTextID(), "name").get();
  85. }
  86. std::string CBuilding::getDescriptionTextID() const
  87. {
  88. return TextIdentifier(getBaseTextID(), "description").get();
  89. }
  90. BuildingID CBuilding::getBase() const
  91. {
  92. const CBuilding * build = this;
  93. while (build->upgrade != BuildingID::NONE)
  94. {
  95. build = build->town->buildings.at(build->upgrade);
  96. }
  97. return build->bid;
  98. }
  99. si32 CBuilding::getDistance(const BuildingID & buildID) const
  100. {
  101. const CBuilding * build = town->buildings.at(buildID);
  102. int distance = 0;
  103. while (build->upgrade != BuildingID::NONE && build != this)
  104. {
  105. build = build->town->buildings.at(build->upgrade);
  106. distance++;
  107. }
  108. if (build == this)
  109. return distance;
  110. return -1;
  111. }
  112. void CBuilding::addNewBonus(const std::shared_ptr<Bonus> & b, BonusList & bonusList) const
  113. {
  114. bonusList.push_back(b);
  115. }
  116. CFaction::~CFaction()
  117. {
  118. if (town)
  119. {
  120. delete town;
  121. town = nullptr;
  122. }
  123. }
  124. int32_t CFaction::getIndex() const
  125. {
  126. return index.getNum();
  127. }
  128. int32_t CFaction::getIconIndex() const
  129. {
  130. return index.getNum(); //???
  131. }
  132. std::string CFaction::getJsonKey() const
  133. {
  134. return modScope + ':' + identifier;
  135. }
  136. void CFaction::registerIcons(const IconRegistar & cb) const
  137. {
  138. if(town)
  139. {
  140. auto & info = town->clientInfo;
  141. cb(info.icons[0][0], 0, "ITPT", info.iconLarge[0][0]);
  142. cb(info.icons[0][1], 0, "ITPT", info.iconLarge[0][1]);
  143. cb(info.icons[1][0], 0, "ITPT", info.iconLarge[1][0]);
  144. cb(info.icons[1][1], 0, "ITPT", info.iconLarge[1][1]);
  145. cb(info.icons[0][0] + 2, 0, "ITPA", info.iconSmall[0][0]);
  146. cb(info.icons[0][1] + 2, 0, "ITPA", info.iconSmall[0][1]);
  147. cb(info.icons[1][0] + 2, 0, "ITPA", info.iconSmall[1][0]);
  148. cb(info.icons[1][1] + 2, 0, "ITPA", info.iconSmall[1][1]);
  149. cb(index.getNum(), 1, "CPRSMALL", info.towerIconSmall);
  150. cb(index.getNum(), 1, "TWCRPORT", info.towerIconLarge);
  151. }
  152. }
  153. std::string CFaction::getNameTranslated() const
  154. {
  155. return VLC->generaltexth->translate(getNameTextID());
  156. }
  157. std::string CFaction::getNameTextID() const
  158. {
  159. return TextIdentifier("faction", modScope, identifier, "name").get();
  160. }
  161. FactionID CFaction::getId() const
  162. {
  163. return FactionID(index);
  164. }
  165. FactionID CFaction::getFaction() const
  166. {
  167. return FactionID(index);
  168. }
  169. bool CFaction::hasTown() const
  170. {
  171. return town != nullptr;
  172. }
  173. EAlignment CFaction::getAlignment() const
  174. {
  175. return alignment;
  176. }
  177. BoatId CFaction::getBoatType() const
  178. {
  179. return boatType;
  180. }
  181. TerrainId CFaction::getNativeTerrain() const
  182. {
  183. return nativeTerrain;
  184. }
  185. void CFaction::updateFrom(const JsonNode & data)
  186. {
  187. }
  188. void CFaction::serializeJson(JsonSerializeFormat & handler)
  189. {
  190. }
  191. CTown::CTown()
  192. : faction(nullptr), mageLevel(0), primaryRes(0), moatAbility(SpellID::NONE), defaultTavernChance(0)
  193. {
  194. }
  195. CTown::~CTown()
  196. {
  197. for(auto & build : buildings)
  198. build.second.dellNull();
  199. for(auto & str : clientInfo.structures)
  200. str.dellNull();
  201. }
  202. std::string CTown::getRandomNameTranslated(size_t index) const
  203. {
  204. return VLC->generaltexth->translate(getRandomNameTextID(index));
  205. }
  206. std::string CTown::getRandomNameTextID(size_t index) const
  207. {
  208. return TextIdentifier("faction", faction->modScope, faction->identifier, "randomName", index).get();
  209. }
  210. size_t CTown::getRandomNamesCount() const
  211. {
  212. return namesCount;
  213. }
  214. std::string CTown::getBuildingScope() const
  215. {
  216. if(faction == nullptr)
  217. //no faction == random faction
  218. return "building";
  219. else
  220. return "building." + faction->getJsonKey();
  221. }
  222. std::set<si32> CTown::getAllBuildings() const
  223. {
  224. std::set<si32> res;
  225. for(const auto & b : buildings)
  226. {
  227. res.insert(b.first.num);
  228. }
  229. return res;
  230. }
  231. const CBuilding * CTown::getSpecialBuilding(BuildingSubID::EBuildingSubID subID) const
  232. {
  233. for(const auto & kvp : buildings)
  234. {
  235. if(kvp.second->subId == subID)
  236. return buildings.at(kvp.first);
  237. }
  238. return nullptr;
  239. }
  240. BuildingID CTown::getBuildingType(BuildingSubID::EBuildingSubID subID) const
  241. {
  242. const auto * building = getSpecialBuilding(subID);
  243. return building == nullptr ? BuildingID::NONE : building->bid.num;
  244. }
  245. std::string CTown::getGreeting(BuildingSubID::EBuildingSubID subID) const
  246. {
  247. return CTownHandler::getMappedValue<const std::string, BuildingSubID::EBuildingSubID>(subID, std::string(), specialMessages, false);
  248. }
  249. void CTown::setGreeting(BuildingSubID::EBuildingSubID subID, const std::string & message) const
  250. {
  251. specialMessages.insert(std::pair<BuildingSubID::EBuildingSubID, const std::string>(subID, message));
  252. }
  253. CTownHandler::CTownHandler():
  254. randomTown(new CTown()),
  255. randomFaction(new CFaction())
  256. {
  257. randomFaction->town = randomTown;
  258. randomTown->faction = randomFaction;
  259. randomFaction->identifier = "random";
  260. randomFaction->modScope = "core";
  261. }
  262. CTownHandler::~CTownHandler()
  263. {
  264. delete randomFaction; // will also delete randomTown
  265. }
  266. JsonNode readBuilding(CLegacyConfigParser & parser)
  267. {
  268. JsonNode ret;
  269. JsonNode & cost = ret["cost"];
  270. //note: this code will try to parse mithril as well but wil always return 0 for it
  271. for(const std::string & resID : GameConstants::RESOURCE_NAMES)
  272. cost[resID].Float() = parser.readNumber();
  273. cost.Struct().erase("mithril"); // erase mithril to avoid confusing validator
  274. parser.endLine();
  275. return ret;
  276. }
  277. TPropagatorPtr & CTownHandler::emptyPropagator()
  278. {
  279. static TPropagatorPtr emptyProp(nullptr);
  280. return emptyProp;
  281. }
  282. std::vector<JsonNode> CTownHandler::loadLegacyData()
  283. {
  284. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_FACTION);
  285. std::vector<JsonNode> dest(dataSize);
  286. objects.resize(dataSize);
  287. auto getBuild = [&](size_t town, size_t building) -> JsonNode &
  288. {
  289. return dest[town]["town"]["buildings"][EBuildingType::names[building]];
  290. };
  291. CLegacyConfigParser parser(TextPath::builtin("DATA/BUILDING.TXT"));
  292. parser.endLine(); // header
  293. parser.endLine();
  294. //Unique buildings
  295. for (size_t town=0; town<dataSize; town++)
  296. {
  297. parser.endLine(); //header
  298. parser.endLine();
  299. int buildID = 17;
  300. do
  301. {
  302. getBuild(town, buildID) = readBuilding(parser);
  303. buildID++;
  304. }
  305. while (!parser.isNextEntryEmpty());
  306. }
  307. // Common buildings
  308. parser.endLine(); // header
  309. parser.endLine();
  310. parser.endLine();
  311. int buildID = 0;
  312. do
  313. {
  314. JsonNode building = readBuilding(parser);
  315. for (size_t town=0; town<dataSize; town++)
  316. getBuild(town, buildID) = building;
  317. buildID++;
  318. }
  319. while (!parser.isNextEntryEmpty());
  320. parser.endLine(); //header
  321. parser.endLine();
  322. //Dwellings
  323. for (size_t town=0; town<dataSize; town++)
  324. {
  325. parser.endLine(); //header
  326. parser.endLine();
  327. for (size_t i=0; i<14; i++)
  328. {
  329. getBuild(town, 30+i) = readBuilding(parser);
  330. }
  331. }
  332. {
  333. CLegacyConfigParser parser(TextPath::builtin("DATA/BLDGNEUT.TXT"));
  334. for(int building=0; building<15; building++)
  335. {
  336. std::string name = parser.readString();
  337. std::string descr = parser.readString();
  338. parser.endLine();
  339. for(int j=0; j<dataSize; j++)
  340. {
  341. getBuild(j, building)["name"].String() = name;
  342. getBuild(j, building)["description"].String() = descr;
  343. }
  344. }
  345. parser.endLine(); // silo
  346. parser.endLine(); // blacksmith //unused entries
  347. parser.endLine(); // moat
  348. //shipyard with the ship
  349. std::string name = parser.readString();
  350. std::string descr = parser.readString();
  351. parser.endLine();
  352. for(int town=0; town<dataSize; town++)
  353. {
  354. getBuild(town, 20)["name"].String() = name;
  355. getBuild(town, 20)["description"].String() = descr;
  356. }
  357. //blacksmith
  358. for(int town=0; town<dataSize; town++)
  359. {
  360. getBuild(town, 16)["name"].String() = parser.readString();
  361. getBuild(town, 16)["description"].String() = parser.readString();
  362. parser.endLine();
  363. }
  364. }
  365. {
  366. CLegacyConfigParser parser(TextPath::builtin("DATA/BLDGSPEC.TXT"));
  367. for(int town=0; town<dataSize; town++)
  368. {
  369. for(int build=0; build<9; build++)
  370. {
  371. getBuild(town, 17 + build)["name"].String() = parser.readString();
  372. getBuild(town, 17 + build)["description"].String() = parser.readString();
  373. parser.endLine();
  374. }
  375. getBuild(town, 26)["name"].String() = parser.readString(); // Grail
  376. getBuild(town, 26)["description"].String() = parser.readString();
  377. parser.endLine();
  378. getBuild(town, 15)["name"].String() = parser.readString(); // Resource silo
  379. getBuild(town, 15)["description"].String() = parser.readString();
  380. parser.endLine();
  381. }
  382. }
  383. {
  384. CLegacyConfigParser parser(TextPath::builtin("DATA/DWELLING.TXT"));
  385. for(int town=0; town<dataSize; town++)
  386. {
  387. for(int build=0; build<14; build++)
  388. {
  389. getBuild(town, 30 + build)["name"].String() = parser.readString();
  390. getBuild(town, 30 + build)["description"].String() = parser.readString();
  391. parser.endLine();
  392. }
  393. }
  394. }
  395. {
  396. CLegacyConfigParser typeParser(TextPath::builtin("DATA/TOWNTYPE.TXT"));
  397. CLegacyConfigParser nameParser(TextPath::builtin("DATA/TOWNNAME.TXT"));
  398. size_t townID=0;
  399. do
  400. {
  401. dest[townID]["name"].String() = typeParser.readString();
  402. for (int i=0; i<NAMES_PER_TOWN; i++)
  403. {
  404. JsonNode name;
  405. name.String() = nameParser.readString();
  406. dest[townID]["town"]["names"].Vector().push_back(name);
  407. nameParser.endLine();
  408. }
  409. townID++;
  410. }
  411. while (typeParser.endLine());
  412. }
  413. return dest;
  414. }
  415. void CTownHandler::loadBuildingRequirements(CBuilding * building, const JsonNode & source, std::vector<BuildingRequirementsHelper> & bidsToLoad) const
  416. {
  417. if (source.isNull())
  418. return;
  419. BuildingRequirementsHelper hlp;
  420. hlp.building = building;
  421. hlp.town = building->town;
  422. hlp.json = source;
  423. bidsToLoad.push_back(hlp);
  424. }
  425. template<typename R, typename K>
  426. R CTownHandler::getMappedValue(const K key, const R defval, const std::map<K, R> & map, bool required)
  427. {
  428. auto it = map.find(key);
  429. if(it != map.end())
  430. return it->second;
  431. if(required)
  432. logMod->warn("Warning: Property: '%s' is unknown. Correct the typo or update VCMI.", key);
  433. return defval;
  434. }
  435. template<typename R>
  436. R CTownHandler::getMappedValue(const JsonNode & node, const R defval, const std::map<std::string, R> & map, bool required)
  437. {
  438. if(!node.isNull() && node.getType() == JsonNode::JsonType::DATA_STRING)
  439. return getMappedValue<R, std::string>(node.String(), defval, map, required);
  440. return defval;
  441. }
  442. void CTownHandler::addBonusesForVanilaBuilding(CBuilding * building) const
  443. {
  444. std::shared_ptr<Bonus> b;
  445. static TPropagatorPtr playerPropagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::ENodeTypes::PLAYER);
  446. if(building->bid == BuildingID::TAVERN)
  447. {
  448. b = createBonus(building, BonusType::MORALE, +1);
  449. }
  450. switch(building->subId)
  451. {
  452. case BuildingSubID::BROTHERHOOD_OF_SWORD:
  453. b = createBonus(building, BonusType::MORALE, +2);
  454. building->overrideBids.insert(BuildingID::TAVERN);
  455. break;
  456. case BuildingSubID::FOUNTAIN_OF_FORTUNE:
  457. b = createBonus(building, BonusType::LUCK, +2);
  458. break;
  459. case BuildingSubID::SPELL_POWER_GARRISON_BONUS:
  460. b = createBonus(building, BonusType::PRIMARY_SKILL, +2, BonusSubtypeID(PrimarySkill::SPELL_POWER));
  461. break;
  462. case BuildingSubID::ATTACK_GARRISON_BONUS:
  463. b = createBonus(building, BonusType::PRIMARY_SKILL, +2, BonusSubtypeID(PrimarySkill::ATTACK));
  464. break;
  465. case BuildingSubID::DEFENSE_GARRISON_BONUS:
  466. b = createBonus(building, BonusType::PRIMARY_SKILL, +2, BonusSubtypeID(PrimarySkill::DEFENSE));
  467. break;
  468. case BuildingSubID::LIGHTHOUSE:
  469. b = createBonus(building, BonusType::MOVEMENT, +500, BonusCustomSubtype::heroMovementSea, playerPropagator);
  470. break;
  471. }
  472. if(b)
  473. building->addNewBonus(b, building->buildingBonuses);
  474. }
  475. std::shared_ptr<Bonus> CTownHandler::createBonus(CBuilding * build, BonusType type, int val) const
  476. {
  477. return createBonus(build, type, val, BonusSubtypeID(), emptyPropagator());
  478. }
  479. std::shared_ptr<Bonus> CTownHandler::createBonus(CBuilding * build, BonusType type, int val, BonusSubtypeID subtype) const
  480. {
  481. return createBonus(build, type, val, subtype, emptyPropagator());
  482. }
  483. std::shared_ptr<Bonus> CTownHandler::createBonus(CBuilding * build, BonusType type, int val, BonusSubtypeID subtype, TPropagatorPtr & prop) const
  484. {
  485. std::ostringstream descr;
  486. descr << build->getNameTranslated();
  487. return createBonusImpl(build->bid, build->town->faction->getId(), type, val, prop, descr.str(), subtype);
  488. }
  489. std::shared_ptr<Bonus> CTownHandler::createBonusImpl(const BuildingID & building,
  490. const FactionID & faction,
  491. BonusType type,
  492. int val,
  493. TPropagatorPtr & prop,
  494. const std::string & description,
  495. BonusSubtypeID subtype) const
  496. {
  497. auto b = std::make_shared<Bonus>(BonusDuration::PERMANENT, type, BonusSource::TOWN_STRUCTURE, val, BuildingTypeUniqueID(faction, building), subtype, description);
  498. if(prop)
  499. b->addPropagator(prop);
  500. return b;
  501. }
  502. void CTownHandler::loadSpecialBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building)
  503. {
  504. for(const auto & b : source.Vector())
  505. {
  506. auto bonus = JsonUtils::parseBuildingBonus(b, building->town->faction->getId(), building->bid, building->getNameTranslated());
  507. if(bonus == nullptr)
  508. continue;
  509. bonus->sid = BonusSourceID(building->getUniqueTypeID());
  510. //JsonUtils::parseBuildingBonus produces UNKNOWN type propagator instead of empty.
  511. if(bonus->propagator != nullptr
  512. && bonus->propagator->getPropagatorType() == CBonusSystemNode::ENodeTypes::UNKNOWN)
  513. bonus->addPropagator(emptyPropagator());
  514. building->addNewBonus(bonus, bonusList);
  515. }
  516. }
  517. void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, const JsonNode & source)
  518. {
  519. assert(stringID.find(':') == std::string::npos);
  520. assert(!source.meta.empty());
  521. auto * ret = new CBuilding();
  522. ret->bid = getMappedValue<BuildingID, std::string>(stringID, BuildingID::NONE, MappedKeys::BUILDING_NAMES_TO_TYPES, false);
  523. ret->subId = BuildingSubID::NONE;
  524. if(ret->bid == BuildingID::NONE && !source["id"].isNull())
  525. {
  526. // FIXME: A lot of false-positives with no clear way to handle them in mods
  527. //logMod->warn("Building %s: id field is deprecated", stringID);
  528. ret->bid = source["id"].isNull() ? BuildingID(BuildingID::NONE) : BuildingID(source["id"].Float());
  529. }
  530. if (ret->bid == BuildingID::NONE)
  531. logMod->error("Building '%s' isn't recognized and won't work properly. Correct the typo or update VCMI.", stringID);
  532. ret->mode = ret->bid == BuildingID::GRAIL
  533. ? CBuilding::BUILD_GRAIL
  534. : getMappedValue<CBuilding::EBuildMode>(source["mode"], CBuilding::BUILD_NORMAL, CBuilding::MODES);
  535. ret->height = getMappedValue<CBuilding::ETowerHeight>(source["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES);
  536. ret->identifier = stringID;
  537. ret->modScope = source.meta;
  538. ret->town = town;
  539. VLC->generaltexth->registerString(source.meta, ret->getNameTextID(), source["name"].String());
  540. VLC->generaltexth->registerString(source.meta, ret->getDescriptionTextID(), source["description"].String());
  541. ret->resources = TResources(source["cost"]);
  542. ret->produce = TResources(source["produce"]);
  543. if(ret->bid == BuildingID::TAVERN)
  544. addBonusesForVanilaBuilding(ret);
  545. else if(ret->bid.IsSpecialOrGrail())
  546. {
  547. loadSpecialBuildingBonuses(source["bonuses"], ret->buildingBonuses, ret);
  548. if(ret->buildingBonuses.empty())
  549. {
  550. ret->subId = getMappedValue<BuildingSubID::EBuildingSubID>(source["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS);
  551. addBonusesForVanilaBuilding(ret);
  552. }
  553. loadSpecialBuildingBonuses(source["onVisitBonuses"], ret->onVisitBonuses, ret);
  554. if(!ret->onVisitBonuses.empty())
  555. {
  556. if(ret->subId == BuildingSubID::NONE)
  557. ret->subId = BuildingSubID::CUSTOM_VISITING_BONUS;
  558. for(auto & bonus : ret->onVisitBonuses)
  559. bonus->sid = BonusSourceID(ret->getUniqueTypeID());
  560. }
  561. if(source["type"].String() == "configurable" && ret->subId == BuildingSubID::NONE)
  562. {
  563. ret->subId = BuildingSubID::CUSTOM_VISITING_REWARD;
  564. ret->rewardableObjectInfo.init(source, ret->getBaseTextID());
  565. }
  566. }
  567. //MODS COMPATIBILITY FOR 0.96
  568. if(!ret->produce.nonZero())
  569. {
  570. switch (ret->bid.toEnum()) {
  571. break; case BuildingID::VILLAGE_HALL: ret->produce[EGameResID::GOLD] = 500;
  572. break; case BuildingID::TOWN_HALL : ret->produce[EGameResID::GOLD] = 1000;
  573. break; case BuildingID::CITY_HALL : ret->produce[EGameResID::GOLD] = 2000;
  574. break; case BuildingID::CAPITOL : ret->produce[EGameResID::GOLD] = 4000;
  575. break; case BuildingID::GRAIL : ret->produce[EGameResID::GOLD] = 5000;
  576. break; case BuildingID::RESOURCE_SILO :
  577. {
  578. switch (ret->town->primaryRes.toEnum())
  579. {
  580. case EGameResID::GOLD:
  581. ret->produce[ret->town->primaryRes] = 500;
  582. break;
  583. case EGameResID::WOOD_AND_ORE:
  584. ret->produce[EGameResID::WOOD] = 1;
  585. ret->produce[EGameResID::ORE] = 1;
  586. break;
  587. default:
  588. ret->produce[ret->town->primaryRes] = 1;
  589. break;
  590. }
  591. }
  592. }
  593. }
  594. loadBuildingRequirements(ret, source["requires"], requirementsToLoad);
  595. if(ret->bid.IsSpecialOrGrail())
  596. loadBuildingRequirements(ret, source["overrides"], overriddenBidsToLoad);
  597. if (!source["upgrades"].isNull())
  598. {
  599. // building id and upgrades can't be the same
  600. if(stringID == source["upgrades"].String())
  601. {
  602. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") %
  603. stringID % ret->town->faction->getNameTranslated()));
  604. }
  605. VLC->identifiers()->requestIdentifier(ret->town->getBuildingScope(), source["upgrades"], [=](si32 identifier)
  606. {
  607. ret->upgrade = BuildingID(identifier);
  608. });
  609. }
  610. else
  611. ret->upgrade = BuildingID::NONE;
  612. ret->town->buildings[ret->bid] = ret;
  613. registerObject(source.meta, ret->town->getBuildingScope(), ret->identifier, ret->bid.getNum());
  614. }
  615. void CTownHandler::loadBuildings(CTown * town, const JsonNode & source)
  616. {
  617. if(source.isStruct())
  618. {
  619. for(const auto & node : source.Struct())
  620. {
  621. if (!node.second.isNull())
  622. loadBuilding(town, node.first, node.second);
  623. }
  624. }
  625. }
  626. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source) const
  627. {
  628. auto * ret = new CStructure();
  629. ret->building = nullptr;
  630. ret->buildable = nullptr;
  631. VLC->identifiers()->tryRequestIdentifier( source.meta, "building." + town.faction->getJsonKey(), stringID, [=, &town](si32 identifier) mutable
  632. {
  633. ret->building = town.buildings[BuildingID(identifier)];
  634. });
  635. if (source["builds"].isNull())
  636. {
  637. VLC->identifiers()->tryRequestIdentifier( source.meta, "building." + town.faction->getJsonKey(), stringID, [=, &town](si32 identifier) mutable
  638. {
  639. ret->building = town.buildings[BuildingID(identifier)];
  640. });
  641. }
  642. else
  643. {
  644. VLC->identifiers()->requestIdentifier("building." + town.faction->getJsonKey(), source["builds"], [=, &town](si32 identifier) mutable
  645. {
  646. ret->buildable = town.buildings[BuildingID(identifier)];
  647. });
  648. }
  649. ret->identifier = stringID;
  650. ret->pos.x = static_cast<si32>(source["x"].Float());
  651. ret->pos.y = static_cast<si32>(source["y"].Float());
  652. ret->pos.z = static_cast<si32>(source["z"].Float());
  653. ret->hiddenUpgrade = source["hidden"].Bool();
  654. ret->defName = AnimationPath::fromJson(source["animation"]);
  655. ret->borderName = ImagePath::fromJson(source["border"]);
  656. ret->areaName = ImagePath::fromJson(source["area"]);
  657. town.clientInfo.structures.emplace_back(ret);
  658. }
  659. void CTownHandler::loadStructures(CTown &town, const JsonNode & source) const
  660. {
  661. for(const auto & node : source.Struct())
  662. {
  663. if (!node.second.isNull())
  664. loadStructure(town, node.first, node.second);
  665. }
  666. }
  667. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source) const
  668. {
  669. auto & dstSlots = town.clientInfo.hallSlots;
  670. const auto & srcSlots = source.Vector();
  671. dstSlots.resize(srcSlots.size());
  672. for(size_t i=0; i<dstSlots.size(); i++)
  673. {
  674. auto & dstRow = dstSlots[i];
  675. const auto & srcRow = srcSlots[i].Vector();
  676. dstRow.resize(srcRow.size());
  677. for(size_t j=0; j < dstRow.size(); j++)
  678. {
  679. auto & dstBox = dstRow[j];
  680. const auto & srcBox = srcRow[j].Vector();
  681. dstBox.resize(srcBox.size());
  682. for(size_t k=0; k<dstBox.size(); k++)
  683. {
  684. auto & dst = dstBox[k];
  685. const auto & src = srcBox[k];
  686. VLC->identifiers()->requestIdentifier("building." + town.faction->getJsonKey(), src, [&](si32 identifier)
  687. {
  688. dst = BuildingID(identifier);
  689. });
  690. }
  691. }
  692. }
  693. }
  694. Point JsonToPoint(const JsonNode & node)
  695. {
  696. if(!node.isStruct())
  697. return Point::makeInvalid();
  698. Point ret;
  699. ret.x = static_cast<si32>(node["x"].Float());
  700. ret.y = static_cast<si32>(node["y"].Float());
  701. return ret;
  702. }
  703. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source) const
  704. {
  705. town.clientInfo.siegePrefix = source["imagePrefix"].String();
  706. town.clientInfo.towerIconSmall = source["towerIconSmall"].String();
  707. town.clientInfo.towerIconLarge = source["towerIconLarge"].String();
  708. VLC->identifiers()->requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  709. {
  710. auto crId = CreatureID(creature);
  711. if((*VLC->creh)[crId]->animation.missleFrameAngles.empty())
  712. logMod->error("Mod '%s' error: Creature '%s' on the Archer's tower is not a shooter. Mod should be fixed. Siege will not work properly!"
  713. , town.faction->getNameTranslated()
  714. , (*VLC->creh)[crId]->getNameSingularTranslated());
  715. town.clientInfo.siegeShooter = crId;
  716. });
  717. auto & pos = town.clientInfo.siegePositions;
  718. pos.resize(21);
  719. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  720. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  721. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  722. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  723. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  724. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  725. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  726. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  727. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  728. pos[9] = JsonToPoint(source["gate"]["gate"]);
  729. pos[10] = JsonToPoint(source["gate"]["arch"]);
  730. pos[7] = JsonToPoint(source["walls"]["upper"]);
  731. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  732. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  733. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  734. pos[13] = JsonToPoint(source["moat"]["moat"]);
  735. pos[14] = JsonToPoint(source["moat"]["bank"]);
  736. pos[11] = JsonToPoint(source["static"]["bottom"]);
  737. pos[12] = JsonToPoint(source["static"]["top"]);
  738. pos[1] = JsonToPoint(source["static"]["background"]);
  739. }
  740. static void readIcon(JsonNode source, std::string & small, std::string & large)
  741. {
  742. if (source.getType() == JsonNode::JsonType::DATA_STRUCT) // don't crash on old format
  743. {
  744. small = source["small"].String();
  745. large = source["large"].String();
  746. }
  747. }
  748. void CTownHandler::loadClientData(CTown &town, const JsonNode & source) const
  749. {
  750. CTown::ClientInfo & info = town.clientInfo;
  751. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  752. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  753. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  754. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  755. info.hallBackground = ImagePath::fromJson(source["hallBackground"]);
  756. info.musicTheme = AudioPath::fromJson(source["musicTheme"]);
  757. info.townBackground = ImagePath::fromJson(source["townBackground"]);
  758. info.guildWindow = ImagePath::fromJson(source["guildWindow"]);
  759. info.buildingsIcons = AnimationPath::fromJson(source["buildingsIcons"]);
  760. info.guildBackground = ImagePath::fromJson(source["guildBackground"]);
  761. info.tavernVideo = VideoPath::fromJson(source["tavernVideo"]);
  762. loadTownHall(town, source["hallSlots"]);
  763. loadStructures(town, source["structures"]);
  764. loadSiegeScreen(town, source["siege"]);
  765. }
  766. void CTownHandler::loadTown(CTown * town, const JsonNode & source)
  767. {
  768. const auto * resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  769. if(resIter == std::end(GameConstants::RESOURCE_NAMES))
  770. town->primaryRes = GameResID(EGameResID::WOOD_AND_ORE); //Wood + Ore
  771. else
  772. town->primaryRes = GameResID(resIter - std::begin(GameConstants::RESOURCE_NAMES));
  773. warMachinesToLoad[town] = source["warMachine"];
  774. town->mageLevel = static_cast<ui32>(source["mageGuild"].Float());
  775. town->namesCount = 0;
  776. for(const auto & name : source["names"].Vector())
  777. {
  778. VLC->generaltexth->registerString(town->faction->modScope, town->getRandomNameTextID(town->namesCount), name.String());
  779. town->namesCount += 1;
  780. }
  781. if (!source["moatAbility"].isNull()) // VCMI 1.2 compatibility code
  782. {
  783. VLC->identifiers()->requestIdentifier( "spell", source["moatAbility"], [=](si32 ability)
  784. {
  785. town->moatAbility = SpellID(ability);
  786. });
  787. }
  788. else
  789. {
  790. VLC->identifiers()->requestIdentifier( source.meta, "spell", "castleMoat", [=](si32 ability)
  791. {
  792. town->moatAbility = SpellID(ability);
  793. });
  794. }
  795. // Horde building creature level
  796. for(const JsonNode &node : source["horde"].Vector())
  797. town->hordeLvl[static_cast<int>(town->hordeLvl.size())] = static_cast<int>(node.Float());
  798. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  799. // but anything below 2 must be handled here
  800. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  801. town->hordeLvl[static_cast<int>(i)] = -1;
  802. const JsonVector & creatures = source["creatures"].Vector();
  803. town->creatures.resize(creatures.size());
  804. for (size_t i=0; i< creatures.size(); i++)
  805. {
  806. const JsonVector & level = creatures[i].Vector();
  807. town->creatures[i].resize(level.size());
  808. for (size_t j=0; j<level.size(); j++)
  809. {
  810. VLC->identifiers()->requestIdentifier("creature", level[j], [=](si32 creature)
  811. {
  812. town->creatures[i][j] = CreatureID(creature);
  813. });
  814. }
  815. }
  816. town->defaultTavernChance = static_cast<ui32>(source["defaultTavern"].Float());
  817. /// set chance of specific hero class to appear in this town
  818. for(const auto & node : source["tavern"].Struct())
  819. {
  820. int chance = static_cast<int>(node.second.Float());
  821. VLC->identifiers()->requestIdentifier(node.second.meta, "heroClass",node.first, [=](si32 classID)
  822. {
  823. VLC->heroh->classes[HeroClassID(classID)]->selectionProbability[town->faction->getId()] = chance;
  824. });
  825. }
  826. for(const auto & node : source["guildSpells"].Struct())
  827. {
  828. int chance = static_cast<int>(node.second.Float());
  829. VLC->identifiers()->requestIdentifier(node.second.meta, "spell", node.first, [=](si32 spellID)
  830. {
  831. VLC->spellh->objects.at(spellID)->probabilities[town->faction->getId()] = chance;
  832. });
  833. }
  834. for(const JsonNode & d : source["adventureMap"]["dwellings"].Vector())
  835. {
  836. town->dwellings.push_back(d["graphics"].String());
  837. town->dwellingNames.push_back(d["name"].String());
  838. }
  839. loadBuildings(town, source["buildings"]);
  840. loadClientData(*town, source);
  841. }
  842. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source) const
  843. {
  844. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  845. std::string prefix = source["prefix"].String();
  846. for(const JsonNode &piece : source["pieces"].Vector())
  847. {
  848. size_t index = faction.puzzleMap.size();
  849. SPuzzleInfo spi;
  850. spi.x = static_cast<si16>(piece["x"].Float());
  851. spi.y = static_cast<si16>(piece["y"].Float());
  852. spi.whenUncovered = static_cast<ui16>(piece["index"].Float());
  853. spi.number = static_cast<ui16>(index);
  854. // filename calculation
  855. std::ostringstream suffix;
  856. suffix << std::setfill('0') << std::setw(2) << index;
  857. spi.filename = ImagePath::builtinTODO(prefix + suffix.str());
  858. faction.puzzleMap.push_back(spi);
  859. }
  860. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  861. }
  862. CFaction * CTownHandler::loadFromJson(const std::string & scope, const JsonNode & source, const std::string & identifier, size_t index)
  863. {
  864. assert(identifier.find(':') == std::string::npos);
  865. auto * faction = new CFaction();
  866. faction->index = static_cast<FactionID>(index);
  867. faction->modScope = scope;
  868. faction->identifier = identifier;
  869. VLC->generaltexth->registerString(scope, faction->getNameTextID(), source["name"].String());
  870. faction->creatureBg120 = ImagePath::fromJson(source["creatureBackground"]["120px"]);
  871. faction->creatureBg130 = ImagePath::fromJson(source["creatureBackground"]["130px"]);
  872. faction->boatType = BoatId::CASTLE; //Do not crash
  873. if (!source["boat"].isNull())
  874. {
  875. VLC->identifiers()->requestIdentifier("core:boat", source["boat"], [=](int32_t boatTypeID)
  876. {
  877. faction->boatType = BoatId(boatTypeID);
  878. });
  879. }
  880. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, source["alignment"].String());
  881. if (alignment == -1)
  882. faction->alignment = EAlignment::NEUTRAL;
  883. else
  884. faction->alignment = static_cast<EAlignment>(alignment);
  885. auto preferUndergound = source["preferUndergroundPlacement"];
  886. faction->preferUndergroundPlacement = preferUndergound.isNull() ? false : preferUndergound.Bool();
  887. // NOTE: semi-workaround - normally, towns are supposed to have native terrains.
  888. // Towns without one are exceptions. So, vcmi requires nativeTerrain to be defined
  889. // But allows it to be defined with explicit value of "none" if town should not have native terrain
  890. // This is better than allowing such terrain-less towns silently, leading to issues with RMG
  891. faction->nativeTerrain = ETerrainId::NONE;
  892. if ( !source["nativeTerrain"].isNull() && source["nativeTerrain"].String() != "none")
  893. {
  894. VLC->identifiers()->requestIdentifier("terrain", source["nativeTerrain"], [=](int32_t index){
  895. faction->nativeTerrain = TerrainId(index);
  896. auto const & terrain = VLC->terrainTypeHandler->getById(faction->nativeTerrain);
  897. if (!terrain->isSurface() && !terrain->isUnderground())
  898. logMod->warn("Faction %s has terrain %s as native, but terrain is not suitable for either surface or subterranean layers!", faction->getJsonKey(), terrain->getJsonKey());
  899. });
  900. }
  901. if (!source["town"].isNull())
  902. {
  903. faction->town = new CTown();
  904. faction->town->faction = faction;
  905. loadTown(faction->town, source["town"]);
  906. }
  907. else
  908. faction->town = nullptr;
  909. if (!source["puzzleMap"].isNull())
  910. loadPuzzle(*faction, source["puzzleMap"]);
  911. return faction;
  912. }
  913. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  914. {
  915. auto * object = loadFromJson(scope, data, name, objects.size());
  916. objects.emplace_back(object);
  917. if (object->town)
  918. {
  919. auto & info = object->town->clientInfo;
  920. info.icons[0][0] = 8 + object->index.getNum() * 4 + 0;
  921. info.icons[0][1] = 8 + object->index.getNum() * 4 + 1;
  922. info.icons[1][0] = 8 + object->index.getNum() * 4 + 2;
  923. info.icons[1][1] = 8 + object->index.getNum() * 4 + 3;
  924. VLC->identifiers()->requestIdentifier(scope, "object", "town", [=](si32 index)
  925. {
  926. // register town once objects are loaded
  927. JsonNode config = data["town"]["mapObject"];
  928. config["faction"].String() = name;
  929. config["faction"].meta = scope;
  930. if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96
  931. config.meta = scope;
  932. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  933. // MODS COMPATIBILITY FOR 0.96
  934. const auto & advMap = data["town"]["adventureMap"];
  935. if (!advMap.isNull())
  936. {
  937. logMod->warn("Outdated town mod. Will try to generate valid templates out of fort");
  938. JsonNode config;
  939. config["animation"] = advMap["castle"];
  940. VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  941. }
  942. });
  943. }
  944. registerObject(scope, "faction", name, object->index.getNum());
  945. }
  946. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  947. {
  948. auto * object = loadFromJson(scope, data, name, index);
  949. if (objects.size() > index)
  950. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  951. else
  952. objects.resize(index + 1);
  953. objects[index] = object;
  954. if (object->town)
  955. {
  956. auto & info = object->town->clientInfo;
  957. info.icons[0][0] = (GameConstants::F_NUMBER + object->index.getNum()) * 2 + 0;
  958. info.icons[0][1] = (GameConstants::F_NUMBER + object->index.getNum()) * 2 + 1;
  959. info.icons[1][0] = object->index.getNum() * 2 + 0;
  960. info.icons[1][1] = object->index.getNum() * 2 + 1;
  961. VLC->identifiers()->requestIdentifier(scope, "object", "town", [=](si32 index)
  962. {
  963. // register town once objects are loaded
  964. JsonNode config = data["town"]["mapObject"];
  965. config["faction"].String() = name;
  966. config["faction"].meta = scope;
  967. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  968. });
  969. }
  970. registerObject(scope, "faction", name, object->index.getNum());
  971. }
  972. void CTownHandler::loadRandomFaction()
  973. {
  974. JsonNode randomFactionJson(JsonPath::builtin("config/factions/random.json"));
  975. randomFactionJson.setMeta(ModScope::scopeBuiltin(), true);
  976. loadBuildings(randomTown, randomFactionJson["random"]["town"]["buildings"]);
  977. }
  978. void CTownHandler::loadCustom()
  979. {
  980. loadRandomFaction();
  981. }
  982. void CTownHandler::afterLoadFinalization()
  983. {
  984. initializeRequirements();
  985. initializeOverridden();
  986. initializeWarMachines();
  987. }
  988. void CTownHandler::initializeRequirements()
  989. {
  990. // must be done separately after all ID's are known
  991. for (auto & requirement : requirementsToLoad)
  992. {
  993. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  994. {
  995. if (node.Vector().size() > 1)
  996. {
  997. logMod->error("Unexpected length of town buildings requirements: %d", node.Vector().size());
  998. logMod->error("Entry contains: ");
  999. logMod->error(node.toJson());
  1000. }
  1001. auto index = VLC->identifiers()->getIdentifier(requirement.town->getBuildingScope(), node[0]);
  1002. if (!index.has_value())
  1003. {
  1004. logMod->error("Unknown building in town buildings: %s", node[0].String());
  1005. return BuildingID::NONE;
  1006. }
  1007. return BuildingID(index.value());
  1008. });
  1009. }
  1010. requirementsToLoad.clear();
  1011. }
  1012. void CTownHandler::initializeOverridden()
  1013. {
  1014. for(auto & bidHelper : overriddenBidsToLoad)
  1015. {
  1016. auto jsonNode = bidHelper.json;
  1017. auto scope = bidHelper.town->getBuildingScope();
  1018. for(const auto & b : jsonNode.Vector())
  1019. {
  1020. auto bid = BuildingID(VLC->identifiers()->getIdentifier(scope, b).value());
  1021. bidHelper.building->overrideBids.insert(bid);
  1022. }
  1023. }
  1024. overriddenBidsToLoad.clear();
  1025. }
  1026. void CTownHandler::initializeWarMachines()
  1027. {
  1028. // must be done separately after all objects are loaded
  1029. for(auto & p : warMachinesToLoad)
  1030. {
  1031. CTown * t = p.first;
  1032. JsonNode creatureKey = p.second;
  1033. auto ret = VLC->identifiers()->getIdentifier("creature", creatureKey, false);
  1034. if(ret)
  1035. {
  1036. const CCreature * creature = CreatureID(*ret).toCreature();
  1037. t->warMachine = creature->warMachine;
  1038. }
  1039. }
  1040. warMachinesToLoad.clear();
  1041. }
  1042. std::set<FactionID> CTownHandler::getDefaultAllowed() const
  1043. {
  1044. std::set<FactionID> allowedFactions;
  1045. for(auto town : objects)
  1046. if (town->town != nullptr)
  1047. allowedFactions.insert(town->getId());
  1048. return allowedFactions;
  1049. }
  1050. std::set<FactionID> CTownHandler::getAllowedFactions(bool withTown) const
  1051. {
  1052. if (withTown)
  1053. return getDefaultAllowed();
  1054. std::set<FactionID> result;
  1055. for(auto town : objects)
  1056. result.insert(town->getId());
  1057. return result;
  1058. }
  1059. const std::vector<std::string> & CTownHandler::getTypeNames() const
  1060. {
  1061. static const std::vector<std::string> typeNames = { "faction", "town" };
  1062. return typeNames;
  1063. }
  1064. VCMI_LIB_NAMESPACE_END