CTownHandler.cpp 23 KB

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