CGameStateCampaign.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /*
  2. * CGameStateCampaign.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 "CGameStateCampaign.h"
  12. #include "CGameState.h"
  13. #include "QuestInfo.h"
  14. #include "../campaign/CampaignState.h"
  15. #include "../entities/building/CBuilding.h"
  16. #include "../entities/building/CBuildingHandler.h"
  17. #include "../entities/hero/CHeroClass.h"
  18. #include "../entities/hero/CHero.h"
  19. #include "../mapping/CMapEditManager.h"
  20. #include "../mapObjects/CGHeroInstance.h"
  21. #include "../mapObjects/CGTownInstance.h"
  22. #include "../networkPacks/ArtifactLocation.h"
  23. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  24. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  25. #include "../StartInfo.h"
  26. #include "../mapping/CMap.h"
  27. #include "../ArtifactUtils.h"
  28. #include "../CPlayerState.h"
  29. #include <vstd/RNG.h>
  30. #include <vcmi/HeroTypeService.h>
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, const ObjectInstanceID & heroPlaceholderId):
  33. hero(hero),
  34. heroPlaceholderId(heroPlaceholderId)
  35. {
  36. }
  37. CGameStateCampaign::CGameStateCampaign(CGameState * owner):
  38. gameState(owner)
  39. {
  40. assert(gameState->scenarioOps->mode == EStartMode::CAMPAIGN);
  41. assert(gameState->scenarioOps->campState != nullptr);
  42. }
  43. std::optional<CampaignBonus> CGameStateCampaign::currentBonus() const
  44. {
  45. auto campaignState = gameState->scenarioOps->campState;
  46. return campaignState->getBonus(*campaignState->currentScenario());
  47. }
  48. std::optional<CampaignScenarioID> CGameStateCampaign::getHeroesSourceScenario() const
  49. {
  50. auto campaignState = gameState->scenarioOps->campState;
  51. auto bonus = currentBonus();
  52. if(bonus && bonus->type == CampaignBonusType::HEROES_FROM_PREVIOUS_SCENARIO)
  53. return static_cast<CampaignScenarioID>(bonus->info2);
  54. return campaignState->lastScenario();
  55. }
  56. void CGameStateCampaign::trimCrossoverHeroesParameters(const CampaignTravel & travelOptions)
  57. {
  58. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  59. if(!travelOptions.whatHeroKeeps.experience)
  60. {
  61. //trimming experience
  62. for(auto & hero : campaignHeroReplacements)
  63. {
  64. hero.hero->initExp(gameState->getRandomGenerator());
  65. }
  66. }
  67. if(!travelOptions.whatHeroKeeps.primarySkills)
  68. {
  69. //trimming prim skills
  70. for(auto & hero : campaignHeroReplacements)
  71. {
  72. for(auto skill : PrimarySkill::ALL_SKILLS())
  73. {
  74. auto sel = Selector::type()(BonusType::PRIMARY_SKILL)
  75. .And(Selector::subtype()(BonusSubtypeID(skill)))
  76. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  77. hero.hero->getLocalBonus(sel)->val = hero.hero->getHeroClass()->primarySkillInitial[skill.getNum()];
  78. }
  79. }
  80. }
  81. if(!travelOptions.whatHeroKeeps.secondarySkills)
  82. {
  83. //trimming sec skills
  84. for(auto & hero : campaignHeroReplacements)
  85. {
  86. hero.hero->secSkills = hero.hero->getHeroType()->secSkillsInit;
  87. hero.hero->recreateSecondarySkillsBonuses();
  88. }
  89. }
  90. if(!travelOptions.whatHeroKeeps.spells)
  91. {
  92. for(auto & hero : campaignHeroReplacements)
  93. {
  94. hero.hero->removeSpellbook();
  95. }
  96. }
  97. if(!travelOptions.whatHeroKeeps.artifacts)
  98. {
  99. //trimming artifacts
  100. for(auto & hero : campaignHeroReplacements)
  101. {
  102. const auto & checkAndRemoveArtifact = [&](const ArtifactPosition & artifactPosition) -> bool
  103. {
  104. if(artifactPosition == ArtifactPosition::SPELLBOOK)
  105. return false; // do not handle spellbook this way
  106. const ArtSlotInfo *info = hero.hero->getSlot(artifactPosition);
  107. if(!info)
  108. return false;
  109. // FIXME: double-check how H3 handles case of transferring components of a combined artifact if entire combined artifact is not transferrable
  110. // For example, what happens if hero has assembled Angelic Alliance, AA is not marked is transferrable, but Sandals can be transferred? Should artifact be disassembled?
  111. if (info->locked)
  112. return false;
  113. // TODO: why would there be nullptr artifacts?
  114. const CArtifactInstance *art = info->artifact;
  115. if(!art)
  116. return false;
  117. ArtifactLocation al(hero.hero->id, artifactPosition);
  118. bool takeable = travelOptions.artifactsKeptByHero.count(art->getTypeId());
  119. bool locked = hero.hero->getSlot(al.slot)->locked;
  120. if (!locked && takeable)
  121. {
  122. logGlobal->debug("Artifact %s from slot %d of hero %s will be transferred to next scenario", art->getType()->getJsonKey(), al.slot.getNum(), hero.hero->getHeroTypeName());
  123. hero.transferrableArtifacts.push_back(artifactPosition);
  124. }
  125. if (!locked && !takeable)
  126. {
  127. logGlobal->debug("Removing artifact %s from slot %d of hero %s", art->getType()->getJsonKey(), al.slot.getNum(), hero.hero->getHeroTypeName());
  128. gameState->map->removeArtifactInstance(*hero.hero, al.slot);
  129. return true;
  130. }
  131. return false;
  132. };
  133. // process on copy - removal of artifact will invalidate container
  134. auto artifactsWorn = hero.hero->artifactsWorn;
  135. for(const auto & art : artifactsWorn)
  136. checkAndRemoveArtifact(art.first);
  137. for (int slotNumber = 0; slotNumber < hero.hero->artifactsInBackpack.size();)
  138. {
  139. if (checkAndRemoveArtifact(ArtifactPosition::BACKPACK_START + slotNumber))
  140. continue; // artifact was removed and backpack slots were shifted -> test this slot again
  141. else
  142. slotNumber++; // artifact was kept for transfer -> test next slot
  143. };
  144. }
  145. }
  146. //trimming creatures
  147. for(auto & hero : campaignHeroReplacements)
  148. {
  149. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  150. {
  151. CreatureID crid = j.second->getCreatureID();
  152. return !travelOptions.monstersKeptByHero.count(crid);
  153. };
  154. auto stacksCopy = hero.hero->stacks; //copy of the map, so we can iterate iover it and remove stacks
  155. for(auto &slotPair : stacksCopy)
  156. if(shouldSlotBeErased(slotPair))
  157. hero.hero->eraseStack(slotPair.first);
  158. }
  159. // Removing short-term bonuses
  160. for(auto & hero : campaignHeroReplacements)
  161. {
  162. hero.hero->removeBonusesRecursive(CSelector(Bonus::OneDay)
  163. .Or(CSelector(Bonus::OneWeek))
  164. .Or(CSelector(Bonus::NTurns))
  165. .Or(CSelector(Bonus::NDays))
  166. .Or(CSelector(Bonus::OneBattle)));
  167. }
  168. }
  169. void CGameStateCampaign::placeCampaignHeroes()
  170. {
  171. // place bonus hero
  172. auto campaignState = gameState->scenarioOps->campState;
  173. auto campaignBonus = campaignState->getBonus(*campaignState->currentScenario());
  174. bool campaignGiveHero = campaignBonus && campaignBonus->type == CampaignBonusType::HERO;
  175. if(campaignGiveHero)
  176. {
  177. auto playerColor = PlayerColor(campaignBonus->info1);
  178. auto it = gameState->scenarioOps->playerInfos.find(playerColor);
  179. if(it != gameState->scenarioOps->playerInfos.end())
  180. {
  181. HeroTypeID heroTypeId = HeroTypeID(campaignBonus->info2);
  182. if(heroTypeId.getNum() == HeroTypeID::CAMP_RANDOM) // random bonus hero
  183. {
  184. heroTypeId = gameState->pickUnusedHeroTypeRandomly(playerColor);
  185. }
  186. gameState->placeStartingHero(playerColor, HeroTypeID(heroTypeId), gameState->map->players[playerColor.getNum()].posOfMainTown);
  187. }
  188. }
  189. logGlobal->debug("\tGenerate list of hero placeholders");
  190. generateCampaignHeroesToReplace();
  191. logGlobal->debug("\tPrepare crossover heroes");
  192. trimCrossoverHeroesParameters(campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  193. // remove same heroes on the map which will be added through crossover heroes
  194. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  195. // with the same hero type id
  196. std::vector<CGHeroInstance *> removedHeroes;
  197. std::set<HeroTypeID> reservedHeroes = campaignState->getReservedHeroes();
  198. std::set<HeroTypeID> heroesToRemove;
  199. for (auto const & heroID : reservedHeroes )
  200. {
  201. // Do not replace reserved heroes initially, e.g. in 1st campaign scenario in which they appear
  202. if (!campaignState->getHeroByType(heroID).isNull())
  203. heroesToRemove.insert(heroID);
  204. }
  205. for(auto & replacement : campaignHeroReplacements)
  206. if (replacement.heroPlaceholderId.hasValue())
  207. heroesToRemove.insert(replacement.hero->getHeroTypeID());
  208. for(auto & heroID : heroesToRemove)
  209. {
  210. auto * hero = gameState->getUsedHero(heroID);
  211. if(hero)
  212. {
  213. removedHeroes.push_back(hero);
  214. gameState->map->heroesOnMap -= hero;
  215. gameState->map->objects[hero->id.getNum()] = nullptr;
  216. gameState->map->removeBlockVisTiles(hero, true);
  217. }
  218. }
  219. logGlobal->debug("\tReplace placeholders with heroes");
  220. replaceHeroesPlaceholders();
  221. // now add removed heroes again with unused type ID
  222. for(auto * hero : removedHeroes)
  223. {
  224. HeroTypeID heroTypeId;
  225. if(hero->ID == Obj::HERO)
  226. {
  227. heroTypeId = gameState->pickUnusedHeroTypeRandomly(hero->tempOwner);
  228. }
  229. else if(hero->ID == Obj::PRISON)
  230. {
  231. auto unusedHeroTypeIds = gameState->getUnusedAllowedHeroes();
  232. if(!unusedHeroTypeIds.empty())
  233. {
  234. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, gameState->getRandomGenerator()));
  235. }
  236. else
  237. {
  238. logGlobal->error("No free hero type ID found to replace prison.");
  239. assert(0);
  240. }
  241. }
  242. else
  243. {
  244. assert(0); // should not happen
  245. }
  246. hero->setHeroType(heroTypeId);
  247. gameState->map->getEditManager()->insertObject(hero);
  248. }
  249. }
  250. void CGameStateCampaign::giveCampaignBonusToHero(CGHeroInstance * hero)
  251. {
  252. auto curBonus = currentBonus();
  253. if(!curBonus)
  254. return;
  255. assert(curBonus->isBonusForHero());
  256. //apply bonus
  257. switch(curBonus->type)
  258. {
  259. case CampaignBonusType::SPELL:
  260. {
  261. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  262. break;
  263. }
  264. case CampaignBonusType::MONSTER:
  265. {
  266. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  267. {
  268. if(hero->slotEmpty(SlotID(i)))
  269. {
  270. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  271. break;
  272. }
  273. }
  274. break;
  275. }
  276. case CampaignBonusType::ARTIFACT:
  277. {
  278. if(!gameState->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2)))
  279. logGlobal->error("Cannot give starting artifact - no free slots!");
  280. break;
  281. }
  282. case CampaignBonusType::SPELL_SCROLL:
  283. {
  284. const auto scroll = gameState->createScroll(SpellID(curBonus->info2));
  285. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  286. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  287. gameState->map->putArtifactInstance(*hero, scroll->getId(), slot);
  288. else
  289. logGlobal->error("Cannot give starting scroll - no free slots!");
  290. break;
  291. }
  292. case CampaignBonusType::PRIMARY_SKILL:
  293. {
  294. const ui8 * ptr = reinterpret_cast<const ui8 *>(&curBonus->info2);
  295. for(auto skill : PrimarySkill::ALL_SKILLS())
  296. {
  297. int val = ptr[skill.getNum()];
  298. if(val == 0)
  299. continue;
  300. auto currentScenario = *gameState->scenarioOps->campState->currentScenario();
  301. auto bb = std::make_shared<Bonus>( BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, BonusSourceID(currentScenario), BonusSubtypeID(skill) );
  302. hero->addNewBonus(bb);
  303. }
  304. break;
  305. }
  306. case CampaignBonusType::SECONDARY_SKILL:
  307. {
  308. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  309. break;
  310. }
  311. }
  312. }
  313. void CGameStateCampaign::replaceHeroesPlaceholders()
  314. {
  315. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  316. {
  317. if (!campaignHeroReplacement.heroPlaceholderId.hasValue())
  318. continue;
  319. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(gameState->getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  320. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  321. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  322. if(heroPlaceholder->tempOwner.isValidPlayer())
  323. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  324. heroToPlace->setAnchorPos(heroPlaceholder->anchorPos());
  325. heroToPlace->setHeroType(heroToPlace->getHeroTypeID());
  326. heroToPlace->appearance = heroToPlace->getObjectHandler()->getTemplates().front();
  327. gameState->map->removeBlockVisTiles(heroPlaceholder, true);
  328. gameState->map->objects[heroPlaceholder->id.getNum()] = nullptr;
  329. gameState->map->instanceNames.erase(heroPlaceholder->instanceName);
  330. gameState->map->heroesOnMap.emplace_back(heroToPlace);
  331. gameState->map->objects[heroToPlace->id.getNum()] = heroToPlace;
  332. gameState->map->addBlockVisTiles(heroToPlace);
  333. gameState->map->instanceNames[heroToPlace->instanceName] = heroToPlace;
  334. delete heroPlaceholder;
  335. }
  336. }
  337. void CGameStateCampaign::transferMissingArtifacts(const CampaignTravel & travelOptions)
  338. {
  339. CGHeroInstance * receiver = nullptr;
  340. for(auto obj : gameState->map->objects)
  341. {
  342. if (!obj)
  343. continue;
  344. if (obj->ID != Obj::HERO)
  345. continue;
  346. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  347. if (gameState->getPlayerState(hero->getOwner())->isHuman())
  348. {
  349. receiver = hero;
  350. break;
  351. }
  352. }
  353. assert(receiver);
  354. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  355. {
  356. if (campaignHeroReplacement.heroPlaceholderId.hasValue())
  357. continue;
  358. auto * donorHero = campaignHeroReplacement.hero;
  359. if (!donorHero)
  360. throw std::runtime_error("Failed to find hero to take artifacts from! Scenario: " + gameState->map->name.toString());
  361. // process in reverse - 2nd artifact from a backpack must be processed before 1st one to avoid invalidation of artifact positions
  362. for (auto const & artLocation : boost::adaptors::reverse(campaignHeroReplacement.transferrableArtifacts))
  363. {
  364. auto * artifact = donorHero->getArt(artLocation);
  365. logGlobal->debug("Removing artifact %s from slot %d of hero %s for transfer", artifact->getType()->getJsonKey(), artLocation.getNum(), donorHero->getHeroTypeName());
  366. gameState->map->removeArtifactInstance(*donorHero, artLocation);
  367. if (receiver)
  368. {
  369. logGlobal->debug("Granting artifact %s to hero %s for transfer", artifact->getType()->getJsonKey(), receiver->getHeroTypeName());
  370. const auto slot = ArtifactUtils::getArtAnyPosition(receiver, artifact->getTypeId());
  371. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  372. gameState->map->putArtifactInstance(*receiver, artifact->getId(), slot);
  373. else
  374. logGlobal->error("Cannot transfer artifact - no free slots!");
  375. }
  376. else
  377. logGlobal->error("Cannot transfer artifact - no receiver hero!");
  378. }
  379. delete donorHero;
  380. }
  381. }
  382. void CGameStateCampaign::generateCampaignHeroesToReplace()
  383. {
  384. auto campaignState = gameState->scenarioOps->campState;
  385. std::vector<CGHeroPlaceholder *> placeholdersByPower;
  386. std::vector<CGHeroPlaceholder *> placeholdersByType;
  387. campaignHeroReplacements.clear();
  388. // find all placeholders on map
  389. for(auto obj : gameState->map->objects)
  390. {
  391. if(!obj)
  392. continue;
  393. if (obj->ID != Obj::HERO_PLACEHOLDER)
  394. continue;
  395. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  396. // only 1 field must be set
  397. assert(heroPlaceholder->powerRank.has_value() != heroPlaceholder->heroType.has_value());
  398. if(heroPlaceholder->powerRank)
  399. placeholdersByPower.push_back(heroPlaceholder);
  400. if(heroPlaceholder->heroType)
  401. placeholdersByType.push_back(heroPlaceholder);
  402. }
  403. //selecting heroes by type
  404. for(const auto * placeholder : placeholdersByType)
  405. {
  406. const auto & node = campaignState->getHeroByType(*placeholder->heroType);
  407. if (node.isNull())
  408. {
  409. logGlobal->info("Hero crossover: Unable to replace placeholder for %d (%s)!", placeholder->heroType->getNum(), LIBRARY->heroTypes()->getById(*placeholder->heroType)->getNameTranslated());
  410. continue;
  411. }
  412. CGHeroInstance * hero = campaignState->crossoverDeserialize(node, gameState->map.get());
  413. logGlobal->info("Hero crossover: Loading placeholder for %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  414. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  415. }
  416. auto lastScenario = getHeroesSourceScenario();
  417. if (lastScenario)
  418. {
  419. // sort hero placeholders descending power
  420. boost::range::sort(placeholdersByPower, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  421. {
  422. return *a->powerRank > *b->powerRank;
  423. });
  424. const auto & nodeList = campaignState->getHeroesByPower(lastScenario.value());
  425. auto nodeListIter = nodeList.begin();
  426. for(const auto * placeholder : placeholdersByPower)
  427. {
  428. if (nodeListIter == nodeList.end())
  429. break;
  430. CGHeroInstance * hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  431. nodeListIter++;
  432. logGlobal->info("Hero crossover: Loading placeholder as %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  433. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  434. }
  435. // Add remaining heroes without placeholders - to transfer their artifacts to placed heroes
  436. for (;nodeListIter != nodeList.end(); ++nodeListIter)
  437. {
  438. CGHeroInstance * hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  439. campaignHeroReplacements.emplace_back(hero, ObjectInstanceID::NONE);
  440. }
  441. }
  442. }
  443. void CGameStateCampaign::initHeroes()
  444. {
  445. auto chosenBonus = currentBonus();
  446. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != HeroTypeID::CAMP_GENERATED) //exclude generated heroes
  447. {
  448. //find human player
  449. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  450. for (auto & elem : gameState->players)
  451. {
  452. if(elem.second.human)
  453. {
  454. humanPlayer = elem.first;
  455. break;
  456. }
  457. }
  458. assert(humanPlayer != PlayerColor::NEUTRAL);
  459. const auto & heroes = gameState->players[humanPlayer].getHeroes();
  460. if (chosenBonus->info1 == HeroTypeID::CAMP_STRONGEST) //most powerful
  461. {
  462. int maxB = -1;
  463. for (int b=0; b<heroes.size(); ++b)
  464. {
  465. if (maxB == -1 || heroes[b]->getValueForCampaign() > heroes[maxB]->getValueForCampaign())
  466. {
  467. maxB = b;
  468. }
  469. }
  470. if(maxB < 0)
  471. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  472. else
  473. giveCampaignBonusToHero(heroes[maxB]);
  474. }
  475. else //specific hero
  476. {
  477. for (auto & hero : heroes)
  478. {
  479. if (hero->getHeroTypeID().getNum() == chosenBonus->info1)
  480. {
  481. giveCampaignBonusToHero(hero);
  482. break;
  483. }
  484. }
  485. }
  486. }
  487. auto campaignState = gameState->scenarioOps->campState;
  488. auto * yog = gameState->getUsedHero(HeroTypeID::SOLMYR);
  489. if (yog && boost::starts_with(campaignState->getFilename(), "DATA/YOG") && campaignState->currentScenario()->getNum() == 2)
  490. {
  491. assert(yog->isCampaignYog());
  492. gameState->giveHeroArtifact(yog, ArtifactID::ANGELIC_ALLIANCE);
  493. }
  494. transferMissingArtifacts(campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  495. }
  496. void CGameStateCampaign::initStartingResources()
  497. {
  498. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  499. {
  500. std::vector<const PlayerSettings *> ret;
  501. for(const auto & playerInfo : gameState->scenarioOps->playerInfos)
  502. {
  503. if(playerInfo.second.isControlledByHuman())
  504. ret.push_back(&playerInfo.second);
  505. }
  506. return ret;
  507. };
  508. auto chosenBonus = currentBonus();
  509. if(chosenBonus && chosenBonus->type == CampaignBonusType::RESOURCE)
  510. {
  511. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  512. for(const PlayerSettings *ps : people)
  513. {
  514. std::vector<GameResID> res; //resources we will give
  515. switch (chosenBonus->info1)
  516. {
  517. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  518. res.push_back(chosenBonus->info1);
  519. break;
  520. case EGameResID::COMMON: //wood+ore
  521. res.push_back(GameResID(EGameResID::WOOD));
  522. res.push_back(GameResID(EGameResID::ORE));
  523. break;
  524. case EGameResID::RARE: //rare
  525. res.push_back(GameResID(EGameResID::MERCURY));
  526. res.push_back(GameResID(EGameResID::SULFUR));
  527. res.push_back(GameResID(EGameResID::CRYSTAL));
  528. res.push_back(GameResID(EGameResID::GEMS));
  529. break;
  530. default:
  531. assert(0);
  532. break;
  533. }
  534. //increasing resource quantity
  535. for (auto & re : res)
  536. {
  537. gameState->players[ps->color].resources[re] += chosenBonus->info2;
  538. }
  539. }
  540. }
  541. }
  542. void CGameStateCampaign::initTowns()
  543. {
  544. auto chosenBonus = currentBonus();
  545. if (!chosenBonus)
  546. return;
  547. if (chosenBonus->type != CampaignBonusType::BUILDING)
  548. return;
  549. for (int g=0; g<gameState->map->towns.size(); ++g)
  550. {
  551. CGTownInstance * town = gameState->map->towns[g];
  552. PlayerState * owner = gameState->getPlayerState(town->getOwner());
  553. if (!owner)
  554. continue;
  555. PlayerInfo & pi = gameState->map->players[owner->color.getNum()];
  556. if (!owner->human)
  557. continue;
  558. if (town->anchorPos() != pi.posOfMainTown)
  559. continue;
  560. BuildingID newBuilding;
  561. if(gameState->scenarioOps->campState->formatVCMI())
  562. newBuilding = BuildingID(chosenBonus->info1);
  563. else
  564. newBuilding = CBuildingHandler::campToERMU(chosenBonus->info1, town->getFactionID(), town->getBuildings());
  565. // Build granted building & all prerequisites - e.g. Mages Guild Lvl 3 should also give Mages Guild Lvl 1 & 2
  566. while(true)
  567. {
  568. if (newBuilding == BuildingID::NONE)
  569. break;
  570. if(town->hasBuilt(newBuilding))
  571. break;
  572. town->addBuilding(newBuilding);
  573. const auto & building = town->getTown()->buildings.at(newBuilding);
  574. newBuilding = building->upgrade;
  575. }
  576. break;
  577. }
  578. }
  579. bool CGameStateCampaign::playerHasStartingHero(PlayerColor playerColor) const
  580. {
  581. auto campaignBonus = currentBonus();
  582. if (!campaignBonus)
  583. return false;
  584. if(campaignBonus->type == CampaignBonusType::HERO && playerColor == PlayerColor(campaignBonus->info1))
  585. return true;
  586. return false;
  587. }
  588. std::unique_ptr<CMap> CGameStateCampaign::getCurrentMap()
  589. {
  590. return gameState->scenarioOps->campState->getMap(CampaignScenarioID::NONE, gameState->callback);
  591. }
  592. VCMI_LIB_NAMESPACE_END