CampaignState.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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/ResourcePath.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(JsonPath::builtin("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. ImagePath CampaignRegions::getBackgroundName() const
  60. {
  61. return ImagePath::builtin(campPrefix + "_BG.BMP");
  62. }
  63. Point CampaignRegions::getPosition(CampaignScenarioID which) const
  64. {
  65. auto const & region = regions[which.getNum()];
  66. return Point(region.xpos, region.ypos);
  67. }
  68. ImagePath CampaignRegions::getNameFor(CampaignScenarioID which, int colorIndex, std::string type) const
  69. {
  70. auto const & region = regions[which.getNum()];
  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 ImagePath::builtin(campPrefix + region.infix + "_" + type + color + ".BMP");
  78. }
  79. ImagePath CampaignRegions::getAvailableName(CampaignScenarioID which, int color) const
  80. {
  81. return getNameFor(which, color, "En");
  82. }
  83. ImagePath CampaignRegions::getSelectedName(CampaignScenarioID which, int color) const
  84. {
  85. return getNameFor(which, color, "Se");
  86. }
  87. ImagePath 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::getDescriptionTranslated() const
  114. {
  115. return description.toString();
  116. }
  117. std::string CampaignHeader::getNameTranslated() const
  118. {
  119. return name.toString();
  120. }
  121. std::string CampaignHeader::getFilename() const
  122. {
  123. return filename;
  124. }
  125. std::string CampaignHeader::getModName() const
  126. {
  127. return modName;
  128. }
  129. std::string CampaignHeader::getEncoding() const
  130. {
  131. return encoding;
  132. }
  133. AudioPath CampaignHeader::getMusic() const
  134. {
  135. return music;
  136. }
  137. const CampaignRegions & CampaignHeader::getRegions() const
  138. {
  139. return campaignRegions;
  140. }
  141. bool CampaignState::isConquered(CampaignScenarioID whichScenario) const
  142. {
  143. return vstd::contains(mapsConquered, whichScenario);
  144. }
  145. bool CampaignState::isAvailable(CampaignScenarioID whichScenario) const
  146. {
  147. //check for void scenraio
  148. if (!scenario(whichScenario).isNotVoid())
  149. {
  150. return false;
  151. }
  152. if (vstd::contains(mapsConquered, whichScenario))
  153. {
  154. return false;
  155. }
  156. //check preconditioned regions
  157. for (auto const & it : scenario(whichScenario).preconditionRegions)
  158. {
  159. if (!vstd::contains(mapsConquered, it))
  160. return false;
  161. }
  162. return true;
  163. }
  164. bool CampaignScenario::isNotVoid() const
  165. {
  166. return !mapName.empty();
  167. }
  168. std::set<HeroTypeID> CampaignState::getReservedHeroes() const
  169. {
  170. std::set<HeroTypeID> result;
  171. for (auto const & scenarioID : allScenarios())
  172. {
  173. if (isConquered(scenarioID))
  174. continue;
  175. auto header = getMapHeader(scenarioID);
  176. result.insert(header->reservedCampaignHeroes.begin(), header->reservedCampaignHeroes.end());
  177. }
  178. return result;
  179. }
  180. const CGHeroInstance * CampaignState::strongestHero(CampaignScenarioID scenarioId, const PlayerColor & owner) const
  181. {
  182. std::function<bool(const JsonNode & node)> isOwned = [owner](const JsonNode & node)
  183. {
  184. auto * h = CampaignState::crossoverDeserialize(node, nullptr);
  185. bool result = h->tempOwner == owner;
  186. vstd::clear_pointer(h);
  187. return result;
  188. };
  189. auto ownedHeroes = scenarioHeroPool.at(scenarioId) | boost::adaptors::filtered(isOwned);
  190. if (ownedHeroes.empty())
  191. return nullptr;
  192. return CampaignState::crossoverDeserialize(ownedHeroes.front(), nullptr);
  193. }
  194. /// Returns heroes that can be instantiated as hero placeholders by power
  195. const std::vector<JsonNode> & CampaignState::getHeroesByPower(CampaignScenarioID scenarioId) const
  196. {
  197. static const std::vector<JsonNode> emptyVector;
  198. if (scenarioHeroPool.count(scenarioId))
  199. return scenarioHeroPool.at(scenarioId);
  200. return emptyVector;
  201. }
  202. /// Returns hero for instantiation as placeholder by type
  203. /// May return empty JsonNode if such hero was not found
  204. const JsonNode & CampaignState::getHeroByType(HeroTypeID heroID) const
  205. {
  206. static const JsonNode emptyNode;
  207. if (!getReservedHeroes().count(heroID))
  208. return emptyNode;
  209. if (!globalHeroPool.count(heroID))
  210. return emptyNode;
  211. return globalHeroPool.at(heroID);
  212. }
  213. void CampaignState::setCurrentMapAsConquered(std::vector<CGHeroInstance *> heroes)
  214. {
  215. range::sort(heroes, [](const CGHeroInstance * a, const CGHeroInstance * b)
  216. {
  217. return a->getHeroStrength() > b->getHeroStrength();
  218. });
  219. logGlobal->info("Scenario %d of campaign %s (%s) has been completed", currentMap->getNum(), getFilename(), getNameTranslated());
  220. mapsConquered.push_back(*currentMap);
  221. auto reservedHeroes = getReservedHeroes();
  222. for (auto * hero : heroes)
  223. {
  224. JsonNode node = CampaignState::crossoverSerialize(hero);
  225. if (reservedHeroes.count(hero->getHeroType()))
  226. {
  227. logGlobal->info("Hero crossover: %d (%s) exported to global pool", hero->getHeroType(), hero->getNameTranslated());
  228. globalHeroPool[hero->getHeroType()] = node;
  229. }
  230. else
  231. {
  232. logGlobal->info("Hero crossover: %d (%s) exported to scenario pool", hero->getHeroType(), hero->getNameTranslated());
  233. scenarioHeroPool[*currentMap].push_back(node);
  234. }
  235. }
  236. }
  237. std::optional<CampaignBonus> CampaignState::getBonus(CampaignScenarioID which) const
  238. {
  239. auto bonuses = scenario(which).travelOptions.bonusesToChoose;
  240. assert(chosenCampaignBonuses.count(*currentMap) || bonuses.empty());
  241. if(bonuses.empty())
  242. return std::optional<CampaignBonus>();
  243. if (!getBonusID(which))
  244. return std::optional<CampaignBonus>();
  245. return bonuses[getBonusID(which).value()];
  246. }
  247. std::optional<ui8> CampaignState::getBonusID(CampaignScenarioID which) const
  248. {
  249. if (!chosenCampaignBonuses.count(which))
  250. return std::nullopt;
  251. return chosenCampaignBonuses.at(which);
  252. }
  253. std::unique_ptr<CMap> CampaignState::getMap(CampaignScenarioID scenarioId) const
  254. {
  255. // FIXME: there is certainly better way to handle maps inside campaigns
  256. if(scenarioId == CampaignScenarioID::NONE)
  257. scenarioId = currentMap.value();
  258. CMapService mapService;
  259. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  260. boost::to_lower(scenarioName);
  261. scenarioName += ':' + std::to_string(scenarioId.getNum());
  262. const auto & mapContent = mapPieces.find(scenarioId)->second;
  263. return mapService.loadMap(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding());
  264. }
  265. std::unique_ptr<CMapHeader> CampaignState::getMapHeader(CampaignScenarioID scenarioId) const
  266. {
  267. if(scenarioId == CampaignScenarioID::NONE)
  268. scenarioId = currentMap.value();
  269. CMapService mapService;
  270. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  271. boost::to_lower(scenarioName);
  272. scenarioName += ':' + std::to_string(scenarioId.getNum());
  273. const auto & mapContent = mapPieces.find(scenarioId)->second;
  274. return mapService.loadMapHeader(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding());
  275. }
  276. std::shared_ptr<CMapInfo> CampaignState::getMapInfo(CampaignScenarioID scenarioId) const
  277. {
  278. if(scenarioId == CampaignScenarioID::NONE)
  279. scenarioId = currentMap.value();
  280. auto mapInfo = std::make_shared<CMapInfo>();
  281. mapInfo->fileURI = getFilename();
  282. mapInfo->mapHeader = getMapHeader(scenarioId);
  283. mapInfo->countPlayers();
  284. return mapInfo;
  285. }
  286. JsonNode CampaignState::crossoverSerialize(CGHeroInstance * hero)
  287. {
  288. JsonNode node;
  289. JsonSerializer handler(nullptr, node);
  290. hero->serializeJsonOptions(handler);
  291. return node;
  292. }
  293. CGHeroInstance * CampaignState::crossoverDeserialize(const JsonNode & node, CMap * map)
  294. {
  295. JsonDeserializer handler(nullptr, const_cast<JsonNode&>(node));
  296. auto * hero = new CGHeroInstance();
  297. hero->ID = Obj::HERO;
  298. hero->serializeJsonOptions(handler);
  299. if (map)
  300. hero->serializeJsonArtifacts(handler, "artifacts", map);
  301. return hero;
  302. }
  303. void CampaignState::setCurrentMap(CampaignScenarioID which)
  304. {
  305. assert(scenario(which).isNotVoid());
  306. currentMap = which;
  307. }
  308. void CampaignState::setCurrentMapBonus(ui8 which)
  309. {
  310. chosenCampaignBonuses[*currentMap] = which;
  311. }
  312. std::optional<CampaignScenarioID> CampaignState::currentScenario() const
  313. {
  314. return currentMap;
  315. }
  316. std::optional<CampaignScenarioID> CampaignState::lastScenario() const
  317. {
  318. if (mapsConquered.empty())
  319. return std::nullopt;
  320. return mapsConquered.back();
  321. }
  322. std::set<CampaignScenarioID> CampaignState::conqueredScenarios() const
  323. {
  324. std::set<CampaignScenarioID> result;
  325. result.insert(mapsConquered.begin(), mapsConquered.end());
  326. return result;
  327. }
  328. std::set<CampaignScenarioID> Campaign::allScenarios() const
  329. {
  330. std::set<CampaignScenarioID> result;
  331. for (auto const & entry : scenarios)
  332. {
  333. if (entry.second.isNotVoid())
  334. result.insert(entry.first);
  335. }
  336. return result;
  337. }
  338. int Campaign::scenariosCount() const
  339. {
  340. return allScenarios().size();
  341. }
  342. const CampaignScenario & Campaign::scenario(CampaignScenarioID which) const
  343. {
  344. assert(scenarios.count(which));
  345. assert(scenarios.at(which).isNotVoid());
  346. return scenarios.at(which);
  347. }
  348. bool CampaignState::isCampaignFinished() const
  349. {
  350. return conqueredScenarios() == allScenarios();
  351. }
  352. VCMI_LIB_NAMESPACE_END