Interface.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /*
  2. * Interface.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 "Interface.h"
  12. #include "../TerrainHandler.h"
  13. #include "../CPlayerState.h"
  14. #include "../CSoundBase.h"
  15. #include "../entities/hero/CHeroHandler.h"
  16. #include "../gameState/CGameState.h"
  17. #include "../spells/CSpellHandler.h"
  18. #include "../spells/ISpellMechanics.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../mapObjects/MiscObjects.h"
  21. #include "../mapping/CMapDefines.h"
  22. #include "../networkPacks/StackLocation.h"
  23. #include "../networkPacks/PacksForClient.h"
  24. #include "../IGameCallback.h"
  25. #include <vstd/RNG.h>
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. std::vector<ui32> Rewardable::Interface::getAvailableRewards(const CGHeroInstance * hero, Rewardable::EEventType event) const
  28. {
  29. std::vector<ui32> ret;
  30. for(size_t i = 0; i < configuration.info.size(); i++)
  31. {
  32. const Rewardable::VisitInfo & visit = configuration.info[i];
  33. if(event == visit.visitType && (!hero || visit.limiter.heroAllowed(hero)))
  34. {
  35. logGlobal->trace("Reward %d is allowed", i);
  36. ret.push_back(static_cast<ui32>(i));
  37. }
  38. }
  39. return ret;
  40. }
  41. void Rewardable::Interface::grantRewardBeforeLevelup(const Rewardable::VisitInfo & info, const CGHeroInstance * hero) const
  42. {
  43. auto cb = getObject()->cb;
  44. assert(hero);
  45. assert(hero->tempOwner.isValidPlayer());
  46. assert(info.reward.creatures.size() <= GameConstants::ARMY_SIZE);
  47. cb->giveResources(hero->tempOwner, info.reward.resources);
  48. if (info.reward.revealTiles)
  49. {
  50. const auto & props = *info.reward.revealTiles;
  51. const auto functor = [&props](const TerrainTile * tile)
  52. {
  53. int score = 0;
  54. if (tile->getTerrain()->isSurface())
  55. score += props.scoreSurface;
  56. if (tile->getTerrain()->isUnderground())
  57. score += props.scoreSubterra;
  58. if (tile->getTerrain()->isWater())
  59. score += props.scoreWater;
  60. if (tile->getTerrain()->isRock())
  61. score += props.scoreRock;
  62. return score > 0;
  63. };
  64. std::unordered_set<int3> tiles;
  65. if (props.radius > 0)
  66. {
  67. cb->getTilesInRange(tiles, hero->getSightCenter(), props.radius, ETileVisibility::HIDDEN, hero->getOwner());
  68. if (props.hide)
  69. cb->getTilesInRange(tiles, hero->getSightCenter(), props.radius, ETileVisibility::REVEALED, hero->getOwner());
  70. vstd::erase_if(tiles, [&](const int3 & coord){
  71. return !functor(cb->getTile(coord));
  72. });
  73. }
  74. else
  75. {
  76. cb->getAllTiles(tiles, hero->tempOwner, -1, functor);
  77. }
  78. if (props.hide)
  79. {
  80. for (auto & player : cb->gameState()->players)
  81. {
  82. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME && cb->getPlayerRelations(player.first, hero->getOwner()) == PlayerRelations::ENEMIES)
  83. cb->changeFogOfWar(tiles, player.first, ETileVisibility::HIDDEN);
  84. }
  85. }
  86. else
  87. {
  88. cb->changeFogOfWar(tiles, hero->getOwner(), ETileVisibility::REVEALED);
  89. }
  90. }
  91. for(const auto & entry : info.reward.secondary)
  92. {
  93. auto currentLevel = static_cast<MasteryLevel::Type>(hero->getSecSkillLevel(entry.first));
  94. if(currentLevel == MasteryLevel::EXPERT)
  95. continue;
  96. if(currentLevel != MasteryLevel::NONE || hero->canLearnSkill())
  97. cb->changeSecSkill(hero, entry.first, entry.second, false);
  98. }
  99. for(int i=0; i< info.reward.primary.size(); i++)
  100. cb->changePrimSkill(hero, static_cast<PrimarySkill>(i), info.reward.primary[i], false);
  101. TExpType expToGive = 0;
  102. if (info.reward.heroLevel > 0)
  103. expToGive += VLC->heroh->reqExp(hero->level+info.reward.heroLevel) - VLC->heroh->reqExp(hero->level);
  104. if (info.reward.heroExperience > 0)
  105. expToGive += hero->calculateXp(info.reward.heroExperience);
  106. if(expToGive)
  107. cb->giveExperience(hero, expToGive);
  108. }
  109. void Rewardable::Interface::grantRewardAfterLevelup(const Rewardable::VisitInfo & info, const CArmedInstance * army, const CGHeroInstance * hero) const
  110. {
  111. auto cb = getObject()->cb;
  112. if(info.reward.manaDiff || info.reward.manaPercentage >= 0)
  113. cb->setManaPoints(hero->id, info.reward.calculateManaPoints(hero));
  114. if(info.reward.movePoints || info.reward.movePercentage >= 0)
  115. {
  116. SetMovePoints smp;
  117. smp.hid = hero->id;
  118. smp.val = hero->movementPointsRemaining();
  119. if (info.reward.movePercentage >= 0) // percent from max
  120. smp.val = hero->movementPointsLimit(hero->boat && hero->boat->layer == EPathfindingLayer::SAIL) * info.reward.movePercentage / 100;
  121. smp.val = std::max<si32>(0, smp.val + info.reward.movePoints);
  122. cb->setMovePoints(&smp);
  123. }
  124. for(const Bonus & bonus : info.reward.bonuses)
  125. {
  126. GiveBonus gb;
  127. gb.who = GiveBonus::ETarget::OBJECT;
  128. gb.bonus = bonus;
  129. gb.id = hero->id;
  130. cb->giveHeroBonus(&gb);
  131. }
  132. for(const ArtifactID & art : info.reward.artifacts)
  133. cb->giveHeroNewArtifact(hero, art, ArtifactPosition::FIRST_AVAILABLE);
  134. if(!info.reward.spells.empty())
  135. {
  136. std::set<SpellID> spellsToGive;
  137. for (auto const & spell : info.reward.spells)
  138. if (hero->canLearnSpell(spell.toEntity(VLC), true))
  139. spellsToGive.insert(spell);
  140. if (!spellsToGive.empty())
  141. cb->changeSpells(hero, true, spellsToGive);
  142. }
  143. if(!info.reward.creaturesChange.empty())
  144. {
  145. for(const auto & slot : hero->Slots())
  146. {
  147. const CStackInstance * heroStack = slot.second;
  148. for(const auto & change : info.reward.creaturesChange)
  149. {
  150. if (heroStack->getId() == change.first)
  151. {
  152. StackLocation location(hero, slot.first);
  153. cb->changeStackType(location, change.second.toCreature());
  154. break;
  155. }
  156. }
  157. }
  158. }
  159. if(!info.reward.creatures.empty())
  160. {
  161. CCreatureSet creatures;
  162. for(const auto & crea : info.reward.creatures)
  163. creatures.addToSlot(creatures.getFreeSlot(), new CStackInstance(crea.getCreature(), crea.count));
  164. if(auto * army = dynamic_cast<const CArmedInstance*>(this)) //TODO: to fix that, CArmedInstance must be split on map instance part and interface part
  165. cb->giveCreatures(army, hero, creatures, false);
  166. }
  167. if(info.reward.spellCast.first != SpellID::NONE)
  168. {
  169. caster.setActualCaster(hero);
  170. caster.setSpellSchoolLevel(info.reward.spellCast.second);
  171. cb->castSpell(&caster, info.reward.spellCast.first, int3{-1, -1, -1});
  172. }
  173. if(info.reward.removeObject)
  174. if(auto * instance = dynamic_cast<const CGObjectInstance*>(this))
  175. cb->removeAfterVisit(instance);
  176. }
  177. void Rewardable::Interface::serializeJson(JsonSerializeFormat & handler)
  178. {
  179. configuration.serializeJson(handler);
  180. }
  181. void Rewardable::Interface::grantRewardWithMessage(const CGHeroInstance * contextHero, int index, bool markAsVisit) const
  182. {
  183. auto vi = configuration.info.at(index);
  184. logGlobal->debug("Granting reward %d. Message says: %s", index, vi.message.toString());
  185. // show message only if it is not empty or in infobox
  186. if (configuration.infoWindowType != EInfoWindowMode::MODAL || !vi.message.toString().empty())
  187. {
  188. InfoWindow iw;
  189. iw.player = contextHero->tempOwner;
  190. iw.text = vi.message;
  191. vi.reward.loadComponents(iw.components, contextHero);
  192. iw.type = configuration.infoWindowType;
  193. if(!iw.components.empty() || !iw.text.toString().empty())
  194. getObject()->cb->showInfoDialog(&iw);
  195. }
  196. // grant reward afterwards. Note that it may remove object
  197. if(markAsVisit)
  198. markAsVisited(contextHero);
  199. grantReward(index, contextHero);
  200. }
  201. void Rewardable::Interface::selectRewardWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, const MetaString & dialog) const
  202. {
  203. BlockingDialog sd(configuration.canRefuse, rewardIndices.size() > 1);
  204. sd.player = contextHero->tempOwner;
  205. sd.text = dialog;
  206. sd.components = loadComponents(contextHero, rewardIndices);
  207. getObject()->cb->showBlockingDialog(getObject(), &sd);
  208. }
  209. std::vector<Component> Rewardable::Interface::loadComponents(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices) const
  210. {
  211. std::vector<Component> result;
  212. if (rewardIndices.empty())
  213. return result;
  214. if (configuration.selectMode != Rewardable::SELECT_FIRST && rewardIndices.size() > 1)
  215. {
  216. for (auto index : rewardIndices)
  217. result.push_back(configuration.info.at(index).reward.getDisplayedComponent(contextHero));
  218. }
  219. else
  220. {
  221. configuration.info.at(rewardIndices.front()).reward.loadComponents(result, contextHero);
  222. }
  223. return result;
  224. }
  225. void Rewardable::Interface::grantAllRewardsWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, bool markAsVisit) const
  226. {
  227. if (rewardIndices.empty())
  228. return;
  229. for (auto index : rewardIndices)
  230. {
  231. // TODO: Merge all rewards of same type, with single message?
  232. grantRewardWithMessage(contextHero, index, false);
  233. }
  234. // Mark visited only after all rewards were processed
  235. if(markAsVisit)
  236. markAsVisited(contextHero);
  237. }
  238. void Rewardable::Interface::doHeroVisit(const CGHeroInstance *h) const
  239. {
  240. if(!wasVisitedBefore(h))
  241. {
  242. auto rewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT);
  243. bool objectRemovalPossible = false;
  244. for(auto index : rewards)
  245. {
  246. if(configuration.info.at(index).reward.removeObject)
  247. objectRemovalPossible = true;
  248. }
  249. logGlobal->debug("Visiting object with %d possible rewards", rewards.size());
  250. switch (rewards.size())
  251. {
  252. case 0: // no available rewards, e.g. visiting School of War without gold
  253. {
  254. auto emptyRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_NOT_AVAILABLE);
  255. if (!emptyRewards.empty())
  256. grantRewardWithMessage(h, emptyRewards[0], false);
  257. else
  258. logMod->warn("No applicable message for visiting empty object!");
  259. break;
  260. }
  261. case 1: // one reward. Just give it with message
  262. {
  263. if (configuration.canRefuse)
  264. selectRewardWithMessage(h, rewards, configuration.info.at(rewards.front()).message);
  265. else
  266. grantRewardWithMessage(h, rewards.front(), true);
  267. break;
  268. }
  269. default: // multiple rewards. Act according to select mode
  270. {
  271. switch (configuration.selectMode) {
  272. case Rewardable::SELECT_PLAYER: // player must select
  273. selectRewardWithMessage(h, rewards, configuration.onSelect);
  274. break;
  275. case Rewardable::SELECT_FIRST: // give first available
  276. if (configuration.canRefuse)
  277. selectRewardWithMessage(h, { rewards.front() }, configuration.info.at(rewards.front()).message);
  278. else
  279. grantRewardWithMessage(h, rewards.front(), true);
  280. break;
  281. case Rewardable::SELECT_RANDOM: // give random
  282. {
  283. ui32 rewardIndex = *RandomGeneratorUtil::nextItem(rewards, getObject()->cb->getRandomGenerator());
  284. if (configuration.canRefuse)
  285. selectRewardWithMessage(h, { rewardIndex }, configuration.info.at(rewardIndex).message);
  286. else
  287. grantRewardWithMessage(h, rewardIndex, true);
  288. break;
  289. }
  290. case Rewardable::SELECT_ALL: // grant all possible
  291. grantAllRewardsWithMessage(h, rewards, true);
  292. break;
  293. }
  294. break;
  295. }
  296. }
  297. if(!objectRemovalPossible && getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT).empty())
  298. markAsScouted(h);
  299. }
  300. else
  301. {
  302. logGlobal->debug("Revisiting already visited object");
  303. if (!wasVisited(h->getOwner()))
  304. markAsScouted(h);
  305. auto visitedRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_ALREADY_VISITED);
  306. if (!visitedRewards.empty())
  307. grantRewardWithMessage(h, visitedRewards[0], false);
  308. else
  309. logMod->warn("No applicable message for visiting already visited object!");
  310. }
  311. }
  312. void Rewardable::Interface::onBlockingDialogAnswered(const CGHeroInstance * hero, int32_t answer) const
  313. {
  314. if (answer == 0)
  315. return; //Player refused
  316. if(answer > 0 && answer - 1 < configuration.info.size())
  317. {
  318. auto list = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  319. markAsVisited(hero);
  320. grantReward(list[answer - 1], hero);
  321. }
  322. else
  323. {
  324. throw std::runtime_error("Unhandled choice");
  325. }
  326. }
  327. VCMI_LIB_NAMESPACE_END