CTownHandler.cpp 37 KB

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