CGameStateCampaign.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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. // Removing short-term bonuses
  169. for(auto & hero : campaignHeroReplacements)
  170. {
  171. hero.hero->removeBonusesRecursive(CSelector(Bonus::OneDay)
  172. .Or(CSelector(Bonus::OneWeek))
  173. .Or(CSelector(Bonus::NTurns))
  174. .Or(CSelector(Bonus::NDays))
  175. .Or(CSelector(Bonus::OneBattle)));
  176. }
  177. }
  178. void CGameStateCampaign::placeCampaignHeroes(vstd::RNG & randomGenerator)
  179. {
  180. // place bonus hero
  181. const auto & campaignState = gameState->scenarioOps->campState;
  182. const auto & campaignBonus = campaignState->getBonus(*campaignState->currentScenario());
  183. bool campaignGiveHero = campaignBonus && campaignBonus->getType() == CampaignBonusType::HERO;
  184. if(campaignGiveHero)
  185. {
  186. const auto & campaignBonusValue = campaignBonus->getValue<CampaignBonusStartingHero>();
  187. const auto & playerColor = campaignBonusValue.startingPlayer;
  188. const auto & it = gameState->scenarioOps->playerInfos.find(playerColor);
  189. if(it != gameState->scenarioOps->playerInfos.end())
  190. {
  191. HeroTypeID heroTypeId = campaignBonusValue.hero;
  192. if(heroTypeId == HeroTypeID::CAMP_RANDOM) // random bonus hero
  193. {
  194. heroTypeId = gameState->pickUnusedHeroTypeRandomly(randomGenerator, playerColor);
  195. }
  196. gameState->placeStartingHero(playerColor, HeroTypeID(heroTypeId), gameState->map->players[playerColor.getNum()].posOfMainTown);
  197. }
  198. }
  199. logGlobal->debug("\tGenerate list of hero placeholders");
  200. generateCampaignHeroesToReplace();
  201. logGlobal->debug("\tPrepare crossover heroes");
  202. trimCrossoverHeroesParameters(randomGenerator, campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  203. // remove same heroes on the map which will be added through crossover heroes
  204. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  205. // with the same hero type id
  206. std::vector<std::shared_ptr<CGObjectInstance>> removedHeroes;
  207. std::set<HeroTypeID> reservedHeroes = campaignState->getReservedHeroes();
  208. std::set<HeroTypeID> heroesToRemove;
  209. for (auto const & heroID : reservedHeroes )
  210. {
  211. // Do not replace reserved heroes initially, e.g. in 1st campaign scenario in which they appear
  212. if (!campaignState->getHeroByType(heroID).isNull())
  213. heroesToRemove.insert(heroID);
  214. }
  215. for(auto & replacement : campaignHeroReplacements)
  216. if (replacement.heroPlaceholderId.hasValue())
  217. heroesToRemove.insert(replacement.hero->getHeroTypeID());
  218. for(auto & heroID : heroesToRemove)
  219. {
  220. auto * hero = gameState->getUsedHero(heroID);
  221. if(hero)
  222. {
  223. removedHeroes.push_back(gameState->map->eraseObject(hero->id));
  224. }
  225. }
  226. logGlobal->debug("\tReplace placeholders with heroes");
  227. replaceHeroesPlaceholders();
  228. // now add removed heroes again with unused type ID
  229. for(auto object : removedHeroes)
  230. {
  231. auto hero = dynamic_cast<CGHeroInstance*>(object.get());
  232. HeroTypeID heroTypeId;
  233. if(hero->ID == Obj::HERO)
  234. {
  235. heroTypeId = gameState->pickUnusedHeroTypeRandomly(randomGenerator, hero->tempOwner);
  236. }
  237. else if(hero->ID == Obj::PRISON)
  238. {
  239. auto unusedHeroTypeIds = gameState->getUnusedAllowedHeroes();
  240. if(!unusedHeroTypeIds.empty())
  241. {
  242. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, randomGenerator));
  243. }
  244. else
  245. {
  246. logGlobal->error("No free hero type ID found to replace prison.");
  247. assert(0);
  248. }
  249. }
  250. else
  251. {
  252. assert(0); // should not happen
  253. }
  254. hero->setHeroType(heroTypeId);
  255. gameState->map->getEditManager()->insertObject(object);
  256. }
  257. }
  258. void CGameStateCampaign::giveCampaignBonusToHero(CGHeroInstance * hero)
  259. {
  260. auto curBonus = currentBonus();
  261. if(!curBonus)
  262. return;
  263. assert(curBonus->isBonusForHero());
  264. //apply bonus
  265. switch(curBonus->getType())
  266. {
  267. case CampaignBonusType::SPELL:
  268. {
  269. const auto & bonusValue = curBonus->getValue<CampaignBonusSpell>();
  270. hero->addSpellToSpellbook(bonusValue.spell);
  271. break;
  272. }
  273. case CampaignBonusType::MONSTER:
  274. {
  275. const auto & bonusValue = curBonus->getValue<CampaignBonusCreatures>();
  276. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  277. {
  278. if(hero->slotEmpty(SlotID(i)))
  279. {
  280. hero->addToSlot(SlotID(i), bonusValue.creature, bonusValue.amount);
  281. break;
  282. }
  283. }
  284. break;
  285. }
  286. case CampaignBonusType::ARTIFACT:
  287. {
  288. const auto & bonusValue = curBonus->getValue<CampaignBonusArtifact>();
  289. if(!gameState->giveHeroArtifact(hero, bonusValue.artifact))
  290. logGlobal->error("Cannot give starting artifact - no free slots!");
  291. break;
  292. }
  293. case CampaignBonusType::SPELL_SCROLL:
  294. {
  295. const auto & bonusValue = curBonus->getValue<CampaignBonusSpellScroll>();
  296. const auto scroll = gameState->createScroll(bonusValue.spell);
  297. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  298. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  299. gameState->map->putArtifactInstance(*hero, scroll->getId(), slot);
  300. else
  301. logGlobal->error("Cannot give starting scroll - no free slots!");
  302. break;
  303. }
  304. case CampaignBonusType::PRIMARY_SKILL:
  305. {
  306. const auto & bonusValue = curBonus->getValue<CampaignBonusPrimarySkill>();
  307. for(auto skill : PrimarySkill::ALL_SKILLS())
  308. {
  309. int val = bonusValue.amounts[skill.getNum()];
  310. if(val == 0)
  311. continue;
  312. auto currentScenario = *gameState->scenarioOps->campState->currentScenario();
  313. auto bb = std::make_shared<Bonus>( BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, BonusSourceID(currentScenario), BonusSubtypeID(skill) );
  314. hero->addNewBonus(bb);
  315. }
  316. break;
  317. }
  318. case CampaignBonusType::SECONDARY_SKILL:
  319. {
  320. const auto & bonusValue = curBonus->getValue<CampaignBonusSecondarySkill>();
  321. hero->setSecSkillLevel(bonusValue.skill, bonusValue.mastery, ChangeValueMode::ABSOLUTE);
  322. break;
  323. }
  324. }
  325. }
  326. void CGameStateCampaign::replaceHeroesPlaceholders()
  327. {
  328. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  329. {
  330. if (!campaignHeroReplacement.heroPlaceholderId.hasValue())
  331. continue;
  332. auto heroPlaceholder = gameState->map->getObject(campaignHeroReplacement.heroPlaceholderId);
  333. auto heroToPlace = campaignHeroReplacement.hero;
  334. if(heroPlaceholder->tempOwner.isValidPlayer())
  335. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  336. heroToPlace->setAnchorPos(heroPlaceholder->anchorPos());
  337. heroToPlace->setHeroType(heroToPlace->getHeroTypeID());
  338. heroToPlace->appearance = heroToPlace->getObjectHandler()->getTemplates().front();
  339. gameState->map->replaceObject(campaignHeroReplacement.heroPlaceholderId, heroToPlace);
  340. }
  341. }
  342. void CGameStateCampaign::transferMissingArtifacts(const CampaignTravel & travelOptions)
  343. {
  344. CGHeroInstance * receiver = nullptr;
  345. for(auto hero : gameState->map->getObjects<CGHeroInstance>())
  346. {
  347. if (!hero->getOwner().isValidPlayer())
  348. continue; // prisons
  349. if (gameState->getPlayerState(hero->getOwner())->isHuman())
  350. {
  351. receiver = hero;
  352. break;
  353. }
  354. }
  355. assert(receiver);
  356. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  357. {
  358. if (campaignHeroReplacement.heroPlaceholderId.hasValue())
  359. continue;
  360. auto donorHero = campaignHeroReplacement.hero;
  361. if (!donorHero)
  362. throw std::runtime_error("Failed to find hero to take artifacts from! Scenario: " + gameState->map->name.toString());
  363. // process in reverse - 2nd artifact from a backpack must be processed before 1st one to avoid invalidation of artifact positions
  364. for (auto const & artLocation : boost::adaptors::reverse(campaignHeroReplacement.transferrableArtifacts))
  365. {
  366. auto * artifact = donorHero->getArt(artLocation);
  367. logGlobal->debug("Removing artifact %s from slot %d of hero %s for transfer", artifact->getType()->getJsonKey(), artLocation.getNum(), donorHero->getHeroTypeName());
  368. gameState->map->removeArtifactInstance(*donorHero, artLocation);
  369. if (receiver)
  370. {
  371. logGlobal->debug("Granting artifact %s to hero %s for transfer", artifact->getType()->getJsonKey(), receiver->getHeroTypeName());
  372. const auto slot = ArtifactUtils::getArtAnyPosition(receiver, artifact->getTypeId());
  373. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  374. gameState->map->putArtifactInstance(*receiver, artifact->getId(), slot);
  375. else
  376. logGlobal->error("Cannot transfer artifact - no free slots!");
  377. }
  378. else
  379. logGlobal->error("Cannot transfer artifact - no receiver hero!");
  380. }
  381. }
  382. }
  383. void CGameStateCampaign::generateCampaignHeroesToReplace()
  384. {
  385. auto campaignState = gameState->scenarioOps->campState;
  386. std::vector<CGHeroPlaceholder *> placeholdersByPower;
  387. std::vector<CGHeroPlaceholder *> placeholdersByType;
  388. campaignHeroReplacements.clear();
  389. // find all placeholders on map
  390. for(auto heroPlaceholder : gameState->map->getObjects<CGHeroPlaceholder>())
  391. {
  392. // only 1 field must be set
  393. assert(heroPlaceholder->powerRank.has_value() != heroPlaceholder->heroType.has_value());
  394. if(heroPlaceholder->powerRank)
  395. placeholdersByPower.push_back(heroPlaceholder);
  396. if(heroPlaceholder->heroType)
  397. placeholdersByType.push_back(heroPlaceholder);
  398. }
  399. //selecting heroes by type
  400. for(const auto * placeholder : placeholdersByType)
  401. {
  402. const auto & node = campaignState->getHeroByType(*placeholder->heroType);
  403. if (node.isNull())
  404. {
  405. logGlobal->info("Hero crossover: Unable to replace placeholder for %d (%s)!", placeholder->heroType->getNum(), LIBRARY->heroTypes()->getById(*placeholder->heroType)->getNameTranslated());
  406. continue;
  407. }
  408. auto hero = campaignState->crossoverDeserialize(node, gameState->map.get());
  409. logGlobal->info("Hero crossover: Loading placeholder for %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  410. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  411. }
  412. auto lastScenario = getHeroesSourceScenario();
  413. if (lastScenario)
  414. {
  415. // sort hero placeholders descending power
  416. boost::range::sort(placeholdersByPower, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  417. {
  418. return *a->powerRank > *b->powerRank;
  419. });
  420. const auto & nodeList = campaignState->getHeroesByPower(lastScenario.value());
  421. auto nodeListIter = nodeList.begin();
  422. for(const auto * placeholder : placeholdersByPower)
  423. {
  424. if (nodeListIter == nodeList.end())
  425. break;
  426. if (!gameState->players.count(placeholder->getOwner()))
  427. continue; // illegal?
  428. // It looks like heroes placeholder by power can only be replaced for human player
  429. // Example where this is important: Spoils of War -> Greed
  430. // Meanwhile, placeholders by hero ID can be replaced for AI as well
  431. // Example: Armageddon's Blade -> To Kill A Hero
  432. if (!gameState->players.at(placeholder->getOwner()).isHuman())
  433. continue;
  434. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  435. nodeListIter++;
  436. logGlobal->info("Hero crossover: Loading placeholder as %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  437. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  438. }
  439. // Add remaining heroes without placeholders - to transfer their artifacts to placed heroes
  440. for (;nodeListIter != nodeList.end(); ++nodeListIter)
  441. {
  442. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  443. campaignHeroReplacements.emplace_back(hero, ObjectInstanceID::NONE);
  444. }
  445. }
  446. }
  447. void CGameStateCampaign::initHeroes()
  448. {
  449. auto chosenBonus = currentBonus();
  450. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->getTargetedHero() != HeroTypeID::CAMP_GENERATED.getNum()) //exclude generated heroes
  451. {
  452. //find human player
  453. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  454. for (auto & elem : gameState->players)
  455. {
  456. if(elem.second.human)
  457. {
  458. humanPlayer = elem.first;
  459. break;
  460. }
  461. }
  462. assert(humanPlayer != PlayerColor::NEUTRAL);
  463. const auto & heroes = gameState->players.at(humanPlayer).getHeroes();
  464. if (chosenBonus->getTargetedHero() == HeroTypeID::CAMP_STRONGEST.getNum()) //most powerful
  465. {
  466. int maxB = -1;
  467. for (int b=0; b<heroes.size(); ++b)
  468. {
  469. if(maxB == -1 || CGHeroInstance::compareCampaignValue(heroes[b], heroes[maxB]))
  470. {
  471. maxB = b;
  472. }
  473. }
  474. if(maxB < 0)
  475. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  476. else
  477. giveCampaignBonusToHero(heroes[maxB]);
  478. }
  479. else //specific hero
  480. {
  481. for (auto & hero : heroes)
  482. {
  483. if (hero->getHeroTypeID().getNum() == chosenBonus->getTargetedHero())
  484. {
  485. giveCampaignBonusToHero(hero);
  486. break;
  487. }
  488. }
  489. }
  490. }
  491. auto campaignState = gameState->scenarioOps->campState;
  492. if (campaignState->getYogWizardID().hasValue() && boost::starts_with(campaignState->getFilename(), "DATA/YOG") && campaignState->currentScenario()->getNum() == 2)
  493. {
  494. auto * yog = gameState->getUsedHero(campaignState->getYogWizardID());
  495. assert(yog);
  496. assert(yog->isCampaignYog());
  497. gameState->giveHeroArtifact(yog, ArtifactID::ANGELIC_ALLIANCE);
  498. }
  499. transferMissingArtifacts(campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  500. }
  501. void CGameStateCampaign::initStartingResources()
  502. {
  503. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  504. {
  505. std::vector<const PlayerSettings *> ret;
  506. for(const auto & playerInfo : gameState->scenarioOps->playerInfos)
  507. {
  508. if(playerInfo.second.isControlledByHuman())
  509. ret.push_back(&playerInfo.second);
  510. }
  511. return ret;
  512. };
  513. const auto & chosenBonus = currentBonus();
  514. if(chosenBonus && chosenBonus->getType() == CampaignBonusType::RESOURCE)
  515. {
  516. const auto & bonusValue = chosenBonus->getValue<CampaignBonusStartingResources>();
  517. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  518. for(const PlayerSettings *ps : people)
  519. {
  520. std::vector<GameResID> res; //resources we will give
  521. switch (bonusValue.resource.toEnum())
  522. {
  523. case EGameResID::COMMON: //wood+ore
  524. res.push_back(GameResID(EGameResID::WOOD));
  525. res.push_back(GameResID(EGameResID::ORE));
  526. break;
  527. case EGameResID::RARE: //rare
  528. res.push_back(GameResID(EGameResID::MERCURY));
  529. res.push_back(GameResID(EGameResID::SULFUR));
  530. res.push_back(GameResID(EGameResID::CRYSTAL));
  531. res.push_back(GameResID(EGameResID::GEMS));
  532. break;
  533. default:
  534. res.push_back(bonusValue.resource);
  535. break;
  536. }
  537. for (auto & re : res)
  538. gameState->players.at(ps->color).resources[re] += bonusValue.amount;
  539. }
  540. }
  541. }
  542. void CGameStateCampaign::initTowns()
  543. {
  544. auto chosenBonus = currentBonus();
  545. if (!chosenBonus)
  546. return;
  547. if (chosenBonus->getType() != CampaignBonusType::BUILDING)
  548. return;
  549. const auto & bonusValue = chosenBonus->getValue<CampaignBonusBuilding>();
  550. for (const auto & townID : gameState->map->getAllTowns())
  551. {
  552. auto town = gameState->getTown(townID);
  553. PlayerState * owner = gameState->getPlayerState(town->getOwner());
  554. if (!owner)
  555. continue;
  556. PlayerInfo & pi = gameState->map->players[owner->color.getNum()];
  557. if (!owner->human)
  558. continue;
  559. if (town->anchorPos() != pi.posOfMainTown)
  560. continue;
  561. BuildingID newBuilding = bonusValue.buildingDecoded;
  562. if (bonusValue.buildingH3M.hasValue())
  563. {
  564. auto mapping = LIBRARY->mapFormat->getMapping(gameState->scenarioOps->campState->getFormat());
  565. newBuilding = mapping.remapBuilding(town->getFactionID(), bonusValue.buildingH3M);
  566. }
  567. // Build granted building & all prerequisites - e.g. Mages Guild Lvl 3 should also give Mages Guild Lvl 1 & 2
  568. while(true)
  569. {
  570. if (newBuilding == BuildingID::NONE)
  571. break;
  572. if(town->hasBuilt(newBuilding))
  573. break;
  574. town->addBuilding(newBuilding);
  575. const auto & building = town->getTown()->buildings.at(newBuilding);
  576. newBuilding = building->upgrade;
  577. }
  578. break;
  579. }
  580. }
  581. bool CGameStateCampaign::playerHasStartingHero(PlayerColor playerColor) const
  582. {
  583. auto campaignBonus = currentBonus();
  584. if (!campaignBonus)
  585. return false;
  586. if(campaignBonus->getType() == CampaignBonusType::HERO && playerColor == PlayerColor(campaignBonus->getValue<CampaignBonusStartingHero>().startingPlayer))
  587. return true;
  588. return false;
  589. }
  590. std::unique_ptr<CMap> CGameStateCampaign::getCurrentMap()
  591. {
  592. return gameState->scenarioOps->campState->getMap(CampaignScenarioID::NONE, gameState);
  593. }
  594. VCMI_LIB_NAMESPACE_END