CTownHandler.cpp 35 KB

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