CTownHandler.cpp 30 KB

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