CGameStateCampaign.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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 "../mapping/CMapEditManager.h"
  16. #include "../mapObjects/CGHeroInstance.h"
  17. #include "../registerTypes/RegisterTypes.h"
  18. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  19. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  20. #include "../StartInfo.h"
  21. #include "../CBuildingHandler.h"
  22. #include "../CHeroHandler.h"
  23. #include "../mapping/CMap.h"
  24. #include "../ArtifactUtils.h"
  25. #include "../CPlayerState.h"
  26. #include "../serializer/CMemorySerializer.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. void CrossoverHeroesList::addHeroToBothLists(CGHeroInstance * hero)
  29. {
  30. heroesFromPreviousScenario.push_back(hero);
  31. heroesFromAnyPreviousScenarios.push_back(hero);
  32. }
  33. void CrossoverHeroesList::removeHeroFromBothLists(CGHeroInstance * hero)
  34. {
  35. heroesFromPreviousScenario -= hero;
  36. heroesFromAnyPreviousScenarios -= hero;
  37. }
  38. CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, const ObjectInstanceID & heroPlaceholderId):
  39. hero(hero),
  40. heroPlaceholderId(heroPlaceholderId)
  41. {
  42. }
  43. CGameStateCampaign::CGameStateCampaign(CGameState * owner):
  44. gameState(owner)
  45. {
  46. assert(gameState->scenarioOps->mode == StartInfo::CAMPAIGN);
  47. assert(gameState->scenarioOps->campState != nullptr);
  48. }
  49. std::optional<CampaignBonus> CGameStateCampaign::currentBonus() const
  50. {
  51. auto campaignState = gameState->scenarioOps->campState;
  52. return campaignState->getBonus(*campaignState->currentScenario());
  53. }
  54. CrossoverHeroesList CGameStateCampaign::getCrossoverHeroesFromPreviousScenarios() const
  55. {
  56. CrossoverHeroesList crossoverHeroes;
  57. auto campaignState = gameState->scenarioOps->campState;
  58. auto bonus = currentBonus();
  59. if(bonus && bonus->type == CampaignBonusType::HEROES_FROM_PREVIOUS_SCENARIO)
  60. {
  61. auto scenarioID = static_cast<CampaignScenarioID>(bonus->info2);
  62. std::vector<CGHeroInstance *> heroes;
  63. for(auto & node : campaignState->getCrossoverHeroes(scenarioID))
  64. {
  65. auto * h = CampaignState::crossoverDeserialize(node);
  66. heroes.push_back(h);
  67. }
  68. crossoverHeroes.heroesFromAnyPreviousScenarios = heroes;
  69. crossoverHeroes.heroesFromPreviousScenario = heroes;
  70. return crossoverHeroes;
  71. }
  72. if(!campaignState->lastScenario())
  73. return crossoverHeroes;
  74. for(auto mapNr : campaignState->conqueredScenarios())
  75. {
  76. // create a list of deleted heroes
  77. auto lostCrossoverHeroes = campaignState->getLostCrossoverHeroes(mapNr);
  78. // remove heroes which didn't reached the end of the scenario, but were available at the start
  79. for(auto * hero : lostCrossoverHeroes)
  80. {
  81. // auto hero = CCampaignState::crossoverDeserialize(node);
  82. vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  83. {
  84. return hero->subID == h->subID;
  85. });
  86. }
  87. // now add heroes which completed the scenario
  88. for(auto node : campaignState->getCrossoverHeroes(mapNr))
  89. {
  90. auto * hero = CampaignState::crossoverDeserialize(node);
  91. // add new heroes and replace old heroes with newer ones
  92. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  93. {
  94. return hero->subID == h->subID;
  95. });
  96. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  97. {
  98. // replace old hero with newer one
  99. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  100. }
  101. else
  102. {
  103. // add new hero
  104. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  105. }
  106. if(mapNr == campaignState->lastScenario())
  107. {
  108. crossoverHeroes.heroesFromPreviousScenario.push_back(hero);
  109. }
  110. }
  111. }
  112. return crossoverHeroes;
  113. }
  114. void CGameStateCampaign::trimCrossoverHeroesParameters(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CampaignTravel & travelOptions)
  115. {
  116. // create heroes list for convenience iterating
  117. std::vector<CGHeroInstance *> crossoverHeroes;
  118. crossoverHeroes.reserve(campaignHeroReplacements.size());
  119. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  120. {
  121. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  122. }
  123. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  124. if(!travelOptions.whatHeroKeeps.experience)
  125. {
  126. //trimming experience
  127. for(CGHeroInstance * cgh : crossoverHeroes)
  128. {
  129. cgh->initExp(gameState->getRandomGenerator());
  130. }
  131. }
  132. if(!travelOptions.whatHeroKeeps.primarySkills)
  133. {
  134. //trimming prim skills
  135. for(CGHeroInstance * cgh : crossoverHeroes)
  136. {
  137. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  138. {
  139. auto sel = Selector::type()(BonusType::PRIMARY_SKILL)
  140. .And(Selector::subtype()(g))
  141. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  142. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  143. }
  144. }
  145. }
  146. if(!travelOptions.whatHeroKeeps.secondarySkills)
  147. {
  148. //trimming sec skills
  149. for(CGHeroInstance * cgh : crossoverHeroes)
  150. {
  151. cgh->secSkills = cgh->type->secSkillsInit;
  152. cgh->recreateSecondarySkillsBonuses();
  153. }
  154. }
  155. if(!travelOptions.whatHeroKeeps.spells)
  156. {
  157. for(CGHeroInstance * cgh : crossoverHeroes)
  158. {
  159. cgh->removeSpellbook();
  160. }
  161. }
  162. if(!travelOptions.whatHeroKeeps.artifacts)
  163. {
  164. //trimming artifacts
  165. for(CGHeroInstance * hero : crossoverHeroes)
  166. {
  167. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  168. for (size_t i = 0; i < totalArts; i++ )
  169. {
  170. auto artifactPosition = ArtifactPosition((si32)i);
  171. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  172. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  173. if(!info)
  174. continue;
  175. // TODO: why would there be nullptr artifacts?
  176. const CArtifactInstance *art = info->artifact;
  177. if(!art)
  178. continue;
  179. bool takeable = travelOptions.artifactsKeptByHero.count(art->artType->getId());
  180. ArtifactLocation al(hero, artifactPosition);
  181. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  182. al.removeArtifact();
  183. }
  184. }
  185. }
  186. //trimming creatures
  187. for(CGHeroInstance * cgh : crossoverHeroes)
  188. {
  189. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  190. {
  191. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  192. return !travelOptions.monstersKeptByHero.count(crid);
  193. };
  194. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  195. for(auto &slotPair : stacksCopy)
  196. if(shouldSlotBeErased(slotPair))
  197. cgh->eraseStack(slotPair.first);
  198. }
  199. // Removing short-term bonuses
  200. for(CGHeroInstance * cgh : crossoverHeroes)
  201. {
  202. cgh->removeBonusesRecursive(CSelector(Bonus::OneDay)
  203. .Or(CSelector(Bonus::OneWeek))
  204. .Or(CSelector(Bonus::NTurns))
  205. .Or(CSelector(Bonus::NDays))
  206. .Or(CSelector(Bonus::OneBattle)));
  207. }
  208. }
  209. void CGameStateCampaign::placeCampaignHeroes()
  210. {
  211. // WARNING: CURRENT CODE IS LIKELY INCORRECT AND LEADS TO MULTIPLE ISSUES WITH HERO TRANSFER
  212. // Approximate behavior according to testing H3 game logic.
  213. // 1) definitions:
  214. // - 'reserved heroes' are heroes that have fixed placeholder in unfinished maps. See CMapHeader::reservedCampaignHeroes
  215. // - 'campaign pool' are serialized heroes and is unique to a campaign
  216. // - 'scenario pool' are serialized heroes and is unique to a scenario
  217. //
  218. // 2) scenario end logic:
  219. // - at end of scenario, all 'reserved heroes' of a player go to 'campaign pool'
  220. // - at end of scenario, rest of player's heroes go to 'scenario pool'
  221. //
  222. // 3) scenario start logic
  223. // - at scenario start, all heroes that are placed on map but already exist in 'campaign pool' and are still 'reserved heroes' are replaced with other, randomly selected heroes (and probably marked as unavailable in map)
  224. // - at scenario start, all fixed placeholders are replaced with heroes from 'campaign pool', if exist
  225. // - at scenario start, all power placeholders owned by player are replaced by heroes from 'scenario pool' of last complete map, if exist
  226. // - exception: if starting bonus is 'select player' then power placeholders are taken from 'scenario pool' of linked map
  227. // place bonus hero
  228. auto campaignState = gameState->scenarioOps->campState;
  229. auto campaignBonus = campaignState->getBonus(*campaignState->currentScenario());
  230. bool campaignGiveHero = campaignBonus && campaignBonus->type == CampaignBonusType::HERO;
  231. if(campaignGiveHero)
  232. {
  233. auto playerColor = PlayerColor(campaignBonus->info1);
  234. auto it = gameState->scenarioOps->playerInfos.find(playerColor);
  235. if(it != gameState->scenarioOps->playerInfos.end())
  236. {
  237. auto heroTypeId = campaignBonus->info2;
  238. if(heroTypeId == 0xffff) // random bonus hero
  239. {
  240. heroTypeId = gameState->pickUnusedHeroTypeRandomly(playerColor);
  241. }
  242. gameState->placeStartingHero(playerColor, HeroTypeID(heroTypeId), gameState->map->players[playerColor.getNum()].posOfMainTown);
  243. }
  244. }
  245. // replace heroes placeholders
  246. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  247. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  248. {
  249. logGlobal->debug("\tGenerate list of hero placeholders");
  250. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  251. logGlobal->debug("\tPrepare crossover heroes");
  252. trimCrossoverHeroesParameters(campaignHeroReplacements, campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  253. // remove same heroes on the map which will be added through crossover heroes
  254. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  255. // with the same hero type id
  256. std::vector<CGHeroInstance *> removedHeroes;
  257. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  258. {
  259. auto * hero = gameState->getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  260. if(hero)
  261. {
  262. removedHeroes.push_back(hero);
  263. gameState->map->heroesOnMap -= hero;
  264. gameState->map->objects[hero->id.getNum()] = nullptr;
  265. gameState->map->removeBlockVisTiles(hero, true);
  266. }
  267. }
  268. logGlobal->debug("\tReplace placeholders with heroes");
  269. replaceHeroesPlaceholders(campaignHeroReplacements);
  270. // now add removed heroes again with unused type ID
  271. for(auto * hero : removedHeroes)
  272. {
  273. si32 heroTypeId = 0;
  274. if(hero->ID == Obj::HERO)
  275. {
  276. heroTypeId = gameState->pickUnusedHeroTypeRandomly(hero->tempOwner);
  277. }
  278. else if(hero->ID == Obj::PRISON)
  279. {
  280. auto unusedHeroTypeIds = gameState->getUnusedAllowedHeroes();
  281. if(!unusedHeroTypeIds.empty())
  282. {
  283. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, gameState->getRandomGenerator())).getNum();
  284. }
  285. else
  286. {
  287. logGlobal->error("No free hero type ID found to replace prison.");
  288. assert(0);
  289. }
  290. }
  291. else
  292. {
  293. assert(0); // should not happen
  294. }
  295. hero->subID = heroTypeId;
  296. hero->portrait = hero->subID;
  297. gameState->map->getEditManager()->insertObject(hero);
  298. }
  299. }
  300. }
  301. void CGameStateCampaign::giveCampaignBonusToHero(CGHeroInstance * hero)
  302. {
  303. auto curBonus = currentBonus();
  304. if(!curBonus)
  305. return;
  306. assert(curBonus->isBonusForHero());
  307. //apply bonus
  308. switch(curBonus->type)
  309. {
  310. case CampaignBonusType::SPELL:
  311. {
  312. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  313. break;
  314. }
  315. case CampaignBonusType::MONSTER:
  316. {
  317. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  318. {
  319. if(hero->slotEmpty(SlotID(i)))
  320. {
  321. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  322. break;
  323. }
  324. }
  325. break;
  326. }
  327. case CampaignBonusType::ARTIFACT:
  328. {
  329. if(!gameState->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2)))
  330. logGlobal->error("Cannot give starting artifact - no free slots!");
  331. break;
  332. }
  333. case CampaignBonusType::SPELL_SCROLL:
  334. {
  335. CArtifactInstance * scroll = ArtifactUtils::createScroll(SpellID(curBonus->info2));
  336. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  337. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  338. scroll->putAt(ArtifactLocation(hero, slot));
  339. else
  340. logGlobal->error("Cannot give starting scroll - no free slots!");
  341. break;
  342. }
  343. case CampaignBonusType::PRIMARY_SKILL:
  344. {
  345. const ui8 * ptr = reinterpret_cast<const ui8 *>(&curBonus->info2);
  346. for(int g = 0; g < GameConstants::PRIMARY_SKILLS; ++g)
  347. {
  348. int val = ptr[g];
  349. if(val == 0)
  350. {
  351. continue;
  352. }
  353. auto bb = std::make_shared<Bonus>(
  354. BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, static_cast<int>(*gameState->scenarioOps->campState->currentScenario()), g
  355. );
  356. hero->addNewBonus(bb);
  357. }
  358. break;
  359. }
  360. case CampaignBonusType::SECONDARY_SKILL:
  361. {
  362. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  363. break;
  364. }
  365. }
  366. }
  367. void CGameStateCampaign::replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements)
  368. {
  369. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  370. {
  371. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(gameState->getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  372. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  373. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  374. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  375. heroToPlace->pos = heroPlaceholder->pos;
  376. heroToPlace->type = VLC->heroh->objects[heroToPlace->subID];
  377. heroToPlace->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO,
  378. heroToPlace->type->heroClass->getIndex())->getTemplates().front();
  379. for(auto &&i : heroToPlace->stacks)
  380. i.second->type = VLC->creh->objects[i.second->getCreatureID()];
  381. auto fixArtifact = [&](CArtifactInstance * art)
  382. {
  383. art->artType = VLC->arth->objects[art->artType->getId()];
  384. gameState->map->artInstances.emplace_back(art);
  385. art->id = ArtifactInstanceID((si32)gameState->map->artInstances.size() - 1);
  386. };
  387. for(auto &&i : heroToPlace->artifactsWorn)
  388. fixArtifact(i.second.artifact);
  389. for(auto &&i : heroToPlace->artifactsInBackpack)
  390. fixArtifact(i.artifact);
  391. gameState->map->removeBlockVisTiles(heroPlaceholder, true);
  392. gameState->map->objects[heroPlaceholder->id.getNum()] = nullptr;
  393. gameState->map->instanceNames.erase(heroPlaceholder->instanceName);
  394. gameState->map->heroesOnMap.emplace_back(heroToPlace);
  395. gameState->map->objects[heroToPlace->id.getNum()] = heroToPlace;
  396. gameState->map->addBlockVisTiles(heroToPlace);
  397. gameState->map->instanceNames[heroToPlace->instanceName] = heroToPlace;
  398. delete heroPlaceholder;
  399. }
  400. }
  401. std::vector<CampaignHeroReplacement> CGameStateCampaign::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  402. {
  403. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  404. //selecting heroes by type
  405. for(auto obj : gameState->map->objects)
  406. {
  407. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  408. {
  409. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  410. if(heroPlaceholder->subID != 0xFF) //select by type
  411. {
  412. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  413. {
  414. return hero->subID == heroPlaceholder->subID;
  415. });
  416. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  417. {
  418. auto * hero = *it;
  419. crossoverHeroes.removeHeroFromBothLists(hero);
  420. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  421. }
  422. }
  423. }
  424. }
  425. //selecting heroes by power
  426. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  427. {
  428. return a->getHeroStrength() > b->getHeroStrength();
  429. }); //sort, descending strength
  430. // sort hero placeholders descending power
  431. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  432. for(auto obj : gameState->map->objects)
  433. {
  434. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  435. {
  436. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  437. if(heroPlaceholder->subID == 0xFF) //select by power
  438. {
  439. heroPlaceholders.push_back(heroPlaceholder);
  440. }
  441. }
  442. }
  443. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  444. {
  445. return a->power > b->power;
  446. });
  447. for(int i = 0; i < heroPlaceholders.size(); ++i)
  448. {
  449. auto * heroPlaceholder = heroPlaceholders[i];
  450. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  451. {
  452. auto * hero = crossoverHeroes.heroesFromPreviousScenario[i];
  453. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  454. }
  455. }
  456. return campaignHeroReplacements;
  457. }
  458. void CGameStateCampaign::initHeroes()
  459. {
  460. auto chosenBonus = currentBonus();
  461. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  462. {
  463. //find human player
  464. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  465. for (auto & elem : gameState->players)
  466. {
  467. if(elem.second.human)
  468. {
  469. humanPlayer = elem.first;
  470. break;
  471. }
  472. }
  473. assert(humanPlayer != PlayerColor::NEUTRAL);
  474. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = gameState->players[humanPlayer].heroes;
  475. if (chosenBonus->info1 == 0xFFFD) //most powerful
  476. {
  477. int maxB = -1;
  478. for (int b=0; b<heroes.size(); ++b)
  479. {
  480. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  481. {
  482. maxB = b;
  483. }
  484. }
  485. if(maxB < 0)
  486. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  487. else
  488. giveCampaignBonusToHero(heroes[maxB]);
  489. }
  490. else //specific hero
  491. {
  492. for (auto & heroe : heroes)
  493. {
  494. if (heroe->subID == chosenBonus->info1)
  495. {
  496. giveCampaignBonusToHero(heroe);
  497. break;
  498. }
  499. }
  500. }
  501. }
  502. }
  503. void CGameStateCampaign::initStartingResources()
  504. {
  505. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  506. {
  507. std::vector<const PlayerSettings *> ret;
  508. for(const auto & playerInfo : gameState->scenarioOps->playerInfos)
  509. {
  510. if(playerInfo.second.isControlledByHuman())
  511. ret.push_back(&playerInfo.second);
  512. }
  513. return ret;
  514. };
  515. auto chosenBonus = currentBonus();
  516. if(chosenBonus && chosenBonus->type == CampaignBonusType::RESOURCE)
  517. {
  518. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  519. for(const PlayerSettings *ps : people)
  520. {
  521. std::vector<int> res; //resources we will give
  522. switch (chosenBonus->info1)
  523. {
  524. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  525. res.push_back(chosenBonus->info1);
  526. break;
  527. case 0xFD: //wood+ore
  528. res.push_back(GameResID(EGameResID::WOOD));
  529. res.push_back(GameResID(EGameResID::ORE));
  530. break;
  531. case 0xFE: //rare
  532. res.push_back(GameResID(EGameResID::MERCURY));
  533. res.push_back(GameResID(EGameResID::SULFUR));
  534. res.push_back(GameResID(EGameResID::CRYSTAL));
  535. res.push_back(GameResID(EGameResID::GEMS));
  536. break;
  537. default:
  538. assert(0);
  539. break;
  540. }
  541. //increasing resource quantity
  542. for (auto & re : res)
  543. {
  544. gameState->players[ps->color].resources[re] += chosenBonus->info2;
  545. }
  546. }
  547. }
  548. }
  549. void CGameStateCampaign::initTowns()
  550. {
  551. auto chosenBonus = currentBonus();
  552. if (chosenBonus && chosenBonus->type == CampaignBonusType::BUILDING)
  553. {
  554. for (int g=0; g<gameState->map->towns.size(); ++g)
  555. {
  556. PlayerState * owner = gameState->getPlayerState(gameState->map->towns[g]->getOwner());
  557. if (owner)
  558. {
  559. PlayerInfo & pi = gameState->map->players[owner->color.getNum()];
  560. if (owner->human && //human-owned
  561. gameState->map->towns[g]->pos == pi.posOfMainTown)
  562. {
  563. BuildingID buildingId;
  564. if(gameState->scenarioOps->campState->formatVCMI())
  565. buildingId = BuildingID(chosenBonus->info1);
  566. else
  567. buildingId = CBuildingHandler::campToERMU(chosenBonus->info1, gameState->map->towns[g]->subID, gameState->map->towns[g]->builtBuildings);
  568. gameState->map->towns[g]->builtBuildings.insert(buildingId);
  569. break;
  570. }
  571. }
  572. }
  573. }
  574. }
  575. bool CGameStateCampaign::playerHasStartingHero(PlayerColor playerColor) const
  576. {
  577. auto campaignBonus = currentBonus();
  578. if (!campaignBonus)
  579. return false;
  580. if(campaignBonus->type == CampaignBonusType::HERO && playerColor == PlayerColor(campaignBonus->info1))
  581. return true;
  582. return false;
  583. }
  584. std::unique_ptr<CMap> CGameStateCampaign::getCurrentMap() const
  585. {
  586. return gameState->scenarioOps->campState->getMap(CampaignScenarioID::NONE);
  587. }
  588. VCMI_LIB_NAMESPACE_END