CampaignState.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * CCampaignHandler.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 "CampaignState.h"
  12. #include "../JsonNode.h"
  13. #include "../filesystem/ResourceID.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../CGeneralTextHandler.h"
  16. #include "../mapping/CMapService.h"
  17. #include "../mapping/CMapInfo.h"
  18. #include "../mapping/CMap.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../serializer/JsonDeserializer.h"
  21. #include "../serializer/JsonSerializer.h"
  22. VCMI_LIB_NAMESPACE_BEGIN
  23. void CampaignScenario::loadPreconditionRegions(ui32 regions)
  24. {
  25. for (int i=0; i<32; i++) //for each bit in region. h3c however can only hold up to 16
  26. {
  27. if ( (1 << i) & regions)
  28. preconditionRegions.insert(static_cast<CampaignScenarioID>(i));
  29. }
  30. }
  31. CampaignRegions::RegionDescription CampaignRegions::RegionDescription::fromJson(const JsonNode & node)
  32. {
  33. CampaignRegions::RegionDescription rd;
  34. rd.infix = node["infix"].String();
  35. rd.xpos = static_cast<int>(node["x"].Float());
  36. rd.ypos = static_cast<int>(node["y"].Float());
  37. return rd;
  38. }
  39. CampaignRegions CampaignRegions::fromJson(const JsonNode & node)
  40. {
  41. CampaignRegions cr;
  42. cr.campPrefix = node["prefix"].String();
  43. cr.colorSuffixLength = static_cast<int>(node["color_suffix_length"].Float());
  44. for(const JsonNode & desc : node["desc"].Vector())
  45. cr.regions.push_back(CampaignRegions::RegionDescription::fromJson(desc));
  46. return cr;
  47. }
  48. CampaignRegions CampaignRegions::getLegacy(int campId)
  49. {
  50. static std::vector<CampaignRegions> campDescriptions;
  51. if(campDescriptions.empty()) //read once
  52. {
  53. const JsonNode config(ResourceID("config/campaign_regions.json"));
  54. for(const JsonNode & campaign : config["campaign_regions"].Vector())
  55. campDescriptions.push_back(CampaignRegions::fromJson(campaign));
  56. }
  57. return campDescriptions.at(campId);
  58. }
  59. std::string CampaignRegions::getBackgroundName() const
  60. {
  61. return campPrefix + "_BG.BMP";
  62. }
  63. Point CampaignRegions::getPosition(CampaignScenarioID which) const
  64. {
  65. auto const & region = regions[static_cast<int>(which)];
  66. return Point(region.xpos, region.ypos);
  67. }
  68. std::string CampaignRegions::getNameFor(CampaignScenarioID which, int colorIndex, std::string type) const
  69. {
  70. auto const & region = regions[static_cast<int>(which)];
  71. static const std::string colors[2][8] =
  72. {
  73. {"R", "B", "N", "G", "O", "V", "T", "P"},
  74. {"Re", "Bl", "Br", "Gr", "Or", "Vi", "Te", "Pi"}
  75. };
  76. std::string color = colors[colorSuffixLength - 1][colorIndex];
  77. return campPrefix + region.infix + "_" + type + color + ".BMP";
  78. }
  79. std::string CampaignRegions::getAvailableName(CampaignScenarioID which, int color) const
  80. {
  81. return getNameFor(which, color, "En");
  82. }
  83. std::string CampaignRegions::getSelectedName(CampaignScenarioID which, int color) const
  84. {
  85. return getNameFor(which, color, "Se");
  86. }
  87. std::string CampaignRegions::getConqueredName(CampaignScenarioID which, int color) const
  88. {
  89. return getNameFor(which, color, "Co");
  90. }
  91. bool CampaignBonus::isBonusForHero() const
  92. {
  93. return type == CampaignBonusType::SPELL ||
  94. type == CampaignBonusType::MONSTER ||
  95. type == CampaignBonusType::ARTIFACT ||
  96. type == CampaignBonusType::SPELL_SCROLL ||
  97. type == CampaignBonusType::PRIMARY_SKILL ||
  98. type == CampaignBonusType::SECONDARY_SKILL;
  99. }
  100. void CampaignHeader::loadLegacyData(ui8 campId)
  101. {
  102. campaignRegions = CampaignRegions::getLegacy(campId);
  103. numberOfScenarios = VLC->generaltexth->getCampaignLength(campId);
  104. }
  105. bool CampaignHeader::playerSelectedDifficulty() const
  106. {
  107. return difficultyChoosenByPlayer;
  108. }
  109. bool CampaignHeader::formatVCMI() const
  110. {
  111. return version == CampaignVersion::VCMI;
  112. }
  113. std::string CampaignHeader::getDescription() const
  114. {
  115. return description;
  116. }
  117. std::string CampaignHeader::getName() const
  118. {
  119. return name;
  120. }
  121. std::string CampaignHeader::getFilename() const
  122. {
  123. return filename;
  124. }
  125. const CampaignRegions & CampaignHeader::getRegions() const
  126. {
  127. return campaignRegions;
  128. }
  129. bool CampaignState::isConquered(CampaignScenarioID whichScenario) const
  130. {
  131. return vstd::contains(mapsConquered, whichScenario);
  132. }
  133. bool CampaignState::isAvailable(CampaignScenarioID whichScenario) const
  134. {
  135. //check for void scenraio
  136. if (!scenario(whichScenario).isNotVoid())
  137. {
  138. return false;
  139. }
  140. if (vstd::contains(mapsConquered, whichScenario))
  141. {
  142. return false;
  143. }
  144. //check preconditioned regions
  145. for (auto const & it : scenario(whichScenario).preconditionRegions)
  146. {
  147. if (!vstd::contains(mapsConquered, it))
  148. return false;
  149. }
  150. return true;
  151. }
  152. bool CampaignScenario::isNotVoid() const
  153. {
  154. return !mapName.empty();
  155. }
  156. std::set<HeroTypeID> CampaignState::getReservedHeroes() const
  157. {
  158. std::set<HeroTypeID> result;
  159. for (auto const & scenarioID : allScenarios())
  160. {
  161. if (isConquered(scenarioID))
  162. continue;
  163. auto header = getMapHeader(scenarioID);
  164. result.insert(header->reservedCampaignHeroes.begin(), header->reservedCampaignHeroes.end());
  165. }
  166. return result;
  167. }
  168. const CGHeroInstance * CampaignState::strongestHero(CampaignScenarioID scenarioId, const PlayerColor & owner) const
  169. {
  170. std::function<bool(const JsonNode & node)> isOwned = [owner](const JsonNode & node)
  171. {
  172. auto * h = CampaignState::crossoverDeserialize(node, nullptr);
  173. bool result = h->tempOwner == owner;
  174. vstd::clear_pointer(h);
  175. return result;
  176. };
  177. auto ownedHeroes = scenarioHeroPool.at(scenarioId) | boost::adaptors::filtered(isOwned);
  178. if (ownedHeroes.empty())
  179. return nullptr;
  180. return CampaignState::crossoverDeserialize(ownedHeroes.front(), nullptr);
  181. }
  182. /// Returns heroes that can be instantiated as hero placeholders by power
  183. const std::vector<JsonNode> & CampaignState::getHeroesByPower(CampaignScenarioID scenarioId) const
  184. {
  185. static const std::vector<JsonNode> emptyVector;
  186. if (scenarioHeroPool.count(scenarioId))
  187. return scenarioHeroPool.at(scenarioId);
  188. return emptyVector;
  189. }
  190. /// Returns hero for instantiation as placeholder by type
  191. /// May return empty JsonNode if such hero was not found
  192. const JsonNode & CampaignState::getHeroByType(HeroTypeID heroID) const
  193. {
  194. static const JsonNode emptyNode;
  195. if (!getReservedHeroes().count(heroID))
  196. return emptyNode;
  197. if (!globalHeroPool.count(heroID))
  198. return emptyNode;
  199. return globalHeroPool.at(heroID);
  200. }
  201. void CampaignState::setCurrentMapAsConquered(std::vector<CGHeroInstance *> heroes)
  202. {
  203. range::sort(heroes, [](const CGHeroInstance * a, const CGHeroInstance * b)
  204. {
  205. return a->getHeroStrength() > b->getHeroStrength();
  206. });
  207. logGlobal->info("Scenario %d of campaign %s (%s) has been completed", static_cast<int>(*currentMap), getFilename(), getName());
  208. mapsConquered.push_back(*currentMap);
  209. auto reservedHeroes = getReservedHeroes();
  210. for (auto * hero : heroes)
  211. {
  212. HeroTypeID heroType(hero->subID);
  213. JsonNode node = CampaignState::crossoverSerialize(hero);
  214. if (reservedHeroes.count(heroType))
  215. {
  216. logGlobal->info("Hero crossover: %d (%s) exported to global pool", hero->subID, hero->getNameTranslated());
  217. globalHeroPool[heroType] = node;
  218. }
  219. else
  220. {
  221. logGlobal->info("Hero crossover: %d (%s) exported to scenario pool", hero->subID, hero->getNameTranslated());
  222. scenarioHeroPool[*currentMap].push_back(node);
  223. }
  224. }
  225. }
  226. std::optional<CampaignBonus> CampaignState::getBonus(CampaignScenarioID which) const
  227. {
  228. auto bonuses = scenario(which).travelOptions.bonusesToChoose;
  229. assert(chosenCampaignBonuses.count(*currentMap) || bonuses.empty());
  230. if(bonuses.empty())
  231. return std::optional<CampaignBonus>();
  232. if (!getBonusID(which))
  233. return std::optional<CampaignBonus>();
  234. return bonuses[getBonusID(which).value()];
  235. }
  236. std::optional<ui8> CampaignState::getBonusID(CampaignScenarioID which) const
  237. {
  238. if (!chosenCampaignBonuses.count(which))
  239. return std::nullopt;
  240. return chosenCampaignBonuses.at(which);
  241. }
  242. std::unique_ptr<CMap> CampaignState::getMap(CampaignScenarioID scenarioId) const
  243. {
  244. // FIXME: there is certainly better way to handle maps inside campaigns
  245. if(scenarioId == CampaignScenarioID::NONE)
  246. scenarioId = currentMap.value();
  247. CMapService mapService;
  248. std::string scenarioName = filename.substr(0, filename.find('.'));
  249. boost::to_lower(scenarioName);
  250. scenarioName += ':' + std::to_string(static_cast<int>(scenarioId));
  251. const std::string & mapContent = mapPieces.find(scenarioId)->second;
  252. const auto * buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  253. return mapService.loadMap(buffer, static_cast<int>(mapContent.size()), scenarioName, modName, encoding);
  254. }
  255. std::unique_ptr<CMapHeader> CampaignState::getMapHeader(CampaignScenarioID scenarioId) const
  256. {
  257. if(scenarioId == CampaignScenarioID::NONE)
  258. scenarioId = currentMap.value();
  259. CMapService mapService;
  260. std::string scenarioName = filename.substr(0, filename.find('.'));
  261. boost::to_lower(scenarioName);
  262. scenarioName += ':' + std::to_string(static_cast<int>(scenarioId));
  263. const std::string & mapContent = mapPieces.find(scenarioId)->second;
  264. const auto * buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  265. return mapService.loadMapHeader(buffer, static_cast<int>(mapContent.size()), scenarioName, modName, encoding);
  266. }
  267. std::shared_ptr<CMapInfo> CampaignState::getMapInfo(CampaignScenarioID scenarioId) const
  268. {
  269. if(scenarioId == CampaignScenarioID::NONE)
  270. scenarioId = currentMap.value();
  271. auto mapInfo = std::make_shared<CMapInfo>();
  272. mapInfo->fileURI = filename;
  273. mapInfo->mapHeader = getMapHeader(scenarioId);
  274. mapInfo->countPlayers();
  275. return mapInfo;
  276. }
  277. JsonNode CampaignState::crossoverSerialize(CGHeroInstance * hero)
  278. {
  279. JsonNode node;
  280. JsonSerializer handler(nullptr, node);
  281. hero->serializeJsonOptions(handler);
  282. return node;
  283. }
  284. CGHeroInstance * CampaignState::crossoverDeserialize(const JsonNode & node, CMap * map)
  285. {
  286. JsonDeserializer handler(nullptr, const_cast<JsonNode&>(node));
  287. auto * hero = new CGHeroInstance();
  288. hero->ID = Obj::HERO;
  289. hero->serializeJsonOptions(handler);
  290. if (map)
  291. hero->serializeJsonArtifacts(handler, "artifacts", map);
  292. return hero;
  293. }
  294. void CampaignState::setCurrentMap(CampaignScenarioID which)
  295. {
  296. assert(scenario(which).isNotVoid());
  297. currentMap = which;
  298. }
  299. void CampaignState::setCurrentMapBonus(ui8 which)
  300. {
  301. chosenCampaignBonuses[*currentMap] = which;
  302. }
  303. std::optional<CampaignScenarioID> CampaignState::currentScenario() const
  304. {
  305. return currentMap;
  306. }
  307. std::optional<CampaignScenarioID> CampaignState::lastScenario() const
  308. {
  309. if (mapsConquered.empty())
  310. return std::nullopt;
  311. return mapsConquered.back();
  312. }
  313. std::set<CampaignScenarioID> CampaignState::conqueredScenarios() const
  314. {
  315. std::set<CampaignScenarioID> result;
  316. result.insert(mapsConquered.begin(), mapsConquered.end());
  317. return result;
  318. }
  319. std::set<CampaignScenarioID> Campaign::allScenarios() const
  320. {
  321. std::set<CampaignScenarioID> result;
  322. for (auto const & entry : scenarios)
  323. {
  324. if (entry.second.isNotVoid())
  325. result.insert(entry.first);
  326. }
  327. return result;
  328. }
  329. int Campaign::scenariosCount() const
  330. {
  331. return allScenarios().size();
  332. }
  333. const CampaignScenario & Campaign::scenario(CampaignScenarioID which) const
  334. {
  335. assert(scenarios.count(which));
  336. assert(scenarios.at(which).isNotVoid());
  337. return scenarios.at(which);
  338. }
  339. bool CampaignState::isCampaignFinished() const
  340. {
  341. return conqueredScenarios() == allScenarios();
  342. }
  343. VCMI_LIB_NAMESPACE_END