CGameStateCampaign.cpp 21 KB

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