CTownHandler.cpp 38 KB

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