CampaignState.cpp 12 KB

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