CTownHandler.cpp 24 KB

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