CampaignState.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. #include "../json/JsonUtils.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["colorSuffixLength"].Float());
  45. cr.campSuffix = node["suffix"].isNull() ? std::vector<std::string>() : std::vector<std::string>{node["suffix"].Vector()[0].String(), node["suffix"].Vector()[1].String(), node["suffix"].Vector()[2].String()};
  46. cr.campBackground = node["background"].isNull() ? "" : node["background"].String();
  47. for(const JsonNode & desc : node["desc"].Vector())
  48. cr.regions.push_back(CampaignRegions::RegionDescription::fromJson(desc));
  49. return cr;
  50. }
  51. CampaignRegions CampaignRegions::getLegacy(int campId)
  52. {
  53. static std::vector<CampaignRegions> campDescriptions;
  54. if(campDescriptions.empty()) //read once
  55. {
  56. const JsonNode config(JsonPath::builtin("config/campaign_regions.json"));
  57. for(const JsonNode & campaign : config["campaign_regions"].Vector())
  58. campDescriptions.push_back(CampaignRegions::fromJson(campaign));
  59. }
  60. return campDescriptions.at(campId);
  61. }
  62. ImagePath CampaignRegions::getBackgroundName() const
  63. {
  64. if(campBackground.empty())
  65. return ImagePath::builtin(campPrefix + "_BG.BMP");
  66. else
  67. return ImagePath::builtin(campBackground);
  68. }
  69. Point CampaignRegions::getPosition(CampaignScenarioID which) const
  70. {
  71. auto const & region = regions[which.getNum()];
  72. return Point(region.xpos, region.ypos);
  73. }
  74. ImagePath CampaignRegions::getNameFor(CampaignScenarioID which, int colorIndex, std::string type) const
  75. {
  76. auto const & region = regions[which.getNum()];
  77. static const std::array<std::array<std::string, 8>, 3> colors = {{
  78. { "", "", "", "", "", "", "", "" },
  79. { "R", "B", "N", "G", "O", "V", "T", "P" },
  80. { "Re", "Bl", "Br", "Gr", "Or", "Vi", "Te", "Pi" }
  81. }};
  82. std::string color = colors[colorSuffixLength][colorIndex];
  83. return ImagePath::builtin(campPrefix + region.infix + "_" + type + color + ".BMP");
  84. }
  85. ImagePath CampaignRegions::getAvailableName(CampaignScenarioID which, int color) const
  86. {
  87. if(campSuffix.empty())
  88. return getNameFor(which, color, "En");
  89. else
  90. return getNameFor(which, color, campSuffix[0]);
  91. }
  92. ImagePath CampaignRegions::getSelectedName(CampaignScenarioID which, int color) const
  93. {
  94. if(campSuffix.empty())
  95. return getNameFor(which, color, "Se");
  96. else
  97. return getNameFor(which, color, campSuffix[1]);
  98. }
  99. ImagePath CampaignRegions::getConqueredName(CampaignScenarioID which, int color) const
  100. {
  101. if(campSuffix.empty())
  102. return getNameFor(which, color, "Co");
  103. else
  104. return getNameFor(which, color, campSuffix[2]);
  105. }
  106. bool CampaignBonus::isBonusForHero() const
  107. {
  108. return type == CampaignBonusType::SPELL ||
  109. type == CampaignBonusType::MONSTER ||
  110. type == CampaignBonusType::ARTIFACT ||
  111. type == CampaignBonusType::SPELL_SCROLL ||
  112. type == CampaignBonusType::PRIMARY_SKILL ||
  113. type == CampaignBonusType::SECONDARY_SKILL;
  114. }
  115. void CampaignHeader::loadLegacyData(ui8 campId)
  116. {
  117. campaignRegions = CampaignRegions::getLegacy(campId);
  118. numberOfScenarios = VLC->generaltexth->getCampaignLength(campId);
  119. }
  120. void CampaignHeader::loadLegacyData(CampaignRegions regions, int numOfScenario)
  121. {
  122. campaignRegions = regions;
  123. numberOfScenarios = numOfScenario;
  124. }
  125. bool CampaignHeader::playerSelectedDifficulty() const
  126. {
  127. return difficultyChosenByPlayer;
  128. }
  129. bool CampaignHeader::formatVCMI() const
  130. {
  131. return version == CampaignVersion::VCMI;
  132. }
  133. std::string CampaignHeader::getDescriptionTranslated() const
  134. {
  135. return description.toString();
  136. }
  137. std::string CampaignHeader::getNameTranslated() const
  138. {
  139. return name.toString();
  140. }
  141. std::string CampaignHeader::getAuthor() const
  142. {
  143. return authorContact.toString();
  144. }
  145. std::string CampaignHeader::getAuthorContact() const
  146. {
  147. return authorContact.toString();
  148. }
  149. std::string CampaignHeader::getCampaignVersion() const
  150. {
  151. return campaignVersion.toString();
  152. }
  153. time_t CampaignHeader::getCreationDateTime() const
  154. {
  155. return creationDateTime;
  156. }
  157. std::string CampaignHeader::getFilename() const
  158. {
  159. return filename;
  160. }
  161. std::string CampaignHeader::getModName() const
  162. {
  163. return modName;
  164. }
  165. std::string CampaignHeader::getEncoding() const
  166. {
  167. return encoding;
  168. }
  169. AudioPath CampaignHeader::getMusic() const
  170. {
  171. return music;
  172. }
  173. ImagePath CampaignHeader::getLoadingBackground() const
  174. {
  175. return loadingBackground;
  176. }
  177. ImagePath CampaignHeader::getVideoRim() const
  178. {
  179. return videoRim;
  180. }
  181. VideoPath CampaignHeader::getIntroVideo() const
  182. {
  183. return introVideo;
  184. }
  185. VideoPath CampaignHeader::getOutroVideo() const
  186. {
  187. return outroVideo;
  188. }
  189. const CampaignRegions & CampaignHeader::getRegions() const
  190. {
  191. return campaignRegions;
  192. }
  193. TextContainerRegistrable & CampaignHeader::getTexts()
  194. {
  195. return textContainer;
  196. }
  197. bool CampaignState::isConquered(CampaignScenarioID whichScenario) const
  198. {
  199. return vstd::contains(mapsConquered, whichScenario);
  200. }
  201. bool CampaignState::isAvailable(CampaignScenarioID whichScenario) const
  202. {
  203. //check for void scenraio
  204. if (!scenario(whichScenario).isNotVoid())
  205. {
  206. return false;
  207. }
  208. if (vstd::contains(mapsConquered, whichScenario))
  209. {
  210. return false;
  211. }
  212. //check preconditioned regions
  213. for (auto const & it : scenario(whichScenario).preconditionRegions)
  214. {
  215. if (!vstd::contains(mapsConquered, it))
  216. return false;
  217. }
  218. return true;
  219. }
  220. bool CampaignScenario::isNotVoid() const
  221. {
  222. return !mapName.empty();
  223. }
  224. std::set<HeroTypeID> CampaignState::getReservedHeroes() const
  225. {
  226. std::set<HeroTypeID> result;
  227. for (auto const & scenarioID : allScenarios())
  228. {
  229. if (isConquered(scenarioID))
  230. continue;
  231. auto header = getMapHeader(scenarioID);
  232. result.insert(header->reservedCampaignHeroes.begin(), header->reservedCampaignHeroes.end());
  233. }
  234. return result;
  235. }
  236. const CGHeroInstance * CampaignState::strongestHero(CampaignScenarioID scenarioId, const PlayerColor & owner) const
  237. {
  238. std::function<bool(const JsonNode & node)> isOwned = [&](const JsonNode & node)
  239. {
  240. auto * h = CampaignState::crossoverDeserialize(node, nullptr);
  241. bool result = h->tempOwner == owner;
  242. vstd::clear_pointer(h);
  243. return result;
  244. };
  245. auto ownedHeroes = scenarioHeroPool.at(scenarioId) | boost::adaptors::filtered(isOwned);
  246. if (ownedHeroes.empty())
  247. return nullptr;
  248. return CampaignState::crossoverDeserialize(ownedHeroes.front(), nullptr);
  249. }
  250. /// Returns heroes that can be instantiated as hero placeholders by power
  251. const std::vector<JsonNode> & CampaignState::getHeroesByPower(CampaignScenarioID scenarioId) const
  252. {
  253. static const std::vector<JsonNode> emptyVector;
  254. if (scenarioHeroPool.count(scenarioId))
  255. return scenarioHeroPool.at(scenarioId);
  256. return emptyVector;
  257. }
  258. /// Returns hero for instantiation as placeholder by type
  259. /// May return empty JsonNode if such hero was not found
  260. const JsonNode & CampaignState::getHeroByType(HeroTypeID heroID) const
  261. {
  262. static const JsonNode emptyNode;
  263. if (!getReservedHeroes().count(heroID))
  264. return emptyNode;
  265. if (!globalHeroPool.count(heroID))
  266. return emptyNode;
  267. return globalHeroPool.at(heroID);
  268. }
  269. void CampaignState::setCurrentMapAsConquered(std::vector<CGHeroInstance *> heroes)
  270. {
  271. range::sort(heroes, [](const CGHeroInstance * a, const CGHeroInstance * b)
  272. {
  273. return a->getHeroStrengthForCampaign() > b->getHeroStrengthForCampaign();
  274. });
  275. logGlobal->info("Scenario %d of campaign %s (%s) has been completed", currentMap->getNum(), getFilename(), getNameTranslated());
  276. mapsConquered.push_back(*currentMap);
  277. auto reservedHeroes = getReservedHeroes();
  278. for (auto * hero : heroes)
  279. {
  280. JsonNode node = CampaignState::crossoverSerialize(hero);
  281. if (reservedHeroes.count(hero->getHeroType()))
  282. {
  283. logGlobal->info("Hero crossover: %d (%s) exported to global pool", hero->getHeroType(), hero->getNameTranslated());
  284. globalHeroPool[hero->getHeroType()] = node;
  285. }
  286. else
  287. {
  288. logGlobal->info("Hero crossover: %d (%s) exported to scenario pool", hero->getHeroType(), hero->getNameTranslated());
  289. scenarioHeroPool[*currentMap].push_back(node);
  290. }
  291. }
  292. }
  293. std::optional<CampaignBonus> CampaignState::getBonus(CampaignScenarioID which) const
  294. {
  295. auto bonuses = scenario(which).travelOptions.bonusesToChoose;
  296. assert(chosenCampaignBonuses.count(*currentMap) || bonuses.empty());
  297. if(bonuses.empty())
  298. return std::optional<CampaignBonus>();
  299. if (!getBonusID(which))
  300. return std::optional<CampaignBonus>();
  301. return bonuses[getBonusID(which).value()];
  302. }
  303. std::optional<ui8> CampaignState::getBonusID(CampaignScenarioID which) const
  304. {
  305. if (!chosenCampaignBonuses.count(which))
  306. return std::nullopt;
  307. return chosenCampaignBonuses.at(which);
  308. }
  309. std::unique_ptr<CMap> CampaignState::getMap(CampaignScenarioID scenarioId, IGameCallback * cb)
  310. {
  311. // FIXME: there is certainly better way to handle maps inside campaigns
  312. if(scenarioId == CampaignScenarioID::NONE)
  313. scenarioId = currentMap.value();
  314. CMapService mapService;
  315. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  316. boost::to_lower(scenarioName);
  317. scenarioName += ':' + std::to_string(scenarioId.getNum());
  318. const auto & mapContent = mapPieces.find(scenarioId)->second;
  319. auto result = mapService.loadMap(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding(), cb);
  320. mapTranslations[scenarioId] = result->texts;
  321. return result;
  322. }
  323. std::unique_ptr<CMapHeader> CampaignState::getMapHeader(CampaignScenarioID scenarioId) const
  324. {
  325. if(scenarioId == CampaignScenarioID::NONE)
  326. scenarioId = currentMap.value();
  327. CMapService mapService;
  328. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  329. boost::to_lower(scenarioName);
  330. scenarioName += ':' + std::to_string(scenarioId.getNum());
  331. const auto & mapContent = mapPieces.find(scenarioId)->second;
  332. return mapService.loadMapHeader(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding());
  333. }
  334. std::shared_ptr<CMapInfo> CampaignState::getMapInfo(CampaignScenarioID scenarioId) const
  335. {
  336. if(scenarioId == CampaignScenarioID::NONE)
  337. scenarioId = currentMap.value();
  338. auto mapInfo = std::make_shared<CMapInfo>();
  339. mapInfo->fileURI = getFilename();
  340. mapInfo->mapHeader = getMapHeader(scenarioId);
  341. mapInfo->countPlayers();
  342. return mapInfo;
  343. }
  344. JsonNode CampaignState::crossoverSerialize(CGHeroInstance * hero) const
  345. {
  346. JsonNode node;
  347. JsonSerializer handler(nullptr, node);
  348. hero->serializeJsonOptions(handler);
  349. return node;
  350. }
  351. CGHeroInstance * CampaignState::crossoverDeserialize(const JsonNode & node, CMap * map) const
  352. {
  353. JsonDeserializer handler(nullptr, const_cast<JsonNode&>(node));
  354. auto * hero = new CGHeroInstance(map ? map->cb : nullptr);
  355. hero->ID = Obj::HERO;
  356. hero->serializeJsonOptions(handler);
  357. if (map)
  358. {
  359. hero->serializeJsonArtifacts(handler, "artifacts");
  360. map->addNewArtifactInstance(*hero);
  361. }
  362. return hero;
  363. }
  364. void CampaignState::setCurrentMap(CampaignScenarioID which)
  365. {
  366. assert(scenario(which).isNotVoid());
  367. currentMap = which;
  368. }
  369. void CampaignState::setCurrentMapBonus(ui8 which)
  370. {
  371. chosenCampaignBonuses[*currentMap] = which;
  372. }
  373. std::optional<CampaignScenarioID> CampaignState::currentScenario() const
  374. {
  375. return currentMap;
  376. }
  377. std::optional<CampaignScenarioID> CampaignState::lastScenario() const
  378. {
  379. if (mapsConquered.empty())
  380. return std::nullopt;
  381. return mapsConquered.back();
  382. }
  383. std::set<CampaignScenarioID> CampaignState::conqueredScenarios() const
  384. {
  385. std::set<CampaignScenarioID> result;
  386. result.insert(mapsConquered.begin(), mapsConquered.end());
  387. return result;
  388. }
  389. std::set<CampaignScenarioID> Campaign::allScenarios() const
  390. {
  391. std::set<CampaignScenarioID> result;
  392. for (auto const & entry : scenarios)
  393. {
  394. if (entry.second.isNotVoid())
  395. result.insert(entry.first);
  396. }
  397. return result;
  398. }
  399. void Campaign::overrideCampaign()
  400. {
  401. const JsonNode node = JsonUtils::assembleFromFiles("config/campaignOverrides.json");
  402. for (auto & entry : node.Struct())
  403. if(filename == entry.first)
  404. {
  405. if(!entry.second["regions"].isNull() && !entry.second["scenarioCount"].isNull())
  406. loadLegacyData(CampaignRegions::fromJson(entry.second["regions"]), entry.second["scenarioCount"].Integer());
  407. if(!entry.second["loadingBackground"].isNull())
  408. loadingBackground = ImagePath::builtin(entry.second["loadingBackground"].String());
  409. if(!entry.second["videoRim"].isNull())
  410. videoRim = ImagePath::builtin(entry.second["videoRim"].String());
  411. if(!entry.second["introVideo"].isNull())
  412. introVideo = VideoPath::builtin(entry.second["introVideo"].String());
  413. if(!entry.second["outroVideo"].isNull())
  414. outroVideo = VideoPath::builtin(entry.second["outroVideo"].String());
  415. }
  416. }
  417. void Campaign::overrideCampaignScenarios()
  418. {
  419. const JsonNode node = JsonUtils::assembleFromFiles("config/campaignOverrides.json");
  420. for (auto & entry : node.Struct())
  421. if(filename == entry.first)
  422. {
  423. if(!entry.second["scenarios"].isNull())
  424. {
  425. auto sc = entry.second["scenarios"].Vector();
  426. for(int i = 0; i < sc.size(); i++)
  427. {
  428. auto it = scenarios.begin();
  429. std::advance(it, i);
  430. if(!sc.at(i)["voiceProlog"].isNull())
  431. it->second.prolog.prologVoice = AudioPath::builtin(sc.at(i)["voiceProlog"].String());
  432. if(!sc.at(i)["voiceEpilog"].isNull())
  433. it->second.epilog.prologVoice = AudioPath::builtin(sc.at(i)["voiceEpilog"].String());
  434. }
  435. }
  436. }
  437. }
  438. int Campaign::scenariosCount() const
  439. {
  440. return allScenarios().size();
  441. }
  442. const CampaignScenario & Campaign::scenario(CampaignScenarioID which) const
  443. {
  444. assert(scenarios.count(which));
  445. assert(scenarios.at(which).isNotVoid());
  446. return scenarios.at(which);
  447. }
  448. bool CampaignState::isCampaignFinished() const
  449. {
  450. return conqueredScenarios() == allScenarios();
  451. }
  452. VCMI_LIB_NAMESPACE_END