CampaignState.cpp 15 KB

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