CGameStateCampaign.cpp 22 KB

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