CTownHandler.cpp 35 KB

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