CGameStateCampaign.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. heroToPlace->instanceName = heroPlaceholder->instanceName;
  340. gameState->map->replaceObject(campaignHeroReplacement.heroPlaceholderId, heroToPlace);
  341. }
  342. }
  343. void CGameStateCampaign::transferMissingArtifacts(const CampaignTravel & travelOptions)
  344. {
  345. CGHeroInstance * receiver = nullptr;
  346. for(auto hero : gameState->map->getObjects<CGHeroInstance>())
  347. {
  348. if (!hero->getOwner().isValidPlayer())
  349. continue; // prisons
  350. if (gameState->getPlayerState(hero->getOwner())->isHuman())
  351. {
  352. receiver = hero;
  353. break;
  354. }
  355. }
  356. assert(receiver);
  357. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  358. {
  359. if (campaignHeroReplacement.heroPlaceholderId.hasValue())
  360. continue;
  361. auto donorHero = campaignHeroReplacement.hero;
  362. if (!donorHero)
  363. throw std::runtime_error("Failed to find hero to take artifacts from! Scenario: " + gameState->map->name.toString());
  364. // process in reverse - 2nd artifact from a backpack must be processed before 1st one to avoid invalidation of artifact positions
  365. for (auto const & artLocation : boost::adaptors::reverse(campaignHeroReplacement.transferrableArtifacts))
  366. {
  367. auto * artifact = donorHero->getArt(artLocation);
  368. logGlobal->debug("Removing artifact %s from slot %d of hero %s for transfer", artifact->getType()->getJsonKey(), artLocation.getNum(), donorHero->getHeroTypeName());
  369. gameState->map->removeArtifactInstance(*donorHero, artLocation);
  370. if (receiver)
  371. {
  372. logGlobal->debug("Granting artifact %s to hero %s for transfer", artifact->getType()->getJsonKey(), receiver->getHeroTypeName());
  373. const auto slot = ArtifactUtils::getArtAnyPosition(receiver, artifact->getTypeId());
  374. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  375. gameState->map->putArtifactInstance(*receiver, artifact->getId(), slot);
  376. else
  377. logGlobal->error("Cannot transfer artifact - no free slots!");
  378. }
  379. else
  380. logGlobal->error("Cannot transfer artifact - no receiver hero!");
  381. }
  382. }
  383. }
  384. void CGameStateCampaign::generateCampaignHeroesToReplace()
  385. {
  386. auto campaignState = gameState->scenarioOps->campState;
  387. std::vector<CGHeroPlaceholder *> placeholdersByPower;
  388. std::vector<CGHeroPlaceholder *> placeholdersByType;
  389. campaignHeroReplacements.clear();
  390. // find all placeholders on map
  391. for(auto heroPlaceholder : gameState->map->getObjects<CGHeroPlaceholder>())
  392. {
  393. // only 1 field must be set
  394. assert(heroPlaceholder->powerRank.has_value() != heroPlaceholder->heroType.has_value());
  395. if(heroPlaceholder->powerRank)
  396. placeholdersByPower.push_back(heroPlaceholder);
  397. if(heroPlaceholder->heroType)
  398. placeholdersByType.push_back(heroPlaceholder);
  399. }
  400. //selecting heroes by type
  401. for(const auto * placeholder : placeholdersByType)
  402. {
  403. const auto & node = campaignState->getHeroByType(*placeholder->heroType);
  404. if (node.isNull())
  405. {
  406. logGlobal->info("Hero crossover: Unable to replace placeholder for %d (%s)!", placeholder->heroType->getNum(), LIBRARY->heroTypes()->getById(*placeholder->heroType)->getNameTranslated());
  407. continue;
  408. }
  409. auto hero = campaignState->crossoverDeserialize(node, gameState->map.get());
  410. logGlobal->info("Hero crossover: Loading placeholder for %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  411. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  412. }
  413. auto lastScenario = getHeroesSourceScenario();
  414. if (lastScenario)
  415. {
  416. // sort hero placeholders descending power
  417. boost::range::sort(placeholdersByPower, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  418. {
  419. return *a->powerRank > *b->powerRank;
  420. });
  421. const auto & nodeList = campaignState->getHeroesByPower(lastScenario.value());
  422. auto nodeListIter = nodeList.begin();
  423. for(const auto * placeholder : placeholdersByPower)
  424. {
  425. if (nodeListIter == nodeList.end())
  426. break;
  427. if (!gameState->players.count(placeholder->getOwner()))
  428. continue; // illegal?
  429. // It looks like heroes placeholder by power can only be replaced for human player
  430. // Example where this is important: Spoils of War -> Greed
  431. // Meanwhile, placeholders by hero ID can be replaced for AI as well
  432. // Example: Armageddon's Blade -> To Kill A Hero
  433. if (!gameState->players.at(placeholder->getOwner()).isHuman())
  434. continue;
  435. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  436. nodeListIter++;
  437. logGlobal->info("Hero crossover: Loading placeholder as %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  438. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  439. }
  440. // Add remaining heroes without placeholders - to transfer their artifacts to placed heroes
  441. for (;nodeListIter != nodeList.end(); ++nodeListIter)
  442. {
  443. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  444. campaignHeroReplacements.emplace_back(hero, ObjectInstanceID::NONE);
  445. }
  446. }
  447. }
  448. void CGameStateCampaign::initHeroes()
  449. {
  450. auto chosenBonus = currentBonus();
  451. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->getTargetedHero() != HeroTypeID::CAMP_GENERATED.getNum()) //exclude generated heroes
  452. {
  453. //find human player
  454. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  455. for (auto & elem : gameState->players)
  456. {
  457. if(elem.second.human)
  458. {
  459. humanPlayer = elem.first;
  460. break;
  461. }
  462. }
  463. assert(humanPlayer != PlayerColor::NEUTRAL);
  464. const auto & heroes = gameState->players.at(humanPlayer).getHeroes();
  465. if (chosenBonus->getTargetedHero() == HeroTypeID::CAMP_STRONGEST.getNum()) //most powerful
  466. {
  467. int maxB = -1;
  468. for (int b=0; b<heroes.size(); ++b)
  469. {
  470. if(maxB == -1 || CGHeroInstance::compareCampaignValue(heroes[b], heroes[maxB]))
  471. {
  472. maxB = b;
  473. }
  474. }
  475. if(maxB < 0)
  476. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  477. else
  478. giveCampaignBonusToHero(heroes[maxB]);
  479. }
  480. else //specific hero
  481. {
  482. for (auto & hero : heroes)
  483. {
  484. if (hero->getHeroTypeID().getNum() == chosenBonus->getTargetedHero())
  485. {
  486. giveCampaignBonusToHero(hero);
  487. break;
  488. }
  489. }
  490. }
  491. }
  492. auto campaignState = gameState->scenarioOps->campState;
  493. if (campaignState->getYogWizardID().hasValue() && boost::starts_with(campaignState->getFilename(), "DATA/YOG") && campaignState->currentScenario()->getNum() == 2)
  494. {
  495. auto * yog = gameState->getUsedHero(campaignState->getYogWizardID());
  496. assert(yog);
  497. assert(yog->isCampaignYog());
  498. gameState->giveHeroArtifact(yog, ArtifactID::ANGELIC_ALLIANCE);
  499. }
  500. transferMissingArtifacts(campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  501. }
  502. void CGameStateCampaign::initStartingResources()
  503. {
  504. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  505. {
  506. std::vector<const PlayerSettings *> ret;
  507. for(const auto & playerInfo : gameState->scenarioOps->playerInfos)
  508. {
  509. if(playerInfo.second.isControlledByHuman())
  510. ret.push_back(&playerInfo.second);
  511. }
  512. return ret;
  513. };
  514. const auto & chosenBonus = currentBonus();
  515. if(chosenBonus && chosenBonus->getType() == CampaignBonusType::RESOURCE)
  516. {
  517. const auto & bonusValue = chosenBonus->getValue<CampaignBonusStartingResources>();
  518. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  519. for(const PlayerSettings *ps : people)
  520. {
  521. std::vector<GameResID> res; //resources we will give
  522. switch (bonusValue.resource.toEnum())
  523. {
  524. case EGameResID::COMMON: //wood+ore
  525. res.push_back(GameResID(EGameResID::WOOD));
  526. res.push_back(GameResID(EGameResID::ORE));
  527. break;
  528. case EGameResID::RARE: //rare
  529. res.push_back(GameResID(EGameResID::MERCURY));
  530. res.push_back(GameResID(EGameResID::SULFUR));
  531. res.push_back(GameResID(EGameResID::CRYSTAL));
  532. res.push_back(GameResID(EGameResID::GEMS));
  533. break;
  534. default:
  535. res.push_back(bonusValue.resource);
  536. break;
  537. }
  538. for (auto & re : res)
  539. gameState->players.at(ps->color).resources[re] += bonusValue.amount;
  540. }
  541. }
  542. }
  543. void CGameStateCampaign::initTowns()
  544. {
  545. auto chosenBonus = currentBonus();
  546. if (!chosenBonus)
  547. return;
  548. if (chosenBonus->getType() != CampaignBonusType::BUILDING)
  549. return;
  550. const auto & bonusValue = chosenBonus->getValue<CampaignBonusBuilding>();
  551. for (const auto & townID : gameState->map->getAllTowns())
  552. {
  553. auto town = gameState->getTown(townID);
  554. PlayerState * owner = gameState->getPlayerState(town->getOwner());
  555. if (!owner)
  556. continue;
  557. PlayerInfo & pi = gameState->map->players[owner->color.getNum()];
  558. if (!owner->human)
  559. continue;
  560. if (town->anchorPos() != pi.posOfMainTown)
  561. continue;
  562. BuildingID newBuilding = bonusValue.buildingDecoded;
  563. if (bonusValue.buildingH3M.hasValue())
  564. {
  565. auto mapping = LIBRARY->mapFormat->getMapping(gameState->scenarioOps->campState->getFormat());
  566. newBuilding = mapping.remapBuilding(town->getFactionID(), bonusValue.buildingH3M);
  567. }
  568. // Build granted building & all prerequisites - e.g. Mages Guild Lvl 3 should also give Mages Guild Lvl 1 & 2
  569. while(true)
  570. {
  571. if (newBuilding == BuildingID::NONE)
  572. break;
  573. if(town->hasBuilt(newBuilding))
  574. break;
  575. town->addBuilding(newBuilding);
  576. const auto & building = town->getTown()->buildings.at(newBuilding);
  577. newBuilding = building->upgrade;
  578. }
  579. break;
  580. }
  581. }
  582. bool CGameStateCampaign::playerHasStartingHero(PlayerColor playerColor) const
  583. {
  584. auto campaignBonus = currentBonus();
  585. if (!campaignBonus)
  586. return false;
  587. if(campaignBonus->getType() == CampaignBonusType::HERO && playerColor == PlayerColor(campaignBonus->getValue<CampaignBonusStartingHero>().startingPlayer))
  588. return true;
  589. return false;
  590. }
  591. std::unique_ptr<CMap> CGameStateCampaign::getCurrentMap()
  592. {
  593. return gameState->scenarioOps->campState->getMap(CampaignScenarioID::NONE, gameState);
  594. }
  595. VCMI_LIB_NAMESPACE_END