CTownHandler.cpp 23 KB

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