CampaignState.cpp 16 KB

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