CRewardableObject.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. * CRewardableObject.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 "CRewardableObject.h"
  12. #include "../CPlayerState.h"
  13. #include "../GameSettings.h"
  14. #include "../IGameCallback.h"
  15. #include "../battle/BattleLayout.h"
  16. #include "../gameState/CGameState.h"
  17. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  18. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  19. #include "../mapObjectConstructors/CRewardableConstructor.h"
  20. #include "../mapObjects/CGHeroInstance.h"
  21. #include "../networkPacks/PacksForClient.h"
  22. #include "../networkPacks/PacksForClientBattle.h"
  23. #include "../serializer/JsonSerializeFormat.h"
  24. #include "../texts/CGeneralTextHandler.h"
  25. #include <vstd/RNG.h>
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. void CRewardableObject::grantRewardWithMessage(const CGHeroInstance * contextHero, int index, bool markAsVisit) const
  28. {
  29. auto vi = configuration.info.at(index);
  30. logGlobal->debug("Granting reward %d. Message says: %s", index, vi.message.toString());
  31. // show message only if it is not empty or in infobox
  32. if (configuration.infoWindowType != EInfoWindowMode::MODAL || !vi.message.toString().empty())
  33. {
  34. InfoWindow iw;
  35. iw.player = contextHero->tempOwner;
  36. iw.text = vi.message;
  37. vi.reward.loadComponents(iw.components, contextHero);
  38. iw.type = configuration.infoWindowType;
  39. if(!iw.components.empty() || !iw.text.toString().empty())
  40. cb->showInfoDialog(&iw);
  41. }
  42. // grant reward afterwards. Note that it may remove object
  43. if(markAsVisit)
  44. markAsVisited(contextHero);
  45. grantReward(index, contextHero);
  46. }
  47. void CRewardableObject::selectRewardWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, const MetaString & dialog) const
  48. {
  49. BlockingDialog sd(configuration.canRefuse, rewardIndices.size() > 1);
  50. sd.player = contextHero->tempOwner;
  51. sd.text = dialog;
  52. sd.components = loadComponents(contextHero, rewardIndices);
  53. cb->showBlockingDialog(this, &sd);
  54. }
  55. void CRewardableObject::grantAllRewardsWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, bool markAsVisit) const
  56. {
  57. if (rewardIndices.empty())
  58. return;
  59. for (auto index : rewardIndices)
  60. {
  61. // TODO: Merge all rewards of same type, with single message?
  62. grantRewardWithMessage(contextHero, index, false);
  63. }
  64. // Mark visited only after all rewards were processed
  65. if(markAsVisit)
  66. markAsVisited(contextHero);
  67. }
  68. std::vector<Component> CRewardableObject::loadComponents(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices) const
  69. {
  70. std::vector<Component> result;
  71. if (rewardIndices.empty())
  72. return result;
  73. if (configuration.selectMode != Rewardable::SELECT_FIRST && rewardIndices.size() > 1)
  74. {
  75. for (auto index : rewardIndices)
  76. result.push_back(configuration.info.at(index).reward.getDisplayedComponent(contextHero));
  77. }
  78. else
  79. {
  80. configuration.info.at(rewardIndices.front()).reward.loadComponents(result, contextHero);
  81. }
  82. return result;
  83. }
  84. bool CRewardableObject::guardedPotentially() const
  85. {
  86. for (auto const & visitInfo : configuration.info)
  87. if (!visitInfo.reward.guards.empty())
  88. return true;
  89. return false;
  90. }
  91. bool CRewardableObject::guardedPresently() const
  92. {
  93. return stacksCount() > 0;
  94. }
  95. void CRewardableObject::onHeroVisit(const CGHeroInstance *hero) const
  96. {
  97. if(!wasScouted(hero->getOwner()))
  98. {
  99. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_SCOUTED, id, hero->id);
  100. cb->sendAndApply(&cov);
  101. }
  102. if (guardedPresently())
  103. {
  104. auto guardedIndexes = getAvailableRewards(hero, Rewardable::EEventType::EVENT_GUARDED);
  105. auto guardedReward = configuration.info.at(guardedIndexes.at(0));
  106. // ask player to confirm attack
  107. BlockingDialog bd(true, false);
  108. bd.player = hero->getOwner();
  109. bd.text = guardedReward.message;
  110. bd.components = getPopupComponents(hero->getOwner());
  111. cb->showBlockingDialog(this, &bd);
  112. }
  113. else
  114. {
  115. doHeroVisit(hero);
  116. }
  117. }
  118. void CRewardableObject::doHeroVisit(const CGHeroInstance *h) const
  119. {
  120. if(!wasVisitedBefore(h))
  121. {
  122. auto rewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT);
  123. bool objectRemovalPossible = false;
  124. for(auto index : rewards)
  125. {
  126. if(configuration.info.at(index).reward.removeObject)
  127. objectRemovalPossible = true;
  128. }
  129. logGlobal->debug("Visiting object with %d possible rewards", rewards.size());
  130. switch (rewards.size())
  131. {
  132. case 0: // no available rewards, e.g. visiting School of War without gold
  133. {
  134. auto emptyRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_NOT_AVAILABLE);
  135. if (!emptyRewards.empty())
  136. grantRewardWithMessage(h, emptyRewards[0], false);
  137. else
  138. logMod->warn("No applicable message for visiting empty object!");
  139. break;
  140. }
  141. case 1: // one reward. Just give it with message
  142. {
  143. if (configuration.canRefuse)
  144. selectRewardWithMessage(h, rewards, configuration.info.at(rewards.front()).message);
  145. else
  146. grantRewardWithMessage(h, rewards.front(), true);
  147. break;
  148. }
  149. default: // multiple rewards. Act according to select mode
  150. {
  151. switch (configuration.selectMode) {
  152. case Rewardable::SELECT_PLAYER: // player must select
  153. selectRewardWithMessage(h, rewards, configuration.onSelect);
  154. break;
  155. case Rewardable::SELECT_FIRST: // give first available
  156. if (configuration.canRefuse)
  157. selectRewardWithMessage(h, { rewards.front() }, configuration.info.at(rewards.front()).message);
  158. else
  159. grantRewardWithMessage(h, rewards.front(), true);
  160. break;
  161. case Rewardable::SELECT_RANDOM: // give random
  162. {
  163. ui32 rewardIndex = *RandomGeneratorUtil::nextItem(rewards, cb->gameState()->getRandomGenerator());
  164. if (configuration.canRefuse)
  165. selectRewardWithMessage(h, { rewardIndex }, configuration.info.at(rewardIndex).message);
  166. else
  167. grantRewardWithMessage(h, rewardIndex, true);
  168. break;
  169. }
  170. case Rewardable::SELECT_ALL: // grant all possible
  171. grantAllRewardsWithMessage(h, rewards, true);
  172. break;
  173. }
  174. break;
  175. }
  176. }
  177. if(!objectRemovalPossible && getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT).empty())
  178. {
  179. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD_PLAYER, id, h->id);
  180. cb->sendAndApply(&cov);
  181. }
  182. }
  183. else
  184. {
  185. logGlobal->debug("Revisiting already visited object");
  186. if (!wasVisited(h->getOwner()))
  187. {
  188. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD_PLAYER, id, h->id);
  189. cb->sendAndApply(&cov);
  190. }
  191. auto visitedRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_ALREADY_VISITED);
  192. if (!visitedRewards.empty())
  193. grantRewardWithMessage(h, visitedRewards[0], false);
  194. else
  195. logMod->warn("No applicable message for visiting already visited object!");
  196. }
  197. }
  198. void CRewardableObject::heroLevelUpDone(const CGHeroInstance *hero) const
  199. {
  200. grantRewardAfterLevelup(cb, configuration.info.at(selectedReward), this, hero);
  201. }
  202. void CRewardableObject::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  203. {
  204. if (result.winner == BattleSide::ATTACKER)
  205. {
  206. doHeroVisit(hero);
  207. }
  208. }
  209. void CRewardableObject::blockingDialogAnswered(const CGHeroInstance * hero, int32_t answer) const
  210. {
  211. if(guardedPresently())
  212. {
  213. if (answer)
  214. {
  215. auto layout = BattleLayout::createLayout(cb, configuration.guardsLayout, hero, this);
  216. cb->startBattle(hero, this, visitablePos(), hero, nullptr, layout, nullptr);
  217. }
  218. }
  219. else
  220. {
  221. if (answer == 0)
  222. return; //Player refused
  223. if(answer > 0 && answer - 1 < configuration.info.size())
  224. {
  225. auto list = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  226. markAsVisited(hero);
  227. grantReward(list[answer - 1], hero);
  228. }
  229. else
  230. {
  231. throw std::runtime_error("Unhandled choice");
  232. }
  233. }
  234. }
  235. void CRewardableObject::markAsVisited(const CGHeroInstance * hero) const
  236. {
  237. cb->setObjPropertyValue(id, ObjProperty::REWARD_CLEARED, true);
  238. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD_HERO, id, hero->id);
  239. cb->sendAndApply(&cov);
  240. }
  241. void CRewardableObject::grantReward(ui32 rewardID, const CGHeroInstance * hero) const
  242. {
  243. cb->setObjPropertyValue(id, ObjProperty::REWARD_SELECT, rewardID);
  244. grantRewardBeforeLevelup(cb, configuration.info.at(rewardID), hero);
  245. // hero is not blocked by levelup dialog - grant remainder immediately
  246. if(!cb->isVisitCoveredByAnotherQuery(this, hero))
  247. {
  248. grantRewardAfterLevelup(cb, configuration.info.at(rewardID), this, hero);
  249. }
  250. }
  251. bool CRewardableObject::wasVisitedBefore(const CGHeroInstance * contextHero) const
  252. {
  253. switch (configuration.visitMode)
  254. {
  255. case Rewardable::VISIT_UNLIMITED:
  256. return false;
  257. case Rewardable::VISIT_ONCE:
  258. return onceVisitableObjectCleared;
  259. case Rewardable::VISIT_PLAYER:
  260. return vstd::contains(cb->getPlayerState(contextHero->getOwner())->visitedObjects, ObjectInstanceID(id));
  261. case Rewardable::VISIT_BONUS:
  262. return contextHero->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID));
  263. case Rewardable::VISIT_HERO:
  264. return contextHero->visitedObjects.count(ObjectInstanceID(id));
  265. case Rewardable::VISIT_LIMITER:
  266. return configuration.visitLimiter.heroAllowed(contextHero);
  267. default:
  268. return false;
  269. }
  270. }
  271. bool CRewardableObject::wasVisited(PlayerColor player) const
  272. {
  273. switch (configuration.visitMode)
  274. {
  275. case Rewardable::VISIT_UNLIMITED:
  276. case Rewardable::VISIT_BONUS:
  277. case Rewardable::VISIT_HERO:
  278. case Rewardable::VISIT_LIMITER:
  279. return false;
  280. case Rewardable::VISIT_ONCE:
  281. case Rewardable::VISIT_PLAYER:
  282. return vstd::contains(cb->getPlayerState(player)->visitedObjects, ObjectInstanceID(id));
  283. default:
  284. return false;
  285. }
  286. }
  287. bool CRewardableObject::wasScouted(PlayerColor player) const
  288. {
  289. return vstd::contains(cb->getPlayerTeam(player)->scoutedObjects, ObjectInstanceID(id));
  290. }
  291. bool CRewardableObject::wasVisited(const CGHeroInstance * h) const
  292. {
  293. switch (configuration.visitMode)
  294. {
  295. case Rewardable::VISIT_BONUS:
  296. return h->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID));
  297. case Rewardable::VISIT_HERO:
  298. return h->visitedObjects.count(ObjectInstanceID(id));
  299. case Rewardable::VISIT_LIMITER:
  300. return wasScouted(h->getOwner()) && configuration.visitLimiter.heroAllowed(h);
  301. default:
  302. return wasVisited(h->getOwner());
  303. }
  304. }
  305. std::string CRewardableObject::getDisplayTextImpl(PlayerColor player, const CGHeroInstance * hero, bool includeDescription) const
  306. {
  307. std::string result = getObjectName();
  308. if (includeDescription && !getDescriptionMessage(player, hero).empty())
  309. result += "\n" + getDescriptionMessage(player, hero);
  310. if (hero)
  311. {
  312. if(configuration.visitMode != Rewardable::VISIT_UNLIMITED)
  313. {
  314. if (wasVisited(hero))
  315. result += "\n" + configuration.visitedTooltip.toString();
  316. else
  317. result += "\n " + configuration.notVisitedTooltip.toString();
  318. }
  319. }
  320. else
  321. {
  322. if(configuration.visitMode == Rewardable::VISIT_PLAYER || configuration.visitMode == Rewardable::VISIT_ONCE)
  323. {
  324. if (wasVisited(player))
  325. result += "\n" + configuration.visitedTooltip.toString();
  326. else
  327. result += "\n" + configuration.notVisitedTooltip.toString();
  328. }
  329. }
  330. return result;
  331. }
  332. std::string CRewardableObject::getHoverText(PlayerColor player) const
  333. {
  334. return getDisplayTextImpl(player, nullptr, false);
  335. }
  336. std::string CRewardableObject::getHoverText(const CGHeroInstance * hero) const
  337. {
  338. return getDisplayTextImpl(hero->getOwner(), hero, false);
  339. }
  340. std::string CRewardableObject::getPopupText(PlayerColor player) const
  341. {
  342. return getDisplayTextImpl(player, nullptr, true);
  343. }
  344. std::string CRewardableObject::getPopupText(const CGHeroInstance * hero) const
  345. {
  346. return getDisplayTextImpl(hero->getOwner(), hero, true);
  347. }
  348. std::string CRewardableObject::getDescriptionMessage(PlayerColor player, const CGHeroInstance * hero) const
  349. {
  350. if (!wasScouted(player) || configuration.info.empty())
  351. return configuration.description.toString();
  352. auto rewardIndices = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  353. if (rewardIndices.empty() || !configuration.info[0].description.empty())
  354. return configuration.info[0].description.toString();
  355. if (!configuration.info[rewardIndices.front()].description.empty())
  356. return configuration.info[rewardIndices.front()].description.toString();
  357. return configuration.description.toString();
  358. }
  359. std::vector<Component> CRewardableObject::getPopupComponentsImpl(PlayerColor player, const CGHeroInstance * hero) const
  360. {
  361. if (!wasScouted(player))
  362. return {};
  363. if (guardedPresently())
  364. {
  365. if (!cb->getSettings().getBoolean(EGameSettings::BANKS_SHOW_GUARDS_COMPOSITION))
  366. return {};
  367. std::map<CreatureID, int> guardsAmounts;
  368. std::vector<Component> result;
  369. for (auto const & slot : Slots())
  370. if (slot.second)
  371. guardsAmounts[slot.second->getCreatureID()] += slot.second->getCount();
  372. for (auto const & guard : guardsAmounts)
  373. {
  374. Component comp(ComponentType::CREATURE, guard.first, guard.second);
  375. result.push_back(comp);
  376. }
  377. return result;
  378. }
  379. else
  380. {
  381. if (!configuration.showScoutedPreview)
  382. return {};
  383. auto rewardIndices = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  384. if (rewardIndices.empty() && !configuration.info.empty())
  385. {
  386. // Object has valid config, but current hero has no rewards that he can receive.
  387. // Usually this happens if hero has already visited this object -> show reward using context without any hero
  388. // since reward may be context-sensitive - e.g. Witch Hut that gives 1 skill, but always at basic level
  389. return loadComponents(nullptr, {0});
  390. }
  391. if (rewardIndices.empty())
  392. return {};
  393. return loadComponents(hero, rewardIndices);
  394. }
  395. }
  396. std::vector<Component> CRewardableObject::getPopupComponents(PlayerColor player) const
  397. {
  398. return getPopupComponentsImpl(player, nullptr);
  399. }
  400. std::vector<Component> CRewardableObject::getPopupComponents(const CGHeroInstance * hero) const
  401. {
  402. return getPopupComponentsImpl(hero->getOwner(), hero);
  403. }
  404. void CRewardableObject::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  405. {
  406. switch (what)
  407. {
  408. case ObjProperty::REWARD_SELECT:
  409. selectedReward = identifier.getNum();
  410. break;
  411. case ObjProperty::REWARD_CLEARED:
  412. onceVisitableObjectCleared = identifier.getNum();
  413. break;
  414. }
  415. }
  416. void CRewardableObject::newTurn(vstd::RNG & rand) const
  417. {
  418. if (configuration.resetParameters.period != 0 && cb->getDate(Date::DAY) > 1 && ((cb->getDate(Date::DAY)-1) % configuration.resetParameters.period) == 0)
  419. {
  420. if (configuration.resetParameters.rewards)
  421. {
  422. auto handler = std::dynamic_pointer_cast<const CRewardableConstructor>(getObjectHandler());
  423. auto newConfiguration = handler->generateConfiguration(cb, rand, ID);
  424. cb->setRewardableObjectConfiguration(id, newConfiguration);
  425. }
  426. if (configuration.resetParameters.visitors)
  427. {
  428. cb->setObjPropertyValue(id, ObjProperty::REWARD_CLEARED, false);
  429. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_CLEAR, id);
  430. cb->sendAndApply(&cov);
  431. }
  432. }
  433. }
  434. void CRewardableObject::initObj(vstd::RNG & rand)
  435. {
  436. getObjectHandler()->configureObject(this, rand);
  437. }
  438. CRewardableObject::CRewardableObject(IGameCallback *cb)
  439. :CArmedInstance(cb)
  440. {}
  441. void CRewardableObject::serializeJsonOptions(JsonSerializeFormat & handler)
  442. {
  443. CArmedInstance::serializeJsonOptions(handler);
  444. handler.serializeStruct("rewardable", static_cast<Rewardable::Interface&>(*this));
  445. }
  446. void CRewardableObject::initializeGuards()
  447. {
  448. clearSlots();
  449. // Workaround for default creature banks strings that has placeholder for object name
  450. // TODO: find better location for this code
  451. for (auto & visitInfo : configuration.info)
  452. visitInfo.message.replaceRawString(getObjectName());
  453. for (auto const & visitInfo : configuration.info)
  454. {
  455. for (auto const & guard : visitInfo.reward.guards)
  456. {
  457. auto slotID = getFreeSlot();
  458. if (!slotID.validSlot())
  459. return;
  460. putStack(slotID, new CStackInstance(guard.getId(), guard.getCount()));
  461. }
  462. }
  463. }
  464. bool CRewardableObject::isCoastVisitable() const
  465. {
  466. return configuration.coastVisitable;
  467. }
  468. VCMI_LIB_NAMESPACE_END