CTownHandler.cpp 37 KB

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