CQuest.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /*
  2. * CQuest.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 "CQuest.h"
  12. #include <vcmi/spells/Spell.h>
  13. #include "../CSoundBase.h"
  14. #include "../texts/CGeneralTextHandler.h"
  15. #include "CGCreature.h"
  16. #include "../IGameSettings.h"
  17. #include "../callback/IGameInfoCallback.h"
  18. #include "../callback/IGameEventCallback.h"
  19. #include "../callback/IGameRandomizer.h"
  20. #include "../entities/artifact/CArtifact.h"
  21. #include "../entities/hero/CHeroHandler.h"
  22. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  23. #include "../serializer/JsonSerializeFormat.h"
  24. #include "../GameConstants.h"
  25. #include "../constants/StringConstants.h"
  26. #include "../CPlayerState.h"
  27. #include "../CSkillHandler.h"
  28. #include "../mapping/CMap.h"
  29. #include "../mapObjects/CGHeroInstance.h"
  30. #include "../modding/ModScope.h"
  31. #include "../modding/ModUtility.h"
  32. #include "../networkPacks/PacksForClient.h"
  33. #include "../spells/CSpellHandler.h"
  34. #include <vstd/RNG.h>
  35. VCMI_LIB_NAMESPACE_BEGIN
  36. //TODO: Remove constructor
  37. CQuest::CQuest():
  38. qid(-1),
  39. isCompleted(false),
  40. lastDay(-1),
  41. killTarget(ObjectInstanceID::NONE),
  42. textOption(0),
  43. completedOption(0),
  44. stackDirection(0),
  45. isCustomFirst(false),
  46. isCustomNext(false),
  47. isCustomComplete(false),
  48. repeatedQuest(false),
  49. questName(CQuest::missionName(EQuestMission::NONE))
  50. {
  51. }
  52. static std::string visitedTxt(const bool visited)
  53. {
  54. int id = visited ? 352 : 353;
  55. return LIBRARY->generaltexth->allTexts[id];
  56. }
  57. const std::string & CQuest::missionName(EQuestMission mission)
  58. {
  59. static const std::array<std::string, 14> names = {
  60. "empty",
  61. "heroLevel",
  62. "primarySkill",
  63. "killHero",
  64. "killCreature",
  65. "bringArt",
  66. "bringCreature",
  67. "bringResources",
  68. "bringHero",
  69. "bringPlayer",
  70. "hotaINVALID", // only used for h3m parsing
  71. "keymaster",
  72. "heroClass",
  73. "reachDate"
  74. };
  75. if(static_cast<size_t>(mission) < names.size())
  76. return names[static_cast<size_t>(mission)];
  77. return names[0];
  78. }
  79. const std::string & CQuest::missionState(int state)
  80. {
  81. static const std::array<std::string, 5> states = {
  82. "receive",
  83. "visit",
  84. "complete",
  85. "hover",
  86. "description",
  87. };
  88. if(state < states.size())
  89. return states[state];
  90. return states[0];
  91. }
  92. bool CQuest::checkMissionArmy(const CQuest * q, const CCreatureSet * army)
  93. {
  94. return army->hasUnits(q->mission.creatures, true);
  95. }
  96. bool CQuest::checkQuest(const CGHeroInstance * h) const
  97. {
  98. if(!mission.heroAllowed(h))
  99. return false;
  100. if(killTarget.hasValue())
  101. {
  102. PlayerColor owner = h->getOwner();
  103. if (!h->cb->getPlayerState(owner)->destroyedObjects.count(killTarget))
  104. return false;
  105. }
  106. return true;
  107. }
  108. void CQuest::completeQuest(IGameEventCallback & gameEvents, const CGHeroInstance *h, bool allowFullArmyRemoval) const
  109. {
  110. // FIXME: this should be part of 'reward', and not hacking into limiter state that should only limit access to such reward
  111. for(auto & elem : mission.artifacts)
  112. {
  113. if(h->hasArt(elem))
  114. {
  115. gameEvents.removeArtifact(ArtifactLocation(h->id, h->getArtPos(elem, false)));
  116. continue;
  117. }
  118. // perhaps artifact is part of a combined artifact?
  119. const auto * assembly = h->getCombinedArtWithPart(elem);
  120. if (assembly)
  121. {
  122. auto parts = assembly->getPartsInfo();
  123. // Remove the assembly
  124. gameEvents.removeArtifact(ArtifactLocation(h->id, h->getArtPos(assembly)));
  125. // Disassemble this backpack artifact
  126. for(const auto & ci : parts)
  127. {
  128. if(ci.getArtifact()->getTypeId() != elem)
  129. gameEvents.giveHeroNewArtifact(h, ci.getArtifact()->getTypeId(), ArtifactPosition::BACKPACK_START);
  130. }
  131. continue;
  132. }
  133. logGlobal->error("Failed to find artifact %s in inventory of hero %s", elem.toEntity(LIBRARY)->getJsonKey(), h->getHeroTypeID());
  134. }
  135. gameEvents.takeCreatures(h->id, mission.creatures, allowFullArmyRemoval);
  136. gameEvents.giveResources(h->getOwner(), -mission.resources);
  137. }
  138. void CQuest::addTextReplacements(const IGameInfoCallback * cb, MetaString & text, std::vector<Component> & components) const
  139. {
  140. if(mission.heroLevel > 0)
  141. text.replaceNumber(mission.heroLevel);
  142. if(mission.heroExperience > 0)
  143. text.replaceNumber(mission.heroExperience);
  144. { //primary skills
  145. MetaString loot;
  146. for(int i = 0; i < 4; ++i)
  147. {
  148. if(mission.primary[i])
  149. {
  150. loot.appendRawString("%d %s");
  151. loot.replaceNumber(mission.primary[i]);
  152. loot.replaceRawString(LIBRARY->generaltexth->primarySkillNames[i]);
  153. }
  154. }
  155. for(auto & skill : mission.secondary)
  156. {
  157. loot.appendTextID(LIBRARY->skillh->getById(skill.first)->getNameTextID());
  158. }
  159. for(auto & spell : mission.spells)
  160. {
  161. loot.appendTextID(LIBRARY->spellh->getById(spell)->getNameTextID());
  162. }
  163. if(!loot.empty())
  164. text.replaceRawString(loot.buildList());
  165. }
  166. if(killTarget != ObjectInstanceID::NONE && !heroName.empty())
  167. {
  168. components.emplace_back(ComponentType::HERO_PORTRAIT, heroPortrait);
  169. addKillTargetReplacements(text);
  170. }
  171. if(killTarget != ObjectInstanceID::NONE && stackToKill != CreatureID::NONE)
  172. {
  173. components.emplace_back(ComponentType::CREATURE, stackToKill);
  174. addKillTargetReplacements(text);
  175. }
  176. if(!mission.heroes.empty())
  177. text.replaceRawString(LIBRARY->heroh->getById(mission.heroes.front())->getNameTranslated());
  178. if(!mission.artifacts.empty())
  179. {
  180. MetaString loot;
  181. for(const auto & elem : mission.artifacts)
  182. {
  183. loot.appendRawString("%s");
  184. loot.replaceName(elem);
  185. }
  186. text.replaceRawString(loot.buildList());
  187. }
  188. if(!mission.creatures.empty())
  189. {
  190. MetaString loot;
  191. for(const auto & elem : mission.creatures)
  192. {
  193. loot.appendRawString("%s");
  194. loot.replaceName(elem);
  195. }
  196. text.replaceRawString(loot.buildList());
  197. }
  198. if(mission.resources.nonZero())
  199. {
  200. MetaString loot;
  201. for(auto i : GameResID::ALL_RESOURCES())
  202. {
  203. if(mission.resources[i])
  204. {
  205. loot.appendRawString("%d %s");
  206. loot.replaceNumber(mission.resources[i]);
  207. loot.replaceName(i);
  208. }
  209. }
  210. text.replaceRawString(loot.buildList());
  211. }
  212. if(!mission.players.empty())
  213. {
  214. MetaString loot;
  215. for(auto & p : mission.players)
  216. loot.appendName(p);
  217. text.replaceRawString(loot.buildList());
  218. }
  219. if(lastDay >= 0)
  220. text.replaceNumber(lastDay - cb->getDate(Date::DAY));
  221. }
  222. void CQuest::getVisitText(const IGameInfoCallback * cb, MetaString &iwText, std::vector<Component> &components, bool firstVisit, const CGHeroInstance * h) const
  223. {
  224. bool failRequirements = (h ? !checkQuest(h) : true);
  225. mission.loadComponents(components, h);
  226. if(firstVisit)
  227. iwText.appendRawString(firstVisitText.toString());
  228. else if(failRequirements)
  229. iwText.appendRawString(nextVisitText.toString());
  230. if(lastDay >= 0)
  231. iwText.appendTextID(TextIdentifier("core", "seerhut", "time", textOption).get());
  232. addTextReplacements(cb, iwText, components);
  233. }
  234. void CQuest::getRolloverText(const IGameInfoCallback * cb, MetaString &ms, bool onHover) const
  235. {
  236. if(onHover)
  237. ms.appendRawString("\n\n");
  238. std::string questState = missionState(onHover ? 3 : 4);
  239. ms.appendTextID(TextIdentifier("core", "seerhut", "quest", questName, questState, textOption).get());
  240. std::vector<Component> components;
  241. addTextReplacements(cb, ms, components);
  242. }
  243. void CQuest::getCompletionText(const IGameInfoCallback * cb, MetaString &iwText) const
  244. {
  245. iwText.appendRawString(completedText.toString());
  246. std::vector<Component> components;
  247. addTextReplacements(cb, iwText, components);
  248. }
  249. void CQuest::defineQuestName()
  250. {
  251. //standard quests
  252. questName = CQuest::missionName(EQuestMission::NONE);
  253. if(mission.heroLevel > 0) questName = CQuest::missionName(EQuestMission::LEVEL);
  254. for(auto & s : mission.primary) if(s) questName = CQuest::missionName(EQuestMission::PRIMARY_SKILL);
  255. if(killTarget != ObjectInstanceID::NONE && !heroName.empty()) questName = CQuest::missionName(EQuestMission::KILL_HERO);
  256. if(killTarget != ObjectInstanceID::NONE && stackToKill != CreatureID::NONE) questName = CQuest::missionName(EQuestMission::KILL_CREATURE);
  257. if(!mission.artifacts.empty()) questName = CQuest::missionName(EQuestMission::ARTIFACT);
  258. if(!mission.creatures.empty()) questName = CQuest::missionName(EQuestMission::ARMY);
  259. if(mission.resources.nonZero()) questName = CQuest::missionName(EQuestMission::RESOURCES);
  260. if(!mission.heroes.empty()) questName = CQuest::missionName(EQuestMission::HERO);
  261. if(!mission.players.empty()) questName = CQuest::missionName(EQuestMission::PLAYER);
  262. if(mission.daysPassed > 0) questName = CQuest::missionName(EQuestMission::HOTA_REACH_DATE);
  263. if(!mission.heroClasses.empty()) questName = CQuest::missionName(EQuestMission::HOTA_HERO_CLASS);
  264. }
  265. void CQuest::addKillTargetReplacements(MetaString &out) const
  266. {
  267. if(!heroName.empty())
  268. out.replaceRawString(heroName);
  269. if(stackToKill != CreatureID::NONE)
  270. {
  271. out.replaceNamePlural(stackToKill);
  272. out.replaceRawString(LIBRARY->generaltexth->arraytxt[147+stackDirection]);
  273. }
  274. }
  275. void CQuest::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName)
  276. {
  277. auto q = handler.enterStruct(fieldName);
  278. handler.serializeStruct("firstVisitText", firstVisitText);
  279. handler.serializeStruct("nextVisitText", nextVisitText);
  280. handler.serializeStruct("completedText", completedText);
  281. handler.serializeBool("repeatedQuest", repeatedQuest, false);
  282. if(!handler.saving)
  283. {
  284. isCustomFirst = !firstVisitText.empty();
  285. isCustomNext = !nextVisitText.empty();
  286. isCustomComplete = !completedText.empty();
  287. }
  288. handler.serializeInt("timeLimit", lastDay, -1);
  289. handler.serializeStruct("limiter", mission);
  290. handler.serializeInstance("killTarget", killTarget, ObjectInstanceID::NONE);
  291. if(!handler.saving) //compatibility with legacy vmaps
  292. {
  293. std::string missionType = "None";
  294. handler.serializeString("missionType", missionType);
  295. if(missionType == "None")
  296. return;
  297. if(missionType == "Level")
  298. handler.serializeInt("heroLevel", mission.heroLevel);
  299. if(missionType == "PrimaryStat")
  300. {
  301. auto primarySkills = handler.enterStruct("primarySkills");
  302. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  303. handler.serializeInt(NPrimarySkill::names[i], mission.primary[i], 0);
  304. }
  305. if(missionType == "Artifact")
  306. handler.serializeIdArray<ArtifactID>("artifacts", mission.artifacts);
  307. if(missionType == "Army")
  308. {
  309. auto a = handler.enterArray("creatures");
  310. a.serializeStruct(mission.creatures);
  311. }
  312. if(missionType == "Resources")
  313. {
  314. auto r = handler.enterStruct("resources");
  315. for(size_t idx = 0; idx < (GameConstants::RESOURCE_QUANTITY - 1); idx++)
  316. {
  317. handler.serializeInt(GameConstants::RESOURCE_NAMES[idx], mission.resources[idx], 0);
  318. }
  319. }
  320. if(missionType == "Hero")
  321. {
  322. HeroTypeID temp;
  323. handler.serializeId("hero", temp, HeroTypeID::NONE);
  324. mission.heroes.emplace_back(temp);
  325. }
  326. if(missionType == "Player")
  327. {
  328. PlayerColor temp;
  329. handler.serializeId("player", temp, PlayerColor::NEUTRAL);
  330. mission.players.emplace_back(temp);
  331. }
  332. }
  333. }
  334. IQuestObject::IQuestObject()
  335. :quest(std::make_shared<CQuest>())
  336. {}
  337. IQuestObject::~IQuestObject() = default;
  338. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  339. {
  340. return getQuest().checkQuest(h);
  341. }
  342. void CGSeerHut::getVisitText(MetaString &text, std::vector<Component> &components, bool FirstVisit, const CGHeroInstance * h) const
  343. {
  344. getQuest().getVisitText(cb, text, components, FirstVisit, h);
  345. }
  346. void CGSeerHut::setObjToKill()
  347. {
  348. if(getQuest().killTarget == ObjectInstanceID::NONE)
  349. return;
  350. if(getCreatureToKill(true))
  351. {
  352. getQuest().stackToKill = getCreatureToKill(false)->getCreatureID();
  353. assert(getQuest().stackToKill != CreatureID::NONE);
  354. getQuest().stackDirection = checkDirection();
  355. }
  356. else if(getHeroToKill(true))
  357. {
  358. getQuest().heroName = getHeroToKill(false)->getNameTranslated();
  359. getQuest().heroPortrait = getHeroToKill(false)->getPortraitSource();
  360. }
  361. }
  362. void CGSeerHut::init(vstd::RNG & rand)
  363. {
  364. auto names = LIBRARY->generaltexth->findStringsWithPrefix("core.seerhut.names");
  365. auto seerNameID = *RandomGeneratorUtil::nextItem(names, rand);
  366. seerName = LIBRARY->generaltexth->translate(seerNameID);
  367. getQuest().textOption = rand.nextInt(2);
  368. getQuest().completedOption = rand.nextInt(1, 3);
  369. getQuest().mission.hasExtraCreatures = !allowsFullArmyRemoval();
  370. configuration.canRefuse = true;
  371. configuration.visitMode = Rewardable::EVisitMode::VISIT_ONCE;
  372. configuration.selectMode = Rewardable::ESelectMode::SELECT_PLAYER;
  373. }
  374. void CGSeerHut::initObj(IGameRandomizer & gameRandomizer)
  375. {
  376. init(gameRandomizer.getDefault());
  377. CRewardableObject::initObj(gameRandomizer);
  378. setObjToKill();
  379. getQuest().defineQuestName();
  380. if(getQuest().mission == Rewardable::Limiter{} && getQuest().killTarget == ObjectInstanceID::NONE)
  381. getQuest().isCompleted = true;
  382. if(getQuest().questName == getQuest().missionName(EQuestMission::NONE))
  383. {
  384. getQuest().firstVisitText.appendTextID(TextIdentifier("core", "seehut", "empty", getQuest().completedOption).get());
  385. }
  386. else
  387. {
  388. if(!getQuest().isCustomFirst)
  389. getQuest().firstVisitText.appendTextID(TextIdentifier("core", "seerhut", "quest", getQuest().questName, getQuest().missionState(0), getQuest().textOption).get());
  390. if(!getQuest().isCustomNext)
  391. getQuest().nextVisitText.appendTextID(TextIdentifier("core", "seerhut", "quest", getQuest().questName, getQuest().missionState(1), getQuest().textOption).get());
  392. if(!getQuest().isCustomComplete)
  393. getQuest().completedText.appendTextID(TextIdentifier("core", "seerhut", "quest", getQuest(). questName, getQuest().missionState(2), getQuest().textOption).get());
  394. }
  395. getQuest().getCompletionText(cb, configuration.onSelect);
  396. for(auto & i : configuration.info)
  397. getQuest().getCompletionText(cb, i.message);
  398. }
  399. void CGSeerHut::getRolloverText(MetaString &text, bool onHover) const
  400. {
  401. getQuest().getRolloverText(cb, text, onHover);
  402. if(!onHover)
  403. text.replaceRawString(seerName);
  404. }
  405. std::string CGSeerHut::getHoverText(PlayerColor player) const
  406. {
  407. std::string hoverName = getObjectName();
  408. if(ID == Obj::SEER_HUT && getQuest().activeForPlayers.count(player))
  409. {
  410. hoverName = LIBRARY->generaltexth->allTexts[347];
  411. boost::algorithm::replace_first(hoverName, "%s", seerName);
  412. }
  413. if(getQuest().activeForPlayers.count(player)
  414. && (getQuest().mission != Rewardable::Limiter{}
  415. || getQuest().killTarget != ObjectInstanceID::NONE)) //rollover when the quest is active
  416. {
  417. MetaString ms;
  418. getRolloverText (ms, true);
  419. hoverName += ms.toString();
  420. }
  421. return hoverName;
  422. }
  423. std::string CGSeerHut::getHoverText(const CGHeroInstance * hero) const
  424. {
  425. return getHoverText(hero->getOwner());
  426. }
  427. std::string CGSeerHut::getPopupText(PlayerColor player) const
  428. {
  429. return getHoverText(player);
  430. }
  431. std::string CGSeerHut::getPopupText(const CGHeroInstance * hero) const
  432. {
  433. return getHoverText(hero->getOwner());
  434. }
  435. std::vector<Component> CGSeerHut::getPopupComponents(PlayerColor player) const
  436. {
  437. std::vector<Component> result;
  438. if (getQuest().activeForPlayers.count(player))
  439. getQuest().mission.loadComponents(result, nullptr);
  440. return result;
  441. }
  442. std::vector<Component> CGSeerHut::getPopupComponents(const CGHeroInstance * hero) const
  443. {
  444. std::vector<Component> result;
  445. if (getQuest().activeForPlayers.count(hero->getOwner()))
  446. getQuest().mission.loadComponents(result, hero);
  447. return result;
  448. }
  449. void CGSeerHut::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  450. {
  451. switch(what)
  452. {
  453. case ObjProperty::SEERHUT_VISITED:
  454. {
  455. getQuest().activeForPlayers.emplace(identifier.as<PlayerColor>());
  456. break;
  457. }
  458. case ObjProperty::SEERHUT_COMPLETE:
  459. {
  460. getQuest().isCompleted = identifier.getNum();
  461. getQuest().activeForPlayers.clear();
  462. break;
  463. }
  464. }
  465. }
  466. void CGSeerHut::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  467. {
  468. CRewardableObject::newTurn(gameEvents, gameRandomizer);
  469. if(getQuest().lastDay >= 0 && getQuest().lastDay <= cb->getDate() - 1) //time is up
  470. {
  471. gameEvents.setObjPropertyValue(id, ObjProperty::SEERHUT_COMPLETE, true);
  472. }
  473. }
  474. void CGSeerHut::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  475. {
  476. InfoWindow iw;
  477. iw.player = h->getOwner();
  478. if(!getQuest().isCompleted)
  479. {
  480. bool firstVisit = !getQuest().activeForPlayers.count(h->getOwner());
  481. bool failRequirements = !checkQuest(h);
  482. if(firstVisit)
  483. {
  484. gameEvents.setObjPropertyID(id, ObjProperty::SEERHUT_VISITED, h->getOwner());
  485. AddQuest aq;
  486. aq.quest = QuestInfo(id);
  487. aq.player = h->tempOwner;
  488. gameEvents.sendAndApply(aq); //TODO: merge with setObjProperty?
  489. }
  490. if(firstVisit || failRequirements)
  491. {
  492. getVisitText (iw.text, iw.components, firstVisit, h);
  493. gameEvents.showInfoDialog(&iw);
  494. }
  495. if(!failRequirements) // propose completion, also on first visit
  496. {
  497. CRewardableObject::onHeroVisit(gameEvents, h);
  498. return;
  499. }
  500. }
  501. else
  502. {
  503. iw.text.appendRawString(LIBRARY->generaltexth->seerEmpty[getQuest().completedOption]);
  504. if (ID == Obj::SEER_HUT)
  505. iw.text.replaceRawString(seerName);
  506. gameEvents.showInfoDialog(&iw);
  507. }
  508. }
  509. int CGSeerHut::checkDirection() const
  510. {
  511. int3 cord = getCreatureToKill(false)->visitablePos();
  512. if(static_cast<double>(cord.x) / static_cast<double>(cb->getMapSize().x) < 0.34) //north
  513. {
  514. if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.34) //northwest
  515. return 8;
  516. else if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.67) //north
  517. return 1;
  518. else //northeast
  519. return 2;
  520. }
  521. else if(static_cast<double>(cord.x) / static_cast<double>(cb->getMapSize().x) < 0.67) //horizontal
  522. {
  523. if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.34) //west
  524. return 7;
  525. else if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.67) //central
  526. return 9;
  527. else //east
  528. return 3;
  529. }
  530. else //south
  531. {
  532. if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.34) //southwest
  533. return 6;
  534. else if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.67) //south
  535. return 5;
  536. else //southeast
  537. return 4;
  538. }
  539. }
  540. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  541. {
  542. const CGObjectInstance *o = cb->getObj(getQuest().killTarget);
  543. if(allowNull && !o)
  544. return nullptr;
  545. return dynamic_cast<const CGHeroInstance *>(o);
  546. }
  547. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  548. {
  549. const CGObjectInstance *o = cb->getObj(getQuest().killTarget);
  550. if(allowNull && !o)
  551. return nullptr;
  552. return dynamic_cast<const CGCreature *>(o);
  553. }
  554. bool CGSeerHut::allowsFullArmyRemoval() const
  555. {
  556. bool seerGivesUnits = !configuration.info.empty() && !configuration.info.back().reward.creatures.empty();
  557. bool h3BugSettingEnabled = cb->getSettings().getBoolean(EGameSettings::MAP_OBJECTS_H3_BUG_QUEST_TAKES_ENTIRE_ARMY);
  558. return seerGivesUnits || h3BugSettingEnabled;
  559. }
  560. void CGSeerHut::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  561. {
  562. if(answer)
  563. {
  564. getQuest().completeQuest(gameEvents, hero, allowsFullArmyRemoval());
  565. gameEvents.setObjPropertyValue(id, ObjProperty::SEERHUT_COMPLETE, !getQuest().repeatedQuest); //mission complete
  566. }
  567. CRewardableObject::blockingDialogAnswered(gameEvents, hero, answer);
  568. }
  569. void CGSeerHut::serializeJsonOptions(JsonSerializeFormat & handler)
  570. {
  571. //quest and reward
  572. CRewardableObject::serializeJsonOptions(handler);
  573. getQuest().serializeJson(handler, "quest");
  574. if(!handler.saving)
  575. {
  576. //backward compatibility for VCMI maps that use old SeerHut format
  577. auto s = handler.enterStruct("reward");
  578. const JsonNode & rewardsJson = handler.getCurrent();
  579. if (rewardsJson.Struct().empty())
  580. return;
  581. std::string fullIdentifier;
  582. std::string metaTypeName;
  583. std::string scope;
  584. std::string identifier;
  585. auto iter = rewardsJson.Struct().begin();
  586. fullIdentifier = iter->first;
  587. ModUtility::parseIdentifier(fullIdentifier, scope, metaTypeName, identifier);
  588. if(!std::set<std::string>{"resource", "primarySkill", "secondarySkill", "artifact", "spell", "creature", "experience", "mana", "morale", "luck"}.count(metaTypeName))
  589. return;
  590. int val = 0;
  591. handler.serializeInt(fullIdentifier, val);
  592. Rewardable::VisitInfo vinfo;
  593. auto & reward = vinfo.reward;
  594. if(metaTypeName == "experience")
  595. reward.heroExperience = val;
  596. if(metaTypeName == "mana")
  597. reward.manaDiff = val;
  598. if(metaTypeName == "morale")
  599. reward.heroBonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(id));
  600. if(metaTypeName == "luck")
  601. reward.heroBonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(id));
  602. if(metaTypeName == "resource")
  603. {
  604. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  605. reward.resources[rawId] = val;
  606. }
  607. if(metaTypeName == "primarySkill")
  608. {
  609. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  610. reward.primary.at(rawId) = val;
  611. }
  612. if(metaTypeName == "secondarySkill")
  613. {
  614. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  615. reward.secondary[rawId] = val;
  616. }
  617. if(metaTypeName == "artifact")
  618. {
  619. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  620. reward.grantedArtifacts.push_back(rawId);
  621. }
  622. if(metaTypeName == "spell")
  623. {
  624. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  625. reward.spells.push_back(rawId);
  626. }
  627. if(metaTypeName == "creature")
  628. {
  629. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  630. reward.creatures.emplace_back(rawId, val);
  631. }
  632. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  633. configuration.info.push_back(vinfo);
  634. }
  635. }
  636. void CGQuestGuard::init(vstd::RNG & rand)
  637. {
  638. blockVisit = true;
  639. getQuest().textOption = rand.nextInt(3, 5);
  640. getQuest().completedOption = rand.nextInt(4, 5);
  641. getQuest().mission.hasExtraCreatures = !allowsFullArmyRemoval();
  642. configuration.info.push_back({});
  643. configuration.info.back().visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  644. configuration.info.back().reward.removeObject = subID.getNum() == 0 ? true : false;
  645. configuration.canRefuse = true;
  646. }
  647. void CGQuestGuard::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  648. {
  649. if(!getQuest().isCompleted)
  650. CGSeerHut::onHeroVisit(gameEvents, h);
  651. else
  652. gameEvents.setObjPropertyValue(id, ObjProperty::SEERHUT_COMPLETE, false);
  653. }
  654. bool CGQuestGuard::passableFor(PlayerColor color) const
  655. {
  656. return getQuest().isCompleted;
  657. }
  658. void CGQuestGuard::serializeJsonOptions(JsonSerializeFormat & handler)
  659. {
  660. //quest only, do not call base class
  661. getQuest().serializeJson(handler, "quest");
  662. }
  663. bool CGKeys::wasMyColorVisited(const PlayerColor & player) const
  664. {
  665. return cb->getPlayerState(player)->visitedObjectsGlobal.count({Obj::KEYMASTER, subID}) != 0;
  666. }
  667. std::string CGKeys::getHoverText(PlayerColor player) const
  668. {
  669. return getObjectName() + "\n" + visitedTxt(wasMyColorVisited(player));
  670. }
  671. std::string CGKeys::getObjectName() const
  672. {
  673. return LIBRARY->generaltexth->tentColors[subID.getNum()] + " " + CGObjectInstance::getObjectName();
  674. }
  675. std::string CGKeys::getObjectDescription(PlayerColor player) const
  676. {
  677. return visitedTxt(wasMyColorVisited(player));
  678. }
  679. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  680. {
  681. return wasMyColorVisited (player);
  682. }
  683. void CGKeymasterTent::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  684. {
  685. int txt_id;
  686. if (!wasMyColorVisited (h->getOwner()) )
  687. {
  688. ChangeObjectVisitors cow;
  689. cow.mode = ChangeObjectVisitors::VISITOR_ADD_PLAYER;
  690. cow.hero = h->id;
  691. cow.object = id;
  692. gameEvents.sendAndApply(cow);
  693. txt_id=19;
  694. }
  695. else
  696. txt_id=20;
  697. h->showInfoDialog(gameEvents, txt_id);
  698. }
  699. void CGBorderGuard::initObj(IGameRandomizer & gameRandomizer)
  700. {
  701. blockVisit = true;
  702. }
  703. void CGBorderGuard::getVisitText(MetaString &text, std::vector<Component> &components, bool FirstVisit, const CGHeroInstance * h) const
  704. {
  705. text.appendLocalString(EMetaText::ADVOB_TXT, 18);
  706. }
  707. void CGBorderGuard::getRolloverText(MetaString &text, bool onHover) const
  708. {
  709. if (!onHover)
  710. {
  711. text.appendRawString(LIBRARY->generaltexth->tentColors[subID.getNum()]);
  712. text.appendRawString(" ");
  713. text.appendRawString(LIBRARY->objtypeh->getObjectName(Obj::KEYMASTER, subID));
  714. }
  715. }
  716. bool CGBorderGuard::checkQuest(const CGHeroInstance * h) const
  717. {
  718. return wasMyColorVisited (h->tempOwner);
  719. }
  720. void CGBorderGuard::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  721. {
  722. if (wasMyColorVisited (h->getOwner()) )
  723. {
  724. BlockingDialog bd (true, false);
  725. bd.player = h->getOwner();
  726. bd.text.appendLocalString (EMetaText::ADVOB_TXT, 17);
  727. gameEvents.showBlockingDialog (this, &bd);
  728. }
  729. else
  730. {
  731. h->showInfoDialog(gameEvents, 18);
  732. AddQuest aq;
  733. aq.quest = QuestInfo(id);
  734. aq.player = h->tempOwner;
  735. gameEvents.sendAndApply(aq);
  736. //TODO: add this quest only once OR check for multiple instances later
  737. }
  738. }
  739. void CGBorderGuard::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  740. {
  741. if (answer)
  742. gameEvents.removeObject(this, hero->getOwner());
  743. }
  744. void CGBorderGate::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const //TODO: passability
  745. {
  746. if (!wasMyColorVisited (h->getOwner()) )
  747. {
  748. h->showInfoDialog(gameEvents, 18);
  749. AddQuest aq;
  750. aq.quest = QuestInfo(id);
  751. aq.player = h->tempOwner;
  752. gameEvents.sendAndApply(aq);
  753. }
  754. }
  755. bool CGBorderGate::passableFor(PlayerColor color) const
  756. {
  757. return wasMyColorVisited(color);
  758. }
  759. VCMI_LIB_NAMESPACE_END