CampaignState.cpp 11 KB

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