CTownHandler.cpp 37 KB

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