CTownHandler.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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->subId == BuildingSubID::NONE)
  412. {
  413. if(building->bid == BuildingID::TAVERN)
  414. {
  415. b = createBonus(building, Bonus::MORALE, +1);
  416. }
  417. }
  418. else
  419. {
  420. switch(building->subId)
  421. {
  422. case BuildingSubID::BROTHERHOOD_OF_SWORD:
  423. b = createBonus(building, Bonus::MORALE, +2);
  424. building->overrideBids.insert(BuildingID::TAVERN);
  425. break;
  426. case BuildingSubID::FOUNTAIN_OF_FORTUNE:
  427. b = createBonus(building, Bonus::LUCK, +2);
  428. break;
  429. case BuildingSubID::SPELL_POWER_GARRISON_BONUS:
  430. b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER);
  431. break;
  432. case BuildingSubID::ATTACK_GARRISON_BONUS:
  433. b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK);
  434. break;
  435. case BuildingSubID::DEFENSE_GARRISON_BONUS:
  436. b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE);
  437. break;
  438. case BuildingSubID::LIGHTHOUSE:
  439. b = createBonus(building, Bonus::MOVEMENT, +500, playerPropagator, 0);
  440. break;
  441. }
  442. }
  443. if(b)
  444. building->addNewBonus(b, building->buildingBonuses);
  445. }
  446. std::shared_ptr<Bonus> CTownHandler::createBonus(CBuilding * build, Bonus::BonusType type, int val, int subtype) const
  447. {
  448. return createBonus(build, type, val, emptyPropagator(), subtype);
  449. }
  450. std::shared_ptr<Bonus> CTownHandler::createBonus(CBuilding * build, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype) const
  451. {
  452. std::ostringstream descr;
  453. descr << build->getNameTranslated();
  454. return createBonusImpl(build->bid, type, val, prop, descr.str(), subtype);
  455. }
  456. std::shared_ptr<Bonus> CTownHandler::createBonusImpl(const BuildingID & building,
  457. Bonus::BonusType type,
  458. int val,
  459. TPropagatorPtr & prop,
  460. const std::string & description,
  461. int subtype) const
  462. {
  463. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, description, subtype);
  464. if(prop)
  465. b->addPropagator(prop);
  466. return b;
  467. }
  468. void CTownHandler::loadSpecialBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building)
  469. {
  470. for(const auto & b : source.Vector())
  471. {
  472. auto bonus = JsonUtils::parseBuildingBonus(b, building->bid, building->getNameTranslated());
  473. if(bonus == nullptr)
  474. continue;
  475. if(bonus->limiter != nullptr)
  476. {
  477. auto * limPtr = dynamic_cast<CreatureFactionLimiter *>(bonus->limiter.get());
  478. if(limPtr != nullptr && limPtr->faction == FactionID::ANY)
  479. limPtr->faction = building->town->faction->getId();
  480. }
  481. //JsonUtils::parseBuildingBonus produces UNKNOWN type propagator instead of empty.
  482. if(bonus->propagator != nullptr
  483. && bonus->propagator->getPropagatorType() == CBonusSystemNode::ENodeTypes::UNKNOWN)
  484. bonus->addPropagator(emptyPropagator());
  485. building->addNewBonus(bonus, bonusList);
  486. }
  487. }
  488. void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, const JsonNode & source)
  489. {
  490. assert(stringID.find(':') == std::string::npos);
  491. assert(!source.meta.empty());
  492. auto * ret = new CBuilding();
  493. ret->bid = getMappedValue<BuildingID, std::string>(stringID, BuildingID::NONE, MappedKeys::BUILDING_NAMES_TO_TYPES, false);
  494. if(ret->bid == BuildingID::NONE)
  495. ret->bid = source["id"].isNull() ? BuildingID(BuildingID::NONE) : BuildingID(source["id"].Float());
  496. if (ret->bid == BuildingID::NONE)
  497. logMod->error("Error: Building '%s' has not internal ID and won't work properly. Correct the typo or update VCMI.", stringID);
  498. ret->mode = ret->bid == BuildingID::GRAIL
  499. ? CBuilding::BUILD_GRAIL
  500. : getMappedValue<CBuilding::EBuildMode>(source["mode"], CBuilding::BUILD_NORMAL, CBuilding::MODES);
  501. ret->subId = getMappedValue<BuildingSubID::EBuildingSubID>(source["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS);
  502. ret->height = CBuilding::HEIGHT_NO_TOWER;
  503. if(ret->subId == BuildingSubID::LOOKOUT_TOWER
  504. || ret->bid == BuildingID::GRAIL)
  505. ret->height = getMappedValue<CBuilding::ETowerHeight>(source["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES);
  506. ret->identifier = stringID;
  507. ret->modScope = source.meta;
  508. ret->town = town;
  509. VLC->generaltexth->registerString(source.meta, ret->getNameTextID(), source["name"].String());
  510. VLC->generaltexth->registerString(source.meta, ret->getDescriptionTextID(), source["description"].String());
  511. ret->resources = TResources(source["cost"]);
  512. ret->produce = TResources(source["produce"]);
  513. if(ret->bid == BuildingID::TAVERN)
  514. addBonusesForVanilaBuilding(ret);
  515. else if(ret->bid.IsSpecialOrGrail())
  516. {
  517. loadSpecialBuildingBonuses(source["bonuses"], ret->buildingBonuses, ret);
  518. if(ret->buildingBonuses.empty())
  519. addBonusesForVanilaBuilding(ret);
  520. loadSpecialBuildingBonuses(source["onVisitBonuses"], ret->onVisitBonuses, ret);
  521. if(!ret->onVisitBonuses.empty())
  522. {
  523. if(ret->subId == BuildingSubID::NONE)
  524. ret->subId = BuildingSubID::CUSTOM_VISITING_BONUS;
  525. for(auto & bonus : ret->onVisitBonuses)
  526. bonus->sid = Bonus::getSid32(ret->town->faction->getIndex(), ret->bid);
  527. }
  528. }
  529. //MODS COMPATIBILITY FOR 0.96
  530. if(!ret->produce.nonZero())
  531. {
  532. switch (ret->bid) {
  533. break; case BuildingID::VILLAGE_HALL: ret->produce[EGameResID::GOLD] = 500;
  534. break; case BuildingID::TOWN_HALL : ret->produce[EGameResID::GOLD] = 1000;
  535. break; case BuildingID::CITY_HALL : ret->produce[EGameResID::GOLD] = 2000;
  536. break; case BuildingID::CAPITOL : ret->produce[EGameResID::GOLD] = 4000;
  537. break; case BuildingID::GRAIL : ret->produce[EGameResID::GOLD] = 5000;
  538. break; case BuildingID::RESOURCE_SILO :
  539. {
  540. switch (ret->town->primaryRes.toEnum())
  541. {
  542. case EGameResID::GOLD:
  543. ret->produce[ret->town->primaryRes] = 500;
  544. break;
  545. case EGameResID::WOOD_AND_ORE:
  546. ret->produce[EGameResID::WOOD] = 1;
  547. ret->produce[EGameResID::ORE] = 1;
  548. break;
  549. default:
  550. ret->produce[ret->town->primaryRes] = 1;
  551. break;
  552. }
  553. }
  554. }
  555. }
  556. loadBuildingRequirements(ret, source["requires"], requirementsToLoad);
  557. if(ret->bid.IsSpecialOrGrail())
  558. loadBuildingRequirements(ret, source["overrides"], overriddenBidsToLoad);
  559. if (!source["upgrades"].isNull())
  560. {
  561. // building id and upgrades can't be the same
  562. if(stringID == source["upgrades"].String())
  563. {
  564. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") %
  565. stringID % ret->town->faction->getNameTranslated()));
  566. }
  567. VLC->modh->identifiers.requestIdentifier(ret->town->getBuildingScope(), source["upgrades"], [=](si32 identifier)
  568. {
  569. ret->upgrade = BuildingID(identifier);
  570. });
  571. }
  572. else
  573. ret->upgrade = BuildingID::NONE;
  574. ret->town->buildings[ret->bid] = ret;
  575. registerObject(source.meta, ret->town->getBuildingScope(), ret->identifier, ret->bid);
  576. }
  577. void CTownHandler::loadBuildings(CTown * town, const JsonNode & source)
  578. {
  579. for(const auto & node : source.Struct())
  580. {
  581. if (!node.second.isNull())
  582. {
  583. loadBuilding(town, node.first, node.second);
  584. }
  585. }
  586. }
  587. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source) const
  588. {
  589. auto * ret = new CStructure();
  590. ret->building = nullptr;
  591. ret->buildable = nullptr;
  592. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->getJsonKey(), stringID, [=, &town](si32 identifier) mutable
  593. {
  594. ret->building = town.buildings[BuildingID(identifier)];
  595. });
  596. if (source["builds"].isNull())
  597. {
  598. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->getJsonKey(), stringID, [=, &town](si32 identifier) mutable
  599. {
  600. ret->building = town.buildings[BuildingID(identifier)];
  601. });
  602. }
  603. else
  604. {
  605. VLC->modh->identifiers.requestIdentifier("building." + town.faction->getJsonKey(), source["builds"], [=, &town](si32 identifier) mutable
  606. {
  607. ret->buildable = town.buildings[BuildingID(identifier)];
  608. });
  609. }
  610. ret->identifier = stringID;
  611. ret->pos.x = static_cast<si32>(source["x"].Float());
  612. ret->pos.y = static_cast<si32>(source["y"].Float());
  613. ret->pos.z = static_cast<si32>(source["z"].Float());
  614. ret->hiddenUpgrade = source["hidden"].Bool();
  615. ret->defName = source["animation"].String();
  616. ret->borderName = source["border"].String();
  617. ret->areaName = source["area"].String();
  618. town.clientInfo.structures.emplace_back(ret);
  619. }
  620. void CTownHandler::loadStructures(CTown &town, const JsonNode & source) const
  621. {
  622. for(const auto & node : source.Struct())
  623. {
  624. if (!node.second.isNull())
  625. loadStructure(town, node.first, node.second);
  626. }
  627. }
  628. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source) const
  629. {
  630. auto & dstSlots = town.clientInfo.hallSlots;
  631. const auto & srcSlots = source.Vector();
  632. dstSlots.resize(srcSlots.size());
  633. for(size_t i=0; i<dstSlots.size(); i++)
  634. {
  635. auto & dstRow = dstSlots[i];
  636. const auto & srcRow = srcSlots[i].Vector();
  637. dstRow.resize(srcRow.size());
  638. for(size_t j=0; j < dstRow.size(); j++)
  639. {
  640. auto & dstBox = dstRow[j];
  641. const auto & srcBox = srcRow[j].Vector();
  642. dstBox.resize(srcBox.size());
  643. for(size_t k=0; k<dstBox.size(); k++)
  644. {
  645. auto & dst = dstBox[k];
  646. const auto & src = srcBox[k];
  647. VLC->modh->identifiers.requestIdentifier("building." + town.faction->getJsonKey(), src, [&](si32 identifier)
  648. {
  649. dst = BuildingID(identifier);
  650. });
  651. }
  652. }
  653. }
  654. }
  655. Point JsonToPoint(const JsonNode & node)
  656. {
  657. if(!node.isStruct())
  658. return Point::makeInvalid();
  659. Point ret;
  660. ret.x = static_cast<si32>(node["x"].Float());
  661. ret.y = static_cast<si32>(node["y"].Float());
  662. return ret;
  663. }
  664. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source) const
  665. {
  666. town.clientInfo.siegePrefix = source["imagePrefix"].String();
  667. town.clientInfo.towerIconSmall = source["towerIconSmall"].String();
  668. town.clientInfo.towerIconLarge = source["towerIconLarge"].String();
  669. VLC->modh->identifiers.requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  670. {
  671. auto crId = CreatureID(creature);
  672. if((*VLC->creh)[crId]->animation.missleFrameAngles.empty())
  673. 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!"
  674. , town.faction->getNameTranslated()
  675. , (*VLC->creh)[crId]->getNameSingularTranslated());
  676. town.clientInfo.siegeShooter = crId;
  677. });
  678. auto & pos = town.clientInfo.siegePositions;
  679. pos.resize(21);
  680. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  681. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  682. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  683. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  684. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  685. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  686. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  687. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  688. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  689. pos[9] = JsonToPoint(source["gate"]["gate"]);
  690. pos[10] = JsonToPoint(source["gate"]["arch"]);
  691. pos[7] = JsonToPoint(source["walls"]["upper"]);
  692. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  693. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  694. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  695. pos[13] = JsonToPoint(source["moat"]["moat"]);
  696. pos[14] = JsonToPoint(source["moat"]["bank"]);
  697. pos[11] = JsonToPoint(source["static"]["bottom"]);
  698. pos[12] = JsonToPoint(source["static"]["top"]);
  699. pos[1] = JsonToPoint(source["static"]["background"]);
  700. }
  701. static void readIcon(JsonNode source, std::string & small, std::string & large)
  702. {
  703. if (source.getType() == JsonNode::JsonType::DATA_STRUCT) // don't crash on old format
  704. {
  705. small = source["small"].String();
  706. large = source["large"].String();
  707. }
  708. }
  709. void CTownHandler::loadClientData(CTown &town, const JsonNode & source) const
  710. {
  711. CTown::ClientInfo & info = town.clientInfo;
  712. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  713. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  714. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  715. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  716. info.hallBackground = source["hallBackground"].String();
  717. info.musicTheme = source["musicTheme"].String();
  718. info.townBackground = source["townBackground"].String();
  719. info.guildWindow = source["guildWindow"].String();
  720. info.buildingsIcons = source["buildingsIcons"].String();
  721. //left for back compatibility - will be removed later
  722. if(!source["guildBackground"].String().empty())
  723. info.guildBackground = source["guildBackground"].String();
  724. else
  725. info.guildBackground = "TPMAGE.bmp";
  726. if(!source["tavernVideo"].String().empty())
  727. info.tavernVideo = source["tavernVideo"].String();
  728. else
  729. info.tavernVideo = "TAVERN.BIK";
  730. //end of legacy assignment
  731. loadTownHall(town, source["hallSlots"]);
  732. loadStructures(town, source["structures"]);
  733. loadSiegeScreen(town, source["siege"]);
  734. }
  735. void CTownHandler::loadTown(CTown * town, const JsonNode & source)
  736. {
  737. const auto * resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  738. if(resIter == std::end(GameConstants::RESOURCE_NAMES))
  739. town->primaryRes = GameResID(EGameResID::WOOD_AND_ORE); //Wood + Ore
  740. else
  741. town->primaryRes = GameResID(resIter - std::begin(GameConstants::RESOURCE_NAMES));
  742. warMachinesToLoad[town] = source["warMachine"];
  743. town->mageLevel = static_cast<ui32>(source["mageGuild"].Float());
  744. town->namesCount = 0;
  745. for(const auto & name : source["names"].Vector())
  746. {
  747. VLC->generaltexth->registerString(town->faction->modScope, town->getRandomNameTextID(town->namesCount), name.String());
  748. town->namesCount += 1;
  749. }
  750. if (!source["moatAbility"].isNull()) // VCMI 1.2 compatibility code
  751. {
  752. VLC->modh->identifiers.requestIdentifier( "spell", source["moatAbility"], [=](si32 ability)
  753. {
  754. town->moatAbility = SpellID(ability);
  755. });
  756. }
  757. else
  758. {
  759. VLC->modh->identifiers.requestIdentifier( source.meta, "spell", "castleMoat", [=](si32 ability)
  760. {
  761. town->moatAbility = SpellID(ability);
  762. });
  763. }
  764. // Horde building creature level
  765. for(const JsonNode &node : source["horde"].Vector())
  766. town->hordeLvl[static_cast<int>(town->hordeLvl.size())] = static_cast<int>(node.Float());
  767. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  768. // but anything below 2 must be handled here
  769. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  770. town->hordeLvl[static_cast<int>(i)] = -1;
  771. const JsonVector & creatures = source["creatures"].Vector();
  772. town->creatures.resize(creatures.size());
  773. for (size_t i=0; i< creatures.size(); i++)
  774. {
  775. const JsonVector & level = creatures[i].Vector();
  776. town->creatures[i].resize(level.size());
  777. for (size_t j=0; j<level.size(); j++)
  778. {
  779. VLC->modh->identifiers.requestIdentifier("creature", level[j], [=](si32 creature)
  780. {
  781. town->creatures[i][j] = CreatureID(creature);
  782. });
  783. }
  784. }
  785. town->defaultTavernChance = static_cast<ui32>(source["defaultTavern"].Float());
  786. /// set chance of specific hero class to appear in this town
  787. for(const auto & node : source["tavern"].Struct())
  788. {
  789. int chance = static_cast<int>(node.second.Float());
  790. VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=](si32 classID)
  791. {
  792. VLC->heroh->classes[HeroClassID(classID)]->selectionProbability[town->faction->getIndex()] = chance;
  793. });
  794. }
  795. for(const auto & node : source["guildSpells"].Struct())
  796. {
  797. int chance = static_cast<int>(node.second.Float());
  798. VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=](si32 spellID)
  799. {
  800. VLC->spellh->objects.at(spellID)->probabilities[town->faction->getIndex()] = chance;
  801. });
  802. }
  803. for(const JsonNode & d : source["adventureMap"]["dwellings"].Vector())
  804. {
  805. town->dwellings.push_back(d["graphics"].String());
  806. town->dwellingNames.push_back(d["name"].String());
  807. }
  808. loadBuildings(town, source["buildings"]);
  809. loadClientData(*town, source);
  810. }
  811. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source) const
  812. {
  813. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  814. std::string prefix = source["prefix"].String();
  815. for(const JsonNode &piece : source["pieces"].Vector())
  816. {
  817. size_t index = faction.puzzleMap.size();
  818. SPuzzleInfo spi;
  819. spi.x = static_cast<si16>(piece["x"].Float());
  820. spi.y = static_cast<si16>(piece["y"].Float());
  821. spi.whenUncovered = static_cast<ui16>(piece["index"].Float());
  822. spi.number = static_cast<ui16>(index);
  823. // filename calculation
  824. std::ostringstream suffix;
  825. suffix << std::setfill('0') << std::setw(2) << index;
  826. spi.filename = prefix + suffix.str();
  827. faction.puzzleMap.push_back(spi);
  828. }
  829. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  830. }
  831. CFaction * CTownHandler::loadFromJson(const std::string & scope, const JsonNode & source, const std::string & identifier, size_t index)
  832. {
  833. assert(identifier.find(':') == std::string::npos);
  834. auto * faction = new CFaction();
  835. faction->index = static_cast<TFaction>(index);
  836. faction->modScope = scope;
  837. faction->identifier = identifier;
  838. VLC->generaltexth->registerString(scope, faction->getNameTextID(), source["name"].String());
  839. faction->creatureBg120 = source["creatureBackground"]["120px"].String();
  840. faction->creatureBg130 = source["creatureBackground"]["130px"].String();
  841. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, source["alignment"].String());
  842. if (alignment == -1)
  843. faction->alignment = EAlignment::NEUTRAL;
  844. else
  845. faction->alignment = static_cast<EAlignment>(alignment);
  846. auto preferUndergound = source["preferUndergroundPlacement"];
  847. faction->preferUndergroundPlacement = preferUndergound.isNull() ? false : preferUndergound.Bool();
  848. // NOTE: semi-workaround - normally, towns are supposed to have native terrains.
  849. // Towns without one are exceptions. So, vcmi requires nativeTerrain to be defined
  850. // But allows it to be defined with explicit value of "none" if town should not have native terrain
  851. // This is better than allowing such terrain-less towns silently, leading to issues with RMG
  852. faction->nativeTerrain = ETerrainId::NONE;
  853. if ( !source["nativeTerrain"].isNull() && source["nativeTerrain"].String() != "none")
  854. {
  855. VLC->modh->identifiers.requestIdentifier("terrain", source["nativeTerrain"], [=](int32_t index){
  856. faction->nativeTerrain = TerrainId(index);
  857. });
  858. }
  859. if (!source["town"].isNull())
  860. {
  861. faction->town = new CTown();
  862. faction->town->faction = faction;
  863. loadTown(faction->town, source["town"]);
  864. }
  865. else
  866. faction->town = nullptr;
  867. if (!source["puzzleMap"].isNull())
  868. loadPuzzle(*faction, source["puzzleMap"]);
  869. return faction;
  870. }
  871. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  872. {
  873. auto * object = loadFromJson(scope, data, name, objects.size());
  874. objects.emplace_back(object);
  875. if (object->town)
  876. {
  877. auto & info = object->town->clientInfo;
  878. info.icons[0][0] = 8 + object->index * 4 + 0;
  879. info.icons[0][1] = 8 + object->index * 4 + 1;
  880. info.icons[1][0] = 8 + object->index * 4 + 2;
  881. info.icons[1][1] = 8 + object->index * 4 + 3;
  882. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  883. {
  884. // register town once objects are loaded
  885. JsonNode config = data["town"]["mapObject"];
  886. config["faction"].String() = name;
  887. config["faction"].meta = scope;
  888. if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96
  889. config.meta = scope;
  890. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  891. // MODS COMPATIBILITY FOR 0.96
  892. const auto & advMap = data["town"]["adventureMap"];
  893. if (!advMap.isNull())
  894. {
  895. logMod->warn("Outdated town mod. Will try to generate valid templates out of fort");
  896. JsonNode config;
  897. config["animation"] = advMap["castle"];
  898. VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  899. }
  900. });
  901. }
  902. registerObject(scope, "faction", name, object->index);
  903. }
  904. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  905. {
  906. auto * object = loadFromJson(scope, data, name, index);
  907. if (objects.size() > index)
  908. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  909. else
  910. objects.resize(index + 1);
  911. objects[index] = object;
  912. if (object->town)
  913. {
  914. auto & info = object->town->clientInfo;
  915. info.icons[0][0] = (GameConstants::F_NUMBER + object->index) * 2 + 0;
  916. info.icons[0][1] = (GameConstants::F_NUMBER + object->index) * 2 + 1;
  917. info.icons[1][0] = object->index * 2 + 0;
  918. info.icons[1][1] = object->index * 2 + 1;
  919. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  920. {
  921. // register town once objects are loaded
  922. JsonNode config = data["town"]["mapObject"];
  923. config["faction"].String() = name;
  924. config["faction"].meta = scope;
  925. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  926. });
  927. }
  928. registerObject(scope, "faction", name, object->index);
  929. }
  930. void CTownHandler::loadRandomFaction()
  931. {
  932. static const ResourceID randomFactionPath("config/factions/random.json");
  933. JsonNode randomFactionJson(randomFactionPath);
  934. randomFactionJson.setMeta(CModHandler::scopeBuiltin(), true);
  935. loadBuildings(randomTown, randomFactionJson["random"]["town"]["buildings"]);
  936. }
  937. void CTownHandler::loadCustom()
  938. {
  939. loadRandomFaction();
  940. }
  941. void CTownHandler::afterLoadFinalization()
  942. {
  943. initializeRequirements();
  944. initializeOverridden();
  945. initializeWarMachines();
  946. }
  947. void CTownHandler::initializeRequirements()
  948. {
  949. // must be done separately after all ID's are known
  950. for (auto & requirement : requirementsToLoad)
  951. {
  952. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  953. {
  954. if (node.Vector().size() > 1)
  955. {
  956. logMod->warn("Unexpected length of town buildings requirements: %d", node.Vector().size());
  957. logMod->warn("Entry contains: ");
  958. logMod->warn(node.toJson());
  959. }
  960. return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).get());
  961. });
  962. }
  963. requirementsToLoad.clear();
  964. }
  965. void CTownHandler::initializeOverridden()
  966. {
  967. for(auto & bidHelper : overriddenBidsToLoad)
  968. {
  969. auto jsonNode = bidHelper.json;
  970. auto scope = bidHelper.town->getBuildingScope();
  971. for(const auto & b : jsonNode.Vector())
  972. {
  973. auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).get());
  974. bidHelper.building->overrideBids.insert(bid);
  975. }
  976. }
  977. overriddenBidsToLoad.clear();
  978. }
  979. void CTownHandler::initializeWarMachines()
  980. {
  981. // must be done separately after all objects are loaded
  982. for(auto & p : warMachinesToLoad)
  983. {
  984. CTown * t = p.first;
  985. JsonNode creatureKey = p.second;
  986. auto ret = VLC->modh->identifiers.getIdentifier("creature", creatureKey, false);
  987. if(ret)
  988. {
  989. const CCreature * creature = CreatureID(*ret).toCreature();
  990. t->warMachine = creature->warMachine;
  991. }
  992. }
  993. warMachinesToLoad.clear();
  994. }
  995. std::vector<bool> CTownHandler::getDefaultAllowed() const
  996. {
  997. std::vector<bool> allowedFactions;
  998. allowedFactions.reserve(objects.size());
  999. for(auto town : objects)
  1000. {
  1001. allowedFactions.push_back(town->town != nullptr);
  1002. }
  1003. return allowedFactions;
  1004. }
  1005. std::set<TFaction> CTownHandler::getAllowedFactions(bool withTown) const
  1006. {
  1007. std::set<TFaction> allowedFactions;
  1008. std::vector<bool> allowed;
  1009. if (withTown)
  1010. allowed = getDefaultAllowed();
  1011. else
  1012. allowed.resize( objects.size(), true);
  1013. for (size_t i=0; i<allowed.size(); i++)
  1014. if (allowed[i])
  1015. allowedFactions.insert(static_cast<TFaction>(i));
  1016. return allowedFactions;
  1017. }
  1018. const std::vector<std::string> & CTownHandler::getTypeNames() const
  1019. {
  1020. static const std::vector<std::string> typeNames = { "faction", "town" };
  1021. return typeNames;
  1022. }
  1023. VCMI_LIB_NAMESPACE_END