CGameStateCampaign.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, const ObjectInstanceID & heroPlaceholderId):
  29. hero(hero),
  30. heroPlaceholderId(heroPlaceholderId)
  31. {
  32. }
  33. CGameStateCampaign::CGameStateCampaign(CGameState * owner):
  34. gameState(owner)
  35. {
  36. assert(gameState->scenarioOps->mode == StartInfo::CAMPAIGN);
  37. assert(gameState->scenarioOps->campState != nullptr);
  38. }
  39. std::optional<CampaignBonus> CGameStateCampaign::currentBonus() const
  40. {
  41. auto campaignState = gameState->scenarioOps->campState;
  42. return campaignState->getBonus(*campaignState->currentScenario());
  43. }
  44. std::optional<CampaignScenarioID> CGameStateCampaign::getHeroesSourceScenario() const
  45. {
  46. auto campaignState = gameState->scenarioOps->campState;
  47. auto bonus = currentBonus();
  48. if(bonus && bonus->type == CampaignBonusType::HEROES_FROM_PREVIOUS_SCENARIO)
  49. return static_cast<CampaignScenarioID>(bonus->info2);;
  50. return campaignState->lastScenario();
  51. }
  52. void CGameStateCampaign::trimCrossoverHeroesParameters(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CampaignTravel & travelOptions)
  53. {
  54. // create heroes list for convenience iterating
  55. std::vector<CGHeroInstance *> crossoverHeroes;
  56. crossoverHeroes.reserve(campaignHeroReplacements.size());
  57. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  58. {
  59. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  60. }
  61. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  62. if(!travelOptions.whatHeroKeeps.experience)
  63. {
  64. //trimming experience
  65. for(CGHeroInstance * cgh : crossoverHeroes)
  66. {
  67. cgh->initExp(gameState->getRandomGenerator());
  68. }
  69. }
  70. if(!travelOptions.whatHeroKeeps.primarySkills)
  71. {
  72. //trimming prim skills
  73. for(CGHeroInstance * cgh : crossoverHeroes)
  74. {
  75. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  76. {
  77. auto sel = Selector::type()(BonusType::PRIMARY_SKILL)
  78. .And(Selector::subtype()(g))
  79. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  80. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  81. }
  82. }
  83. }
  84. if(!travelOptions.whatHeroKeeps.secondarySkills)
  85. {
  86. //trimming sec skills
  87. for(CGHeroInstance * cgh : crossoverHeroes)
  88. {
  89. cgh->secSkills = cgh->type->secSkillsInit;
  90. cgh->recreateSecondarySkillsBonuses();
  91. }
  92. }
  93. if(!travelOptions.whatHeroKeeps.spells)
  94. {
  95. for(CGHeroInstance * cgh : crossoverHeroes)
  96. {
  97. cgh->removeSpellbook();
  98. }
  99. }
  100. if(!travelOptions.whatHeroKeeps.artifacts)
  101. {
  102. //trimming artifacts
  103. for(CGHeroInstance * hero : crossoverHeroes)
  104. {
  105. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  106. for (size_t i = 0; i < totalArts; i++ )
  107. {
  108. auto artifactPosition = ArtifactPosition((si32)i);
  109. if(artifactPosition == ArtifactPosition::SPELLBOOK)
  110. continue; // do not handle spellbook this way
  111. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  112. if(!info)
  113. continue;
  114. // TODO: why would there be nullptr artifacts?
  115. const CArtifactInstance *art = info->artifact;
  116. if(!art)
  117. continue;
  118. bool takeable = travelOptions.artifactsKeptByHero.count(art->artType->getId());
  119. ArtifactLocation al(hero, artifactPosition);
  120. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  121. al.removeArtifact();
  122. }
  123. }
  124. }
  125. //trimming creatures
  126. for(CGHeroInstance * cgh : crossoverHeroes)
  127. {
  128. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  129. {
  130. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  131. return !travelOptions.monstersKeptByHero.count(crid);
  132. };
  133. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  134. for(auto &slotPair : stacksCopy)
  135. if(shouldSlotBeErased(slotPair))
  136. cgh->eraseStack(slotPair.first);
  137. }
  138. // Removing short-term bonuses
  139. for(CGHeroInstance * cgh : crossoverHeroes)
  140. {
  141. cgh->removeBonusesRecursive(CSelector(Bonus::OneDay)
  142. .Or(CSelector(Bonus::OneWeek))
  143. .Or(CSelector(Bonus::NTurns))
  144. .Or(CSelector(Bonus::NDays))
  145. .Or(CSelector(Bonus::OneBattle)));
  146. }
  147. }
  148. void CGameStateCampaign::placeCampaignHeroes()
  149. {
  150. // place bonus hero
  151. auto campaignState = gameState->scenarioOps->campState;
  152. auto campaignBonus = campaignState->getBonus(*campaignState->currentScenario());
  153. bool campaignGiveHero = campaignBonus && campaignBonus->type == CampaignBonusType::HERO;
  154. if(campaignGiveHero)
  155. {
  156. auto playerColor = PlayerColor(campaignBonus->info1);
  157. auto it = gameState->scenarioOps->playerInfos.find(playerColor);
  158. if(it != gameState->scenarioOps->playerInfos.end())
  159. {
  160. auto heroTypeId = campaignBonus->info2;
  161. if(heroTypeId == 0xffff) // random bonus hero
  162. {
  163. heroTypeId = gameState->pickUnusedHeroTypeRandomly(playerColor);
  164. }
  165. gameState->placeStartingHero(playerColor, HeroTypeID(heroTypeId), gameState->map->players[playerColor.getNum()].posOfMainTown);
  166. }
  167. }
  168. logGlobal->debug("\tGenerate list of hero placeholders");
  169. auto campaignHeroReplacements = generateCampaignHeroesToReplace();
  170. logGlobal->debug("\tPrepare crossover heroes");
  171. trimCrossoverHeroesParameters(campaignHeroReplacements, campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  172. // remove same heroes on the map which will be added through crossover heroes
  173. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  174. // with the same hero type id
  175. std::vector<CGHeroInstance *> removedHeroes;
  176. std::set<HeroTypeID> heroesToRemove = campaignState->getReservedHeroes();
  177. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  178. heroesToRemove.insert(HeroTypeID(campaignHeroReplacement.hero->subID));
  179. for(auto & heroID : heroesToRemove)
  180. {
  181. auto * hero = gameState->getUsedHero(heroID);
  182. if(hero)
  183. {
  184. removedHeroes.push_back(hero);
  185. gameState->map->heroesOnMap -= hero;
  186. gameState->map->objects[hero->id.getNum()] = nullptr;
  187. gameState->map->removeBlockVisTiles(hero, true);
  188. }
  189. }
  190. logGlobal->debug("\tReplace placeholders with heroes");
  191. replaceHeroesPlaceholders(campaignHeroReplacements);
  192. // now add removed heroes again with unused type ID
  193. for(auto * hero : removedHeroes)
  194. {
  195. si32 heroTypeId = 0;
  196. if(hero->ID == Obj::HERO)
  197. {
  198. heroTypeId = gameState->pickUnusedHeroTypeRandomly(hero->tempOwner);
  199. }
  200. else if(hero->ID == Obj::PRISON)
  201. {
  202. auto unusedHeroTypeIds = gameState->getUnusedAllowedHeroes();
  203. if(!unusedHeroTypeIds.empty())
  204. {
  205. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, gameState->getRandomGenerator())).getNum();
  206. }
  207. else
  208. {
  209. logGlobal->error("No free hero type ID found to replace prison.");
  210. assert(0);
  211. }
  212. }
  213. else
  214. {
  215. assert(0); // should not happen
  216. }
  217. hero->subID = heroTypeId;
  218. hero->portrait = hero->subID;
  219. gameState->map->getEditManager()->insertObject(hero);
  220. }
  221. }
  222. void CGameStateCampaign::giveCampaignBonusToHero(CGHeroInstance * hero)
  223. {
  224. auto curBonus = currentBonus();
  225. if(!curBonus)
  226. return;
  227. assert(curBonus->isBonusForHero());
  228. //apply bonus
  229. switch(curBonus->type)
  230. {
  231. case CampaignBonusType::SPELL:
  232. {
  233. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  234. break;
  235. }
  236. case CampaignBonusType::MONSTER:
  237. {
  238. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  239. {
  240. if(hero->slotEmpty(SlotID(i)))
  241. {
  242. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  243. break;
  244. }
  245. }
  246. break;
  247. }
  248. case CampaignBonusType::ARTIFACT:
  249. {
  250. if(!gameState->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2)))
  251. logGlobal->error("Cannot give starting artifact - no free slots!");
  252. break;
  253. }
  254. case CampaignBonusType::SPELL_SCROLL:
  255. {
  256. CArtifactInstance * scroll = ArtifactUtils::createScroll(SpellID(curBonus->info2));
  257. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  258. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  259. scroll->putAt(ArtifactLocation(hero, slot));
  260. else
  261. logGlobal->error("Cannot give starting scroll - no free slots!");
  262. break;
  263. }
  264. case CampaignBonusType::PRIMARY_SKILL:
  265. {
  266. const ui8 * ptr = reinterpret_cast<const ui8 *>(&curBonus->info2);
  267. for(int g = 0; g < GameConstants::PRIMARY_SKILLS; ++g)
  268. {
  269. int val = ptr[g];
  270. if(val == 0)
  271. {
  272. continue;
  273. }
  274. auto bb = std::make_shared<Bonus>(
  275. BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, static_cast<int>(*gameState->scenarioOps->campState->currentScenario()), g
  276. );
  277. hero->addNewBonus(bb);
  278. }
  279. break;
  280. }
  281. case CampaignBonusType::SECONDARY_SKILL:
  282. {
  283. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  284. break;
  285. }
  286. }
  287. }
  288. void CGameStateCampaign::replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements)
  289. {
  290. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  291. {
  292. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(gameState->getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  293. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  294. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  295. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  296. heroToPlace->pos = heroPlaceholder->pos;
  297. heroToPlace->type = VLC->heroh->objects[heroToPlace->subID];
  298. heroToPlace->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, heroToPlace->type->heroClass->getIndex())->getTemplates().front();
  299. gameState->map->removeBlockVisTiles(heroPlaceholder, true);
  300. gameState->map->objects[heroPlaceholder->id.getNum()] = nullptr;
  301. gameState->map->instanceNames.erase(heroPlaceholder->instanceName);
  302. gameState->map->heroesOnMap.emplace_back(heroToPlace);
  303. gameState->map->objects[heroToPlace->id.getNum()] = heroToPlace;
  304. gameState->map->addBlockVisTiles(heroToPlace);
  305. gameState->map->instanceNames[heroToPlace->instanceName] = heroToPlace;
  306. delete heroPlaceholder;
  307. }
  308. }
  309. std::vector<CampaignHeroReplacement> CGameStateCampaign::generateCampaignHeroesToReplace()
  310. {
  311. auto campaignState = gameState->scenarioOps->campState;
  312. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  313. std::vector<CGHeroPlaceholder *> placeholdersByPower;
  314. std::vector<CGHeroPlaceholder *> placeholdersByType;
  315. // find all placeholders on map
  316. for(auto obj : gameState->map->objects)
  317. {
  318. if(!obj)
  319. continue;
  320. if (obj->ID != Obj::HERO_PLACEHOLDER)
  321. continue;
  322. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  323. // only 1 field must be set
  324. assert(heroPlaceholder->powerRank != heroPlaceholder->heroType);
  325. if(heroPlaceholder->powerRank)
  326. placeholdersByPower.push_back(heroPlaceholder);
  327. if(heroPlaceholder->heroType)
  328. placeholdersByType.push_back(heroPlaceholder);
  329. }
  330. //selecting heroes by type
  331. for (auto const * placeholder : placeholdersByType)
  332. {
  333. auto const & node = campaignState->getHeroByType(*placeholder->heroType);
  334. if (node.isNull())
  335. {
  336. logGlobal->info("Hero crossover: Unable to replace placeholder for %d (%s)!", placeholder->heroType->getNum(), VLC->heroTypes()->getById(*placeholder->heroType)->getNameTranslated());
  337. continue;
  338. }
  339. CGHeroInstance * hero = CampaignState::crossoverDeserialize(node, gameState->map);
  340. logGlobal->info("Hero crossover: Loading placeholder for %d (%s)", hero->subID, hero->getNameTranslated());
  341. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  342. }
  343. auto lastScenario = getHeroesSourceScenario();
  344. if (!placeholdersByPower.empty() && lastScenario)
  345. {
  346. // sort hero placeholders descending power
  347. boost::range::sort(placeholdersByPower, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  348. {
  349. return *a->powerRank > *b->powerRank;
  350. });
  351. auto const & nodeList = campaignState->getHeroesByPower(lastScenario.value());
  352. auto nodeListIter = nodeList.begin();
  353. for (auto const * placeholder : placeholdersByPower)
  354. {
  355. if (nodeListIter == nodeList.end())
  356. break;
  357. CGHeroInstance * hero = CampaignState::crossoverDeserialize(*nodeListIter, gameState->map);
  358. nodeListIter++;
  359. logGlobal->info("Hero crossover: Loading placeholder as %d (%s)", hero->subID, hero->getNameTranslated());
  360. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  361. }
  362. }
  363. return campaignHeroReplacements;
  364. }
  365. void CGameStateCampaign::initHeroes()
  366. {
  367. auto chosenBonus = currentBonus();
  368. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  369. {
  370. //find human player
  371. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  372. for (auto & elem : gameState->players)
  373. {
  374. if(elem.second.human)
  375. {
  376. humanPlayer = elem.first;
  377. break;
  378. }
  379. }
  380. assert(humanPlayer != PlayerColor::NEUTRAL);
  381. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = gameState->players[humanPlayer].heroes;
  382. if (chosenBonus->info1 == 0xFFFD) //most powerful
  383. {
  384. int maxB = -1;
  385. for (int b=0; b<heroes.size(); ++b)
  386. {
  387. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  388. {
  389. maxB = b;
  390. }
  391. }
  392. if(maxB < 0)
  393. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  394. else
  395. giveCampaignBonusToHero(heroes[maxB]);
  396. }
  397. else //specific hero
  398. {
  399. for (auto & heroe : heroes)
  400. {
  401. if (heroe->subID == chosenBonus->info1)
  402. {
  403. giveCampaignBonusToHero(heroe);
  404. break;
  405. }
  406. }
  407. }
  408. }
  409. }
  410. void CGameStateCampaign::initStartingResources()
  411. {
  412. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  413. {
  414. std::vector<const PlayerSettings *> ret;
  415. for(const auto & playerInfo : gameState->scenarioOps->playerInfos)
  416. {
  417. if(playerInfo.second.isControlledByHuman())
  418. ret.push_back(&playerInfo.second);
  419. }
  420. return ret;
  421. };
  422. auto chosenBonus = currentBonus();
  423. if(chosenBonus && chosenBonus->type == CampaignBonusType::RESOURCE)
  424. {
  425. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  426. for(const PlayerSettings *ps : people)
  427. {
  428. std::vector<int> res; //resources we will give
  429. switch (chosenBonus->info1)
  430. {
  431. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  432. res.push_back(chosenBonus->info1);
  433. break;
  434. case 0xFD: //wood+ore
  435. res.push_back(GameResID(EGameResID::WOOD));
  436. res.push_back(GameResID(EGameResID::ORE));
  437. break;
  438. case 0xFE: //rare
  439. res.push_back(GameResID(EGameResID::MERCURY));
  440. res.push_back(GameResID(EGameResID::SULFUR));
  441. res.push_back(GameResID(EGameResID::CRYSTAL));
  442. res.push_back(GameResID(EGameResID::GEMS));
  443. break;
  444. default:
  445. assert(0);
  446. break;
  447. }
  448. //increasing resource quantity
  449. for (auto & re : res)
  450. {
  451. gameState->players[ps->color].resources[re] += chosenBonus->info2;
  452. }
  453. }
  454. }
  455. }
  456. void CGameStateCampaign::initTowns()
  457. {
  458. auto chosenBonus = currentBonus();
  459. if (!chosenBonus)
  460. return;
  461. if (chosenBonus->type != CampaignBonusType::BUILDING)
  462. return;
  463. for (int g=0; g<gameState->map->towns.size(); ++g)
  464. {
  465. CGTownInstance * town = gameState->map->towns[g];
  466. PlayerState * owner = gameState->getPlayerState(town->getOwner());
  467. if (!owner)
  468. continue;
  469. PlayerInfo & pi = gameState->map->players[owner->color.getNum()];
  470. if (!owner->human)
  471. continue;
  472. if (town->pos != pi.posOfMainTown)
  473. continue;
  474. BuildingID newBuilding;
  475. if(gameState->scenarioOps->campState->formatVCMI())
  476. newBuilding = BuildingID(chosenBonus->info1);
  477. else
  478. newBuilding = CBuildingHandler::campToERMU(chosenBonus->info1, town->subID, town->builtBuildings);
  479. // Build granted building & all prerequisites - e.g. Mages Guild Lvl 3 should also give Mages Guild Lvl 1 & 2
  480. while(true)
  481. {
  482. if (newBuilding == BuildingID::NONE)
  483. break;
  484. if (town->builtBuildings.count(newBuilding) != 0)
  485. break;
  486. town->builtBuildings.insert(newBuilding);
  487. auto building = town->town->buildings.at(newBuilding);
  488. newBuilding = building->upgrade;
  489. }
  490. break;
  491. }
  492. }
  493. bool CGameStateCampaign::playerHasStartingHero(PlayerColor playerColor) const
  494. {
  495. auto campaignBonus = currentBonus();
  496. if (!campaignBonus)
  497. return false;
  498. if(campaignBonus->type == CampaignBonusType::HERO && playerColor == PlayerColor(campaignBonus->info1))
  499. return true;
  500. return false;
  501. }
  502. std::unique_ptr<CMap> CGameStateCampaign::getCurrentMap() const
  503. {
  504. return gameState->scenarioOps->campState->getMap(CampaignScenarioID::NONE);
  505. }
  506. VCMI_LIB_NAMESPACE_END