CTownHandler.cpp 36 KB

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