CTownHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. #include "StdInc.h"
  2. #include "CTownHandler.h"
  3. #include "VCMI_Lib.h"
  4. #include "CGeneralTextHandler.h"
  5. #include "JsonNode.h"
  6. #include "StringConstants.h"
  7. #include "CCreatureHandler.h"
  8. #include "CModHandler.h"
  9. #include "CHeroHandler.h"
  10. #include "CArtHandler.h"
  11. #include "spells/CSpellHandler.h"
  12. #include "filesystem/Filesystem.h"
  13. #include "mapObjects/CObjectClassesHandler.h"
  14. #include "mapObjects/CObjectHandler.h"
  15. /*
  16. * CTownHandler.cpp, part of VCMI engine
  17. *
  18. * Authors: listed in file AUTHORS in main folder
  19. *
  20. * License: GNU General Public License v2.0 or later
  21. * Full text of license available in license.txt file, in main folder
  22. *
  23. */
  24. const int NAMES_PER_TOWN=16; // number of town names per faction in H3 files. Json can define any number
  25. const std::string & CBuilding::Name() const
  26. {
  27. return name;
  28. }
  29. const std::string & CBuilding::Description() const
  30. {
  31. return description;
  32. }
  33. BuildingID CBuilding::getBase() const
  34. {
  35. const CBuilding * build = this;
  36. while (build->upgrade >= 0)
  37. {
  38. build = build->town->buildings.at(build->upgrade);
  39. }
  40. return build->bid;
  41. }
  42. si32 CBuilding::getDistance(BuildingID buildID) const
  43. {
  44. const CBuilding * build = town->buildings.at(buildID);
  45. int distance = 0;
  46. while (build->upgrade >= 0 && build != this)
  47. {
  48. build = build->town->buildings.at(build->upgrade);
  49. distance++;
  50. }
  51. if (build == this)
  52. return distance;
  53. return -1;
  54. }
  55. CFaction::CFaction()
  56. {
  57. town = nullptr;
  58. }
  59. CFaction::~CFaction()
  60. {
  61. delete town;
  62. }
  63. CTown::CTown()
  64. {
  65. }
  66. CTown::~CTown()
  67. {
  68. for(auto & build : buildings)
  69. build.second.dellNull();
  70. for(auto & str : clientInfo.structures)
  71. str.dellNull();
  72. }
  73. std::vector<BattleHex> CTown::defaultMoatHexes()
  74. {
  75. static const std::vector<BattleHex> moatHexes = {11, 28, 44, 61, 77, 111, 129, 146, 164, 181};
  76. return moatHexes;
  77. }
  78. CTownHandler::CTownHandler()
  79. {
  80. VLC->townh = this;
  81. }
  82. CTownHandler::~CTownHandler()
  83. {
  84. for(auto faction : factions)
  85. faction.dellNull();
  86. }
  87. JsonNode readBuilding(CLegacyConfigParser & parser)
  88. {
  89. JsonNode ret;
  90. JsonNode & cost = ret["cost"];
  91. //note: this code will try to parse mithril as well but wil always return 0 for it
  92. for(const std::string & resID : GameConstants::RESOURCE_NAMES)
  93. cost[resID].Float() = parser.readNumber();
  94. cost.Struct().erase("mithril"); // erase mithril to avoid confusing validator
  95. parser.endLine();
  96. return ret;
  97. }
  98. std::vector<JsonNode> CTownHandler::loadLegacyData(size_t dataSize)
  99. {
  100. std::vector<JsonNode> dest(dataSize);
  101. factions.resize(dataSize);
  102. auto getBuild = [&](size_t town, size_t building) -> JsonNode &
  103. {
  104. return dest[town]["town"]["buildings"][EBuildingType::names[building]];
  105. };
  106. CLegacyConfigParser parser("DATA/BUILDING.TXT");
  107. parser.endLine(); // header
  108. parser.endLine();
  109. //Unique buildings
  110. for (size_t town=0; town<dataSize; town++)
  111. {
  112. parser.endLine(); //header
  113. parser.endLine();
  114. int buildID = 17;
  115. do
  116. {
  117. getBuild(town, buildID) = readBuilding(parser);
  118. buildID++;
  119. }
  120. while (!parser.isNextEntryEmpty());
  121. }
  122. // Common buildings
  123. parser.endLine(); // header
  124. parser.endLine();
  125. parser.endLine();
  126. int buildID = 0;
  127. do
  128. {
  129. JsonNode building = readBuilding(parser);
  130. for (size_t town=0; town<dataSize; town++)
  131. getBuild(town, buildID) = building;
  132. buildID++;
  133. }
  134. while (!parser.isNextEntryEmpty());
  135. parser.endLine(); //header
  136. parser.endLine();
  137. //Dwellings
  138. for (size_t town=0; town<dataSize; town++)
  139. {
  140. parser.endLine(); //header
  141. parser.endLine();
  142. for (size_t i=0; i<14; i++)
  143. {
  144. getBuild(town, 30+i) = readBuilding(parser);
  145. }
  146. }
  147. {
  148. CLegacyConfigParser parser("DATA/BLDGNEUT.TXT");
  149. for(int building=0; building<15; building++)
  150. {
  151. std::string name = parser.readString();
  152. std::string descr = parser.readString();
  153. parser.endLine();
  154. for(int j=0; j<dataSize; j++)
  155. {
  156. getBuild(j, building)["name"].String() = name;
  157. getBuild(j, building)["description"].String() = descr;
  158. }
  159. }
  160. parser.endLine(); // silo
  161. parser.endLine(); // blacksmith //unused entries
  162. parser.endLine(); // moat
  163. //shipyard with the ship
  164. std::string name = parser.readString();
  165. std::string descr = parser.readString();
  166. parser.endLine();
  167. for(int town=0; town<dataSize; town++)
  168. {
  169. getBuild(town, 20)["name"].String() = name;
  170. getBuild(town, 20)["description"].String() = descr;
  171. }
  172. //blacksmith
  173. for(int town=0; town<dataSize; town++)
  174. {
  175. getBuild(town, 16)["name"].String() = parser.readString();
  176. getBuild(town, 16)["description"].String() = parser.readString();
  177. parser.endLine();
  178. }
  179. }
  180. {
  181. CLegacyConfigParser parser("DATA/BLDGSPEC.TXT");
  182. for(int town=0; town<dataSize; town++)
  183. {
  184. for(int build=0; build<9; build++)
  185. {
  186. getBuild(town, 17 + build)["name"].String() = parser.readString();
  187. getBuild(town, 17 + build)["description"].String() = parser.readString();
  188. parser.endLine();
  189. }
  190. getBuild(town, 26)["name"].String() = parser.readString(); // Grail
  191. getBuild(town, 26)["description"].String() = parser.readString();
  192. parser.endLine();
  193. getBuild(town, 15)["name"].String() = parser.readString(); // Resource silo
  194. getBuild(town, 15)["description"].String() = parser.readString();
  195. parser.endLine();
  196. }
  197. }
  198. {
  199. CLegacyConfigParser parser("DATA/DWELLING.TXT");
  200. for(int town=0; town<dataSize; town++)
  201. {
  202. for(int build=0; build<14; build++)
  203. {
  204. getBuild(town, 30 + build)["name"].String() = parser.readString();
  205. getBuild(town, 30 + build)["description"].String() = parser.readString();
  206. parser.endLine();
  207. }
  208. }
  209. }
  210. {
  211. CLegacyConfigParser typeParser("DATA/TOWNTYPE.TXT");
  212. CLegacyConfigParser nameParser("DATA/TOWNNAME.TXT");
  213. size_t townID=0;
  214. do
  215. {
  216. dest[townID]["name"].String() = typeParser.readString();
  217. for (int i=0; i<NAMES_PER_TOWN; i++)
  218. {
  219. JsonNode name;
  220. name.String() = nameParser.readString();
  221. dest[townID]["town"]["names"].Vector().push_back(name);
  222. nameParser.endLine();
  223. }
  224. townID++;
  225. }
  226. while (typeParser.endLine());
  227. }
  228. return dest;
  229. }
  230. void CTownHandler::loadBuildingRequirements(CTown &town, CBuilding & building, const JsonNode & source)
  231. {
  232. if (source.isNull())
  233. return;
  234. BuildingRequirementsHelper hlp;
  235. hlp.building = &building;
  236. hlp.faction = town.faction;
  237. hlp.json = source;
  238. requirementsToLoad.push_back(hlp);
  239. }
  240. void CTownHandler::loadBuilding(CTown &town, const std::string & stringID, const JsonNode & source)
  241. {
  242. auto ret = new CBuilding;
  243. static const std::string modes [] = {"normal", "auto", "special", "grail"};
  244. ret->mode = static_cast<CBuilding::EBuildMode>(boost::find(modes, source["mode"].String()) - modes);
  245. ret->identifier = stringID;
  246. ret->town = &town;
  247. ret->bid = BuildingID(source["id"].Float());
  248. ret->name = source["name"].String();
  249. ret->description = source["description"].String();
  250. ret->resources = TResources(source["cost"]);
  251. ret->produce = TResources(source["produce"]);
  252. //MODS COMPATIBILITY FOR 0.96
  253. if(!ret->produce.nonZero())
  254. {
  255. switch (ret->bid) {
  256. break; case BuildingID::VILLAGE_HALL: ret->produce[Res::GOLD] = 500;
  257. break; case BuildingID::TOWN_HALL : ret->produce[Res::GOLD] = 1000;
  258. break; case BuildingID::CITY_HALL : ret->produce[Res::GOLD] = 2000;
  259. break; case BuildingID::CAPITOL : ret->produce[Res::GOLD] = 4000;
  260. break; case BuildingID::GRAIL : ret->produce[Res::GOLD] = 5000;
  261. break; case BuildingID::RESOURCE_SILO :
  262. {
  263. switch (ret->town->primaryRes)
  264. {
  265. case Res::GOLD:
  266. ret->produce[ret->town->primaryRes] = 500;
  267. break;
  268. case Res::WOOD_AND_ORE:
  269. ret->produce[Res::WOOD] = 1;
  270. ret->produce[Res::ORE] = 1;
  271. break;
  272. default:
  273. ret->produce[ret->town->primaryRes] = 1;
  274. break;
  275. }
  276. }
  277. }
  278. }
  279. loadBuildingRequirements(town, *ret, source["requires"]);
  280. if (!source["upgrades"].isNull())
  281. {
  282. // building id and upgrades can't be the same
  283. if(stringID == source["upgrades"].String())
  284. {
  285. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") %
  286. stringID % town.faction->name));
  287. }
  288. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["upgrades"], [=](si32 identifier)
  289. {
  290. ret->upgrade = BuildingID(identifier);
  291. });
  292. }
  293. else
  294. ret->upgrade = BuildingID::NONE;
  295. town.buildings[ret->bid] = ret;
  296. VLC->modh->identifiers.registerObject(source.meta, "building." + town.faction->identifier, ret->identifier, ret->bid);
  297. }
  298. void CTownHandler::loadBuildings(CTown &town, const JsonNode & source)
  299. {
  300. for(auto &node : source.Struct())
  301. {
  302. if (!node.second.isNull())
  303. {
  304. loadBuilding(town, node.first, node.second);
  305. }
  306. }
  307. }
  308. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source)
  309. {
  310. auto ret = new CStructure;
  311. ret->building = nullptr;
  312. ret->buildable = nullptr;
  313. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  314. {
  315. ret->building = town.buildings[BuildingID(identifier)];
  316. });
  317. if (source["builds"].isNull())
  318. {
  319. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  320. {
  321. ret->building = town.buildings[BuildingID(identifier)];
  322. });
  323. }
  324. else
  325. {
  326. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["builds"], [=, &town](si32 identifier) mutable
  327. {
  328. ret->buildable = town.buildings[BuildingID(identifier)];
  329. });
  330. }
  331. ret->identifier = stringID;
  332. ret->pos.x = source["x"].Float();
  333. ret->pos.y = source["y"].Float();
  334. ret->pos.z = source["z"].Float();
  335. ret->hiddenUpgrade = source["hidden"].Bool();
  336. ret->defName = source["animation"].String();
  337. ret->borderName = source["border"].String();
  338. ret->areaName = source["area"].String();
  339. town.clientInfo.structures.push_back(ret);
  340. }
  341. void CTownHandler::loadStructures(CTown &town, const JsonNode & source)
  342. {
  343. for(auto &node : source.Struct())
  344. {
  345. if (!node.second.isNull())
  346. loadStructure(town, node.first, node.second);
  347. }
  348. }
  349. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source)
  350. {
  351. auto & dstSlots = town.clientInfo.hallSlots;
  352. auto & srcSlots = source.Vector();
  353. dstSlots.resize(srcSlots.size());
  354. for(size_t i=0; i<dstSlots.size(); i++)
  355. {
  356. auto & dstRow = dstSlots[i];
  357. auto & srcRow = srcSlots[i].Vector();
  358. dstRow.resize(srcRow.size());
  359. for(size_t j=0; j < dstRow.size(); j++)
  360. {
  361. auto & dstBox = dstRow[j];
  362. auto & srcBox = srcRow[j].Vector();
  363. dstBox.resize(srcBox.size());
  364. for(size_t k=0; k<dstBox.size(); k++)
  365. {
  366. auto & dst = dstBox[k];
  367. auto & src = srcBox[k];
  368. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, src, [&](si32 identifier)
  369. {
  370. dst = BuildingID(identifier);
  371. });
  372. }
  373. }
  374. }
  375. }
  376. CTown::ClientInfo::Point JsonToPoint(const JsonNode & node)
  377. {
  378. CTown::ClientInfo::Point ret;
  379. ret.x = node["x"].Float();
  380. ret.y = node["y"].Float();
  381. return ret;
  382. }
  383. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source)
  384. {
  385. town.clientInfo.siegePrefix = source["imagePrefix"].String();
  386. VLC->modh->identifiers.requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  387. {
  388. town.clientInfo.siegeShooter = CreatureID(creature);
  389. });
  390. auto & pos = town.clientInfo.siegePositions;
  391. pos.resize(21);
  392. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  393. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  394. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  395. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  396. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  397. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  398. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  399. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  400. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  401. pos[9] = JsonToPoint(source["gate"]["gate"]);
  402. pos[10] = JsonToPoint(source["gate"]["arch"]);
  403. pos[7] = JsonToPoint(source["walls"]["upper"]);
  404. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  405. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  406. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  407. pos[13] = JsonToPoint(source["moat"]["moat"]);
  408. pos[14] = JsonToPoint(source["moat"]["bank"]);
  409. pos[11] = JsonToPoint(source["static"]["bottom"]);
  410. pos[12] = JsonToPoint(source["static"]["top"]);
  411. pos[1] = JsonToPoint(source["static"]["background"]);
  412. }
  413. static void readIcon(JsonNode source, std::string & small, std::string & large)
  414. {
  415. if (source.getType() == JsonNode::DATA_STRUCT) // don't crash on old format
  416. {
  417. small = source["small"].String();
  418. large = source["large"].String();
  419. }
  420. }
  421. void CTownHandler::loadClientData(CTown &town, const JsonNode & source)
  422. {
  423. CTown::ClientInfo & info = town.clientInfo;
  424. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  425. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  426. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  427. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  428. info.hallBackground = source["hallBackground"].String();
  429. info.musicTheme = source["musicTheme"].String();
  430. info.townBackground = source["townBackground"].String();
  431. info.guildWindow = source["guildWindow"].String();
  432. info.buildingsIcons = source["buildingsIcons"].String();
  433. //left for back compatibility - will be removed later
  434. if (source["guildBackground"].String() != "")
  435. info.guildBackground = source["guildBackground"].String();
  436. else
  437. info.guildBackground = "TPMAGE.bmp";
  438. if (source["tavernVideo"].String() != "")
  439. info.tavernVideo = source["tavernVideo"].String();
  440. else
  441. info.tavernVideo = "TAVERN.BIK";
  442. //end of legacy assignment
  443. loadTownHall(town, source["hallSlots"]);
  444. loadStructures(town, source["structures"]);
  445. loadSiegeScreen(town, source["siege"]);
  446. }
  447. void CTownHandler::loadTown(CTown &town, const JsonNode & source)
  448. {
  449. auto resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  450. if (resIter == std::end(GameConstants::RESOURCE_NAMES))
  451. town.primaryRes = Res::WOOD_AND_ORE; //Wood + Ore
  452. else
  453. town.primaryRes = resIter - std::begin(GameConstants::RESOURCE_NAMES);
  454. VLC->modh->identifiers.requestIdentifier("creature", source["warMachine"],
  455. [&town](si32 creature)
  456. {
  457. town.warMachine = CArtHandler::creatureToMachineID(CreatureID(creature));
  458. });
  459. town.moatDamage = source["moatDamage"].Float();
  460. // Compatability for <= 0.98f mods
  461. if(source["moatHexes"].isNull())
  462. {
  463. town.moatHexes = CTown::defaultMoatHexes();
  464. }
  465. else
  466. town.moatHexes = source["moatHexes"].convertTo<std::vector<BattleHex> >();
  467. town.mageLevel = source["mageGuild"].Float();
  468. town.names = source["names"].convertTo<std::vector<std::string> >();
  469. // Horde building creature level
  470. for(const JsonNode &node : source["horde"].Vector())
  471. town.hordeLvl[town.hordeLvl.size()] = node.Float();
  472. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  473. // but anything below 2 must be handled here
  474. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  475. town.hordeLvl[i] = -1;
  476. const JsonVector & creatures = source["creatures"].Vector();
  477. town.creatures.resize(creatures.size());
  478. for (size_t i=0; i< creatures.size(); i++)
  479. {
  480. const JsonVector & level = creatures[i].Vector();
  481. town.creatures[i].resize(level.size());
  482. for (size_t j=0; j<level.size(); j++)
  483. {
  484. VLC->modh->identifiers.requestIdentifier("creature", level[j], [=, &town](si32 creature)
  485. {
  486. town.creatures[i][j] = CreatureID(creature);
  487. });
  488. }
  489. }
  490. town.defaultTavernChance = source["defaultTavern"].Float();
  491. /// set chance of specific hero class to appear in this town
  492. for(auto &node : source["tavern"].Struct())
  493. {
  494. int chance = node.second.Float();
  495. VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=, &town](si32 classID)
  496. {
  497. VLC->heroh->classes.heroClasses[classID]->selectionProbability[town.faction->index] = chance;
  498. });
  499. }
  500. for(auto &node : source["guildSpells"].Struct())
  501. {
  502. int chance = node.second.Float();
  503. VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=, &town](si32 spellID)
  504. {
  505. VLC->spellh->objects.at(spellID)->probabilities[town.faction->index] = chance;
  506. });
  507. }
  508. for (const JsonNode &d : source["adventureMap"]["dwellings"].Vector())
  509. {
  510. town.dwellings.push_back (d["graphics"].String());
  511. town.dwellingNames.push_back (d["name"].String());
  512. }
  513. loadBuildings(town, source["buildings"]);
  514. loadClientData(town,source);
  515. }
  516. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source)
  517. {
  518. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  519. std::string prefix = source["prefix"].String();
  520. for(const JsonNode &piece : source["pieces"].Vector())
  521. {
  522. size_t index = faction.puzzleMap.size();
  523. SPuzzleInfo spi;
  524. spi.x = piece["x"].Float();
  525. spi.y = piece["y"].Float();
  526. spi.whenUncovered = piece["index"].Float();
  527. spi.number = index;
  528. // filename calculation
  529. std::ostringstream suffix;
  530. suffix << std::setfill('0') << std::setw(2) << index;
  531. spi.filename = prefix + suffix.str();
  532. faction.puzzleMap.push_back(spi);
  533. }
  534. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  535. }
  536. CFaction * CTownHandler::loadFromJson(const JsonNode &source, const std::string & identifier)
  537. {
  538. auto faction = new CFaction();
  539. faction->name = source["name"].String();
  540. faction->identifier = identifier;
  541. faction->creatureBg120 = source["creatureBackground"]["120px"].String();
  542. faction->creatureBg130 = source["creatureBackground"]["130px"].String();
  543. faction->nativeTerrain = ETerrainType(vstd::find_pos(GameConstants::TERRAIN_NAMES,
  544. source["nativeTerrain"].String()));
  545. int alignment = vstd::find_pos(EAlignment::names, source["alignment"].String());
  546. if (alignment == -1)
  547. faction->alignment = EAlignment::NEUTRAL;
  548. else
  549. faction->alignment = static_cast<EAlignment::EAlignment>(alignment);
  550. if (!source["town"].isNull())
  551. {
  552. faction->town = new CTown;
  553. faction->town->faction = faction;
  554. loadTown(*faction->town, source["town"]);
  555. }
  556. else
  557. faction->town = nullptr;
  558. if (!source["puzzleMap"].isNull())
  559. loadPuzzle(*faction, source["puzzleMap"]);
  560. return faction;
  561. }
  562. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  563. {
  564. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  565. object->index = factions.size();
  566. factions.push_back(object);
  567. if (object->town)
  568. {
  569. auto & info = object->town->clientInfo;
  570. info.icons[0][0] = 8 + object->index * 4 + 0;
  571. info.icons[0][1] = 8 + object->index * 4 + 1;
  572. info.icons[1][0] = 8 + object->index * 4 + 2;
  573. info.icons[1][1] = 8 + object->index * 4 + 3;
  574. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  575. {
  576. // register town once objects are loaded
  577. JsonNode config = data["town"]["mapObject"];
  578. config["faction"].String() = name;
  579. config["faction"].meta = scope;
  580. if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96
  581. config.meta = scope;
  582. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  583. // MODS COMPATIBILITY FOR 0.96
  584. auto & advMap = data["town"]["adventureMap"];
  585. if (!advMap.isNull())
  586. {
  587. logGlobal->warnStream() << "Outdated town mod. Will try to generate valid templates out of fort";
  588. JsonNode config;
  589. config["animation"] = advMap["castle"];
  590. VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  591. }
  592. });
  593. }
  594. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  595. }
  596. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  597. {
  598. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  599. object->index = index;
  600. assert(factions[index] == nullptr); // ensure that this id was not loaded before
  601. factions[index] = object;
  602. if (object->town)
  603. {
  604. auto & info = object->town->clientInfo;
  605. info.icons[0][0] = (GameConstants::F_NUMBER + object->index) * 2 + 0;
  606. info.icons[0][1] = (GameConstants::F_NUMBER + object->index) * 2 + 1;
  607. info.icons[1][0] = object->index * 2 + 0;
  608. info.icons[1][1] = object->index * 2 + 1;
  609. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  610. {
  611. // register town once objects are loaded
  612. JsonNode config = data["town"]["mapObject"];
  613. config["faction"].String() = name;
  614. config["faction"].meta = scope;
  615. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  616. });
  617. }
  618. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  619. }
  620. void CTownHandler::afterLoadFinalization()
  621. {
  622. initializeRequirements();
  623. }
  624. void CTownHandler::initializeRequirements()
  625. {
  626. // must be done separately after all ID's are known
  627. for (auto & requirement : requirementsToLoad)
  628. {
  629. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  630. {
  631. if (node.Vector().size() > 1)
  632. {
  633. logGlobal->warnStream() << "Unexpected length of town buildings requirements: " << node.Vector().size();
  634. logGlobal->warnStream() << "Entry contains " << node;
  635. }
  636. return BuildingID(VLC->modh->identifiers.getIdentifier("building." + requirement.faction->identifier, node.Vector()[0]).get());
  637. });
  638. }
  639. requirementsToLoad.clear();
  640. }
  641. std::vector<bool> CTownHandler::getDefaultAllowed() const
  642. {
  643. std::vector<bool> allowedFactions;
  644. for(auto town : factions)
  645. {
  646. allowedFactions.push_back(town->town != nullptr);
  647. }
  648. return allowedFactions;
  649. }
  650. std::set<TFaction> CTownHandler::getAllowedFactions(bool withTown /*=true*/) const
  651. {
  652. std::set<TFaction> allowedFactions;
  653. std::vector<bool> allowed;
  654. if (withTown)
  655. allowed = getDefaultAllowed();
  656. else
  657. allowed.resize( factions.size(), true);
  658. for (size_t i=0; i<allowed.size(); i++)
  659. if (allowed[i])
  660. allowedFactions.insert(i);
  661. return allowedFactions;
  662. }
  663. si32 CTownHandler::decodeFaction(const std::string & identifier)
  664. {
  665. auto rawId = VLC->modh->identifiers.getIdentifier("core", "faction", identifier);
  666. if(rawId)
  667. return rawId.get();
  668. else
  669. return -1;
  670. }
  671. std::string CTownHandler::encodeFaction(const si32 index)
  672. {
  673. return VLC->townh->factions[index]->identifier;
  674. }