CTownHandler.cpp 36 KB

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