CTownHandler.cpp 24 KB

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