CampaignState.cpp 11 KB

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