CTownHandler.cpp 37 KB

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