2
0

CTownHandler.cpp 24 KB

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