CTownHandler.cpp 31 KB

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