MiscObjects.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. /*
  2. * MiscObjects.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 "MiscObjects.h"
  12. #include "../ArtifactUtils.h"
  13. #include "../bonuses/Propagators.h"
  14. #include "../constants/StringConstants.h"
  15. #include "../CConfigHandler.h"
  16. #include "../texts/CGeneralTextHandler.h"
  17. #include "../CSoundBase.h"
  18. #include "../CSkillHandler.h"
  19. #include "../spells/CSpellHandler.h"
  20. #include "../IGameCallback.h"
  21. #include "../gameState/CGameState.h"
  22. #include "../mapping/CMap.h"
  23. #include "../CPlayerState.h"
  24. #include "../StartInfo.h"
  25. #include "../serializer/JsonSerializeFormat.h"
  26. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  27. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  28. #include "../mapObjects/CGHeroInstance.h"
  29. #include "../modding/ModScope.h"
  30. #include "../networkPacks/PacksForClient.h"
  31. #include "../networkPacks/PacksForClientBattle.h"
  32. #include "../networkPacks/StackLocation.h"
  33. #include "../lib/gameState/UpgradeInfo.h"
  34. #include <vstd/RNG.h>
  35. VCMI_LIB_NAMESPACE_BEGIN
  36. ///helpers
  37. static std::string visitedTxt(const bool visited)
  38. {
  39. int id = visited ? 352 : 353;
  40. return LIBRARY->generaltexth->allTexts[id];
  41. }
  42. void CTeamVisited::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  43. {
  44. if(what == ObjProperty::VISITED)
  45. players.insert(identifier.as<PlayerColor>());
  46. }
  47. bool CTeamVisited::wasVisited(PlayerColor player) const
  48. {
  49. return wasVisited(cb->getPlayerState(player)->team);
  50. }
  51. bool CTeamVisited::wasVisited(const CGHeroInstance * h) const
  52. {
  53. return wasVisited(h->tempOwner);
  54. }
  55. bool CTeamVisited::wasVisited(const TeamID & team) const
  56. {
  57. for(const auto & i : players)
  58. {
  59. if(cb->getPlayerState(i)->team == team)
  60. return true;
  61. }
  62. return false;
  63. }
  64. //CGMine
  65. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  66. {
  67. auto relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  68. if(relations == PlayerRelations::SAME_PLAYER) //we're visiting our mine
  69. {
  70. cb->showGarrisonDialog(id,h->id,true);
  71. return;
  72. }
  73. else if (relations == PlayerRelations::ALLIES)//ally
  74. return;
  75. if(stacksCount()) //Mine is guarded
  76. {
  77. BlockingDialog ynd(true,false);
  78. ynd.player = h->tempOwner;
  79. ynd.text.appendLocalString(EMetaText::ADVOB_TXT, isAbandoned() ? 84 : 187);
  80. cb->showBlockingDialog(this, &ynd);
  81. return;
  82. }
  83. flagMine(h->tempOwner);
  84. }
  85. void CGMine::initObj(vstd::RNG & rand)
  86. {
  87. if(isAbandoned())
  88. {
  89. //set guardians
  90. int howManyTroglodytes = rand.nextInt(100, 199);
  91. auto * troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  92. putStack(SlotID(0), troglodytes);
  93. assert(!abandonedMineResources.empty());
  94. if (!abandonedMineResources.empty())
  95. {
  96. producedResource = *RandomGeneratorUtil::nextItem(abandonedMineResources, rand);
  97. }
  98. else
  99. {
  100. logGlobal->error("Abandoned mine at (%s) has no valid resource candidates!", anchorPos().toString());
  101. producedResource = GameResID::GOLD;
  102. }
  103. }
  104. else
  105. {
  106. producedResource = GameResID(getObjTypeIndex().getNum());
  107. }
  108. producedQuantity = defaultResProduction();
  109. }
  110. bool CGMine::isAbandoned() const
  111. {
  112. return subID.getNum() >= 7;
  113. }
  114. const IOwnableObject * CGMine::asOwnable() const
  115. {
  116. return this;
  117. }
  118. std::vector<CreatureID> CGMine::providedCreatures() const
  119. {
  120. return {};
  121. }
  122. ResourceSet CGMine::dailyIncome() const
  123. {
  124. ResourceSet result;
  125. result[producedResource] += defaultResProduction();
  126. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  127. result.applyHandicap(playerSettings->handicap.percentIncome);
  128. return result;
  129. }
  130. std::string CGMine::getObjectName() const
  131. {
  132. return LIBRARY->generaltexth->translate("core.minename", getObjTypeIndex());
  133. }
  134. std::string CGMine::getHoverText(PlayerColor player) const
  135. {
  136. std::string hoverName = CArmedInstance::getHoverText(player);
  137. if (tempOwner != PlayerColor::NEUTRAL)
  138. hoverName += "\n(" + LIBRARY->generaltexth->restypes[producedResource.getNum()] + ")";
  139. if(stacksCount())
  140. {
  141. hoverName += "\n";
  142. hoverName += LIBRARY->generaltexth->allTexts[202]; //Guarded by
  143. hoverName += " ";
  144. hoverName += getArmyDescription();
  145. }
  146. return hoverName;
  147. }
  148. void CGMine::flagMine(const PlayerColor & player) const
  149. {
  150. assert(tempOwner != player);
  151. cb->setOwner(this, player); //not ours? flag it!
  152. InfoWindow iw;
  153. iw.type = EInfoWindowMode::AUTO;
  154. iw.text.appendTextID(TextIdentifier("core.mineevnt", producedResource.getNum()).get()); //not use subID, abandoned mines uses default mine texts
  155. iw.player = player;
  156. iw.components.emplace_back(ComponentType::RESOURCE_PER_DAY, producedResource, getProducedQuantity());
  157. cb->showInfoDialog(&iw);
  158. }
  159. ui32 CGMine::defaultResProduction() const
  160. {
  161. switch(producedResource.toEnum())
  162. {
  163. case EGameResID::WOOD:
  164. case EGameResID::ORE:
  165. return 2;
  166. case EGameResID::GOLD:
  167. return 1000;
  168. default:
  169. return 1;
  170. }
  171. }
  172. ui32 CGMine::getProducedQuantity() const
  173. {
  174. auto * playerSettings = cb->getPlayerSettings(getOwner());
  175. // always round up income - we don't want mines to always produce zero if handicap in use
  176. return vstd::divideAndCeil(producedQuantity * playerSettings->handicap.percentIncome, 100);
  177. }
  178. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  179. {
  180. if(result.winner == BattleSide::ATTACKER) //attacker won
  181. {
  182. if(isAbandoned())
  183. {
  184. hero->showInfoDialog(85);
  185. }
  186. flagMine(hero->tempOwner);
  187. }
  188. }
  189. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  190. {
  191. if(answer)
  192. cb->startBattle(hero, this);
  193. }
  194. void CGMine::serializeJsonOptions(JsonSerializeFormat & handler)
  195. {
  196. CArmedInstance::serializeJsonOptions(handler);
  197. serializeJsonOwner(handler);
  198. if(isAbandoned())
  199. {
  200. if(handler.saving)
  201. {
  202. JsonNode node;
  203. for(const auto & resID : abandonedMineResources)
  204. node.Vector().emplace_back(GameConstants::RESOURCE_NAMES[resID.getNum()]);
  205. handler.serializeRaw("possibleResources", node, std::nullopt);
  206. }
  207. else
  208. {
  209. auto guard = handler.enterArray("possibleResources");
  210. const JsonNode & node = handler.getCurrent();
  211. auto names = node.convertTo<std::vector<std::string>>();
  212. for(const std::string & s : names)
  213. {
  214. int raw_res = vstd::find_pos(GameConstants::RESOURCE_NAMES, s);
  215. if(raw_res < 0)
  216. logGlobal->error("Invalid resource name: %s", s);
  217. else
  218. abandonedMineResources.emplace(raw_res);
  219. }
  220. }
  221. }
  222. }
  223. bool CGTeleport::isEntrance() const
  224. {
  225. return type == BOTH || type == ENTRANCE;
  226. }
  227. bool CGTeleport::isExit() const
  228. {
  229. return type == BOTH || type == EXIT;
  230. }
  231. bool CGTeleport::isChannelEntrance(const ObjectInstanceID & id) const
  232. {
  233. return vstd::contains(getAllEntrances(), id);
  234. }
  235. bool CGTeleport::isChannelExit(const ObjectInstanceID & id) const
  236. {
  237. return vstd::contains(getAllExits(), id);
  238. }
  239. std::vector<ObjectInstanceID> CGTeleport::getAllEntrances(bool excludeCurrent) const
  240. {
  241. auto ret = cb->getTeleportChannelEntrances(channel);
  242. if(excludeCurrent)
  243. vstd::erase_if_present(ret, id);
  244. return ret;
  245. }
  246. std::vector<ObjectInstanceID> CGTeleport::getAllExits(bool excludeCurrent) const
  247. {
  248. auto ret = cb->getTeleportChannelExits(channel);
  249. if(excludeCurrent)
  250. vstd::erase_if_present(ret, id);
  251. return ret;
  252. }
  253. ObjectInstanceID CGTeleport::getRandomExit(const CGHeroInstance * h) const
  254. {
  255. auto passableExits = getPassableExits(cb->gameState(), h, getAllExits(true));
  256. if(!passableExits.empty())
  257. return *RandomGeneratorUtil::nextItem(passableExits, cb->gameState()->getRandomGenerator());
  258. return ObjectInstanceID();
  259. }
  260. bool CGTeleport::isTeleport(const CGObjectInstance * obj)
  261. {
  262. return dynamic_cast<const CGTeleport *>(obj) != nullptr;
  263. }
  264. bool CGTeleport::isConnected(const CGTeleport * src, const CGTeleport * dst)
  265. {
  266. return src && dst && src->isChannelExit(dst->id);
  267. }
  268. bool CGTeleport::isConnected(const CGObjectInstance * src, const CGObjectInstance * dst)
  269. {
  270. const auto * srcObj = dynamic_cast<const CGTeleport *>(src);
  271. const auto * dstObj = dynamic_cast<const CGTeleport *>(dst);
  272. return isConnected(srcObj, dstObj);
  273. }
  274. bool CGTeleport::isExitPassable(CGameState * gs, const CGHeroInstance * h, const CGObjectInstance * obj)
  275. {
  276. auto * objTopVisObj = gs->getMap().getTile(obj->visitablePos()).topVisitableObj();
  277. if(objTopVisObj->ID == Obj::HERO)
  278. {
  279. if(h->id == objTopVisObj->id) // Just to be sure it's won't happen.
  280. return false;
  281. // Check if it's friendly hero or not
  282. if(gs->getPlayerRelations(h->tempOwner, objTopVisObj->tempOwner) != PlayerRelations::ENEMIES)
  283. {
  284. // Exchange between heroes only possible via subterranean gates
  285. if(!dynamic_cast<const CGSubterraneanGate *>(obj))
  286. return false;
  287. }
  288. }
  289. return true;
  290. }
  291. std::vector<ObjectInstanceID> CGTeleport::getPassableExits(CGameState * gs, const CGHeroInstance * h, std::vector<ObjectInstanceID> exits)
  292. {
  293. vstd::erase_if(exits, [&](const ObjectInstanceID & exit) -> bool
  294. {
  295. return !isExitPassable(gs, h, gs->getObj(exit));
  296. });
  297. return exits;
  298. }
  299. void CGTeleport::addToChannel(std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > &channelsList, const CGTeleport * obj)
  300. {
  301. std::shared_ptr<TeleportChannel> tc;
  302. if(channelsList.find(obj->channel) == channelsList.end())
  303. {
  304. tc = std::make_shared<TeleportChannel>();
  305. channelsList.insert(std::make_pair(obj->channel, tc));
  306. }
  307. else
  308. tc = channelsList[obj->channel];
  309. if(obj->isEntrance() && !vstd::contains(tc->entrances, obj->id))
  310. tc->entrances.push_back(obj->id);
  311. if(obj->isExit() && !vstd::contains(tc->exits, obj->id))
  312. tc->exits.push_back(obj->id);
  313. if(!tc->entrances.empty() && !tc->exits.empty()
  314. && (tc->entrances.size() != 1 || tc->entrances != tc->exits))
  315. {
  316. tc->passability = TeleportChannel::PASSABLE;
  317. }
  318. }
  319. TeleportChannelID CGMonolith::findMeChannel(const std::vector<Obj> & IDs, MapObjectSubID SubID) const
  320. {
  321. for(auto teleportObj : cb->gameState()->getMap().getObjects<CGMonolith>())
  322. {
  323. if(vstd::contains(IDs, teleportObj->ID) && teleportObj->subID == SubID)
  324. return teleportObj->channel;
  325. }
  326. return TeleportChannelID();
  327. }
  328. void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const
  329. {
  330. TeleportDialog td(h->id, channel);
  331. if(isEntrance())
  332. {
  333. if(cb->isTeleportChannelBidirectional(channel) && 1 < cb->getTeleportChannelExits(channel).size())
  334. {
  335. auto exits = cb->getTeleportChannelExits(channel);
  336. for(const auto & exit : exits)
  337. {
  338. td.exits.push_back(std::make_pair(exit, cb->getObj(exit)->visitablePos()));
  339. }
  340. }
  341. if(cb->isTeleportChannelImpassable(channel))
  342. {
  343. logGlobal->debug("Cannot find corresponding exit monolith for %d at %s", id.getNum(), anchorPos().toString());
  344. td.impassable = true;
  345. }
  346. else if(getRandomExit(h) == ObjectInstanceID())
  347. logGlobal->debug("All exits blocked for monolith %d at %s", id.getNum(), anchorPos().toString());
  348. }
  349. else
  350. h->showInfoDialog(70);
  351. cb->showTeleportDialog(&td);
  352. }
  353. void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  354. {
  355. int3 dPos;
  356. auto randomExit = getRandomExit(hero);
  357. auto realExits = getAllExits(true);
  358. if(!isEntrance() // Do nothing if hero visited exit only object
  359. || (exits.empty() && realExits.empty()) // Do nothing if there no exits on this channel
  360. || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate
  361. {
  362. return;
  363. }
  364. else if(vstd::isValidIndex(exits, answer))
  365. dPos = exits[answer].second;
  366. else
  367. dPos = cb->getObj(randomExit)->visitablePos();
  368. cb->moveHero(hero->id, hero->convertFromVisitablePos(dPos), EMovementMode::MONOLITH);
  369. }
  370. void CGMonolith::initObj(vstd::RNG & rand)
  371. {
  372. std::vector<Obj> IDs;
  373. IDs.push_back(ID);
  374. switch(ID.toEnum())
  375. {
  376. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  377. type = ENTRANCE;
  378. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_EXIT);
  379. break;
  380. case Obj::MONOLITH_ONE_WAY_EXIT:
  381. type = EXIT;
  382. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_ENTRANCE);
  383. break;
  384. case Obj::MONOLITH_TWO_WAY:
  385. default:
  386. type = BOTH;
  387. break;
  388. }
  389. channel = findMeChannel(IDs, subID);
  390. if(channel == TeleportChannelID())
  391. channel = TeleportChannelID(static_cast<si32>(cb->gameState()->getMap().teleportChannels.size()));
  392. addToChannel(cb->gameState()->getMap().teleportChannels, this);
  393. }
  394. void CGSubterraneanGate::onHeroVisit( const CGHeroInstance * h ) const
  395. {
  396. TeleportDialog td(h->id, channel);
  397. if(cb->isTeleportChannelImpassable(channel))
  398. {
  399. h->showInfoDialog(153);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  400. logGlobal->debug("Cannot find exit subterranean gate for %d at %s", id.getNum(), anchorPos().toString());
  401. td.impassable = true;
  402. }
  403. else
  404. {
  405. auto exit = getRandomExit(h);
  406. td.exits.push_back(std::make_pair(exit, cb->getObj(exit)->visitablePos()));
  407. }
  408. cb->showTeleportDialog(&td);
  409. }
  410. void CGSubterraneanGate::initObj(vstd::RNG & rand)
  411. {
  412. type = BOTH;
  413. }
  414. void CGSubterraneanGate::postInit(IGameCallback * cb) //matches subterranean gates into pairs
  415. {
  416. //split on underground and surface gates
  417. std::vector<CGSubterraneanGate *> gatesSplit[2]; //surface and underground gates
  418. for(auto gate : cb->gameState()->getMap().getObjects<CGSubterraneanGate>())
  419. {
  420. gatesSplit[gate->visitablePos().z].push_back(gate);
  421. }
  422. //sort by position
  423. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  424. {
  425. return a->visitablePos() < b->visitablePos();
  426. });
  427. auto assignToChannel = [&](CGSubterraneanGate * obj)
  428. {
  429. if(obj->channel == TeleportChannelID())
  430. { // if object not linked to channel then create new channel
  431. obj->channel = TeleportChannelID(static_cast<si32>(cb->gameState()->getMap().teleportChannels.size()));
  432. addToChannel(cb->gameState()->getMap().teleportChannels, obj);
  433. }
  434. };
  435. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  436. {
  437. CGSubterraneanGate * objCurrent = gatesSplit[0][i];
  438. //find nearest underground exit
  439. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  440. for(int j = 0; j < gatesSplit[1].size(); j++)
  441. {
  442. CGSubterraneanGate *checked = gatesSplit[1][j];
  443. if(checked->channel != TeleportChannelID())
  444. continue;
  445. si32 hlp = checked->visitablePos().dist2dSQ(objCurrent->visitablePos());
  446. if(hlp < best.second)
  447. {
  448. best.first = j;
  449. best.second = hlp;
  450. }
  451. }
  452. assignToChannel(objCurrent);
  453. if(best.first >= 0) //found pair
  454. {
  455. gatesSplit[1][best.first]->channel = objCurrent->channel;
  456. addToChannel(cb->gameState()->getMap().teleportChannels, gatesSplit[1][best.first]);
  457. }
  458. }
  459. // we should assign empty channels to underground gates if they don't have matching overground gates
  460. for(auto & i : gatesSplit[1])
  461. assignToChannel(i);
  462. }
  463. void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const
  464. {
  465. TeleportDialog td(h->id, channel);
  466. if(cb->isTeleportChannelImpassable(channel))
  467. {
  468. logGlobal->debug("Cannot find exit whirlpool for %d at %s", id.getNum(), anchorPos().toString());
  469. td.impassable = true;
  470. }
  471. else if(getRandomExit(h) == ObjectInstanceID())
  472. logGlobal->debug("All exits are blocked for whirlpool %d at %s", id.getNum(), anchorPos().toString());
  473. if(!isProtected(h))
  474. {
  475. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  476. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  477. {
  478. if(h->getPower(targetstack) > h->getPower(i->first))
  479. targetstack = (i->first);
  480. }
  481. auto countToTake = static_cast<TQuantity>(h->getStackCount(targetstack) * 0.5);
  482. vstd::amax(countToTake, 1);
  483. InfoWindow iw;
  484. iw.type = EInfoWindowMode::AUTO;
  485. iw.player = h->tempOwner;
  486. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 168);
  487. iw.components.emplace_back(ComponentType::CREATURE, h->getCreature(targetstack)->getId(), -countToTake);
  488. cb->showInfoDialog(&iw);
  489. cb->changeStackCount(StackLocation(h->id, targetstack), -countToTake);
  490. }
  491. else
  492. {
  493. auto exits = getAllExits();
  494. for(const auto & exit : exits)
  495. {
  496. auto blockedPosList = cb->getObj(exit)->getBlockedPos();
  497. for(const auto & bPos : blockedPosList)
  498. td.exits.push_back(std::make_pair(exit, bPos));
  499. }
  500. }
  501. cb->showTeleportDialog(&td);
  502. }
  503. void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  504. {
  505. int3 dPos;
  506. auto realExits = getAllExits();
  507. if(exits.empty() && realExits.empty())
  508. return;
  509. else if(vstd::isValidIndex(exits, answer))
  510. dPos = exits[answer].second;
  511. else
  512. {
  513. auto exit = getRandomExit(hero);
  514. if(exit == ObjectInstanceID())
  515. return;
  516. const auto * obj = cb->getObj(exit);
  517. std::set<int3> tiles = obj->getBlockedPos();
  518. dPos = *RandomGeneratorUtil::nextItem(tiles, cb->gameState()->getRandomGenerator());
  519. }
  520. cb->moveHero(hero->id, hero->convertFromVisitablePos(dPos), EMovementMode::MONOLITH);
  521. }
  522. bool CGWhirlpool::isProtected(const CGHeroInstance * h)
  523. {
  524. return h->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION)
  525. || (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1)
  526. || (h->stacksCount() == 0 && h->getCommander() && h->getCommander()->alive);
  527. }
  528. ArtifactID CGArtifact::getArtifact() const
  529. {
  530. if(ID == Obj::SPELL_SCROLL)
  531. return ArtifactID::SPELL_SCROLL;
  532. else
  533. return getObjTypeIndex().getNum();
  534. }
  535. void CGArtifact::pickRandomObject(vstd::RNG & rand)
  536. {
  537. switch(ID.toEnum())
  538. {
  539. case MapObjectID::RANDOM_ART:
  540. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC);
  541. break;
  542. case MapObjectID::RANDOM_TREASURE_ART:
  543. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_TREASURE);
  544. break;
  545. case MapObjectID::RANDOM_MINOR_ART:
  546. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_MINOR);
  547. break;
  548. case MapObjectID::RANDOM_MAJOR_ART:
  549. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_MAJOR);
  550. break;
  551. case MapObjectID::RANDOM_RELIC_ART:
  552. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_RELIC);
  553. break;
  554. }
  555. if (ID != MapObjectID::SPELL_SCROLL && ID != MapObjectID::ARTIFACT)
  556. {
  557. ID = MapObjectID::ARTIFACT;
  558. setType(ID, subID);
  559. }
  560. else if (ID != MapObjectID::SPELL_SCROLL)
  561. ID = MapObjectID::ARTIFACT;
  562. }
  563. void CGArtifact::initObj(vstd::RNG & rand)
  564. {
  565. blockVisit = true;
  566. if(ID == Obj::ARTIFACT)
  567. {
  568. if (!storedArtifact)
  569. storedArtifact = cb->gameState()->createArtifact(ArtifactID());
  570. if(!storedArtifact->getType())
  571. storedArtifact->setType(getArtifact().toArtifact());
  572. }
  573. if(ID == Obj::SPELL_SCROLL)
  574. subID = 1;
  575. assert(storedArtifact->getType());
  576. assert(!storedArtifact->getParentNodes().empty());
  577. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  578. }
  579. std::string CGArtifact::getObjectName() const
  580. {
  581. return LIBRARY->artifacts()->getById(getArtifact())->getNameTranslated();
  582. }
  583. std::string CGArtifact::getPopupText(PlayerColor player) const
  584. {
  585. if (settings["general"]["enableUiEnhancements"].Bool())
  586. {
  587. std::string description = LIBRARY->artifacts()->getById(getArtifact())->getDescriptionTranslated();
  588. if (getArtifact() == ArtifactID::SPELL_SCROLL)
  589. ArtifactUtils::insertScrrollSpellName(description, SpellID::NONE); // erase text placeholder
  590. return description;
  591. }
  592. else
  593. return getObjectName();
  594. }
  595. std::string CGArtifact::getPopupText(const CGHeroInstance * hero) const
  596. {
  597. return getPopupText(hero->getOwner());
  598. }
  599. std::vector<Component> CGArtifact::getPopupComponents(PlayerColor player) const
  600. {
  601. return {
  602. Component(ComponentType::ARTIFACT, getArtifact())
  603. };
  604. }
  605. void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
  606. {
  607. if(!stacksCount())
  608. {
  609. InfoWindow iw;
  610. iw.type = EInfoWindowMode::AUTO;
  611. iw.player = h->tempOwner;
  612. if(storedArtifact->getType()->canBePutAt(h))
  613. {
  614. switch (ID.toEnum())
  615. {
  616. case Obj::ARTIFACT:
  617. {
  618. iw.components.emplace_back(ComponentType::ARTIFACT, getArtifact());
  619. if(!message.empty())
  620. iw.text = message;
  621. else
  622. iw.text.appendTextID(getArtifact().toArtifact()->getEventTextID());
  623. }
  624. break;
  625. case Obj::SPELL_SCROLL:
  626. {
  627. SpellID spell = storedArtifact->getScrollSpellID();
  628. iw.components.emplace_back(ComponentType::SPELL, spell);
  629. if(!message.empty())
  630. iw.text = message;
  631. else
  632. {
  633. iw.text.appendLocalString(EMetaText::ADVOB_TXT,135);
  634. iw.text.replaceName(spell);
  635. }
  636. }
  637. break;
  638. }
  639. }
  640. else
  641. {
  642. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 2);
  643. }
  644. cb->showInfoDialog(&iw);
  645. pick(h);
  646. }
  647. else
  648. {
  649. switch(ID.toEnum())
  650. {
  651. case Obj::ARTIFACT:
  652. {
  653. BlockingDialog ynd(true,false);
  654. ynd.player = h->getOwner();
  655. if(!message.empty())
  656. ynd.text = message;
  657. else
  658. {
  659. // TODO: Guard text is more complex in H3, see mantis issue 2325 for details
  660. ynd.text.appendLocalString(EMetaText::GENERAL_TXT, 420);
  661. ynd.text.replaceRawString("");
  662. ynd.text.replaceRawString(getArmyDescription());
  663. ynd.text.replaceLocalString(EMetaText::GENERAL_TXT, 43); // creatures
  664. }
  665. cb->showBlockingDialog(this, &ynd);
  666. }
  667. break;
  668. case Obj::SPELL_SCROLL:
  669. {
  670. if(!message.empty())
  671. {
  672. BlockingDialog ynd(true,false);
  673. ynd.player = h->getOwner();
  674. ynd.text = message;
  675. cb->showBlockingDialog(this, &ynd);
  676. }
  677. else
  678. blockingDialogAnswered(h, true);
  679. }
  680. break;
  681. }
  682. }
  683. }
  684. void CGArtifact::pick(const CGHeroInstance * h) const
  685. {
  686. if(cb->putArtifact(ArtifactLocation(h->id, ArtifactPosition::FIRST_AVAILABLE), storedArtifact->getId()))
  687. cb->removeObject(this, h->getOwner());
  688. }
  689. BattleField CGArtifact::getBattlefield() const
  690. {
  691. return BattleField::NONE;
  692. }
  693. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  694. {
  695. if(result.winner == BattleSide::ATTACKER) //attacker won
  696. pick(hero);
  697. }
  698. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  699. {
  700. if(answer)
  701. cb->startBattle(hero, this);
  702. }
  703. void CGArtifact::serializeJsonOptions(JsonSerializeFormat& handler)
  704. {
  705. handler.serializeStruct("guardMessage", message);
  706. CArmedInstance::serializeJsonOptions(handler);
  707. if(!handler.saving && !handler.getCurrent()["guards"].Vector().empty())
  708. CCreatureSet::serializeJson(handler, "guards", 7);
  709. if(handler.saving && ID == Obj::SPELL_SCROLL)
  710. {
  711. const auto & b = storedArtifact->getFirstBonus(Selector::type()(BonusType::SPELL));
  712. SpellID spellId(b->subtype.as<SpellID>());
  713. handler.serializeId("spell", spellId, SpellID::NONE);
  714. }
  715. }
  716. void CGSignBottle::initObj(vstd::RNG & rand)
  717. {
  718. //if no text is set than we pick random from the predefined ones
  719. if(message.empty())
  720. {
  721. auto vector = LIBRARY->generaltexth->findStringsWithPrefix("core.randsign");
  722. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  723. message.appendTextID(messageIdentifier);
  724. }
  725. if(ID == Obj::OCEAN_BOTTLE)
  726. {
  727. blockVisit = true;
  728. }
  729. }
  730. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  731. {
  732. InfoWindow iw;
  733. iw.player = h->getOwner();
  734. iw.text = message;
  735. cb->showInfoDialog(&iw);
  736. if(ID == Obj::OCEAN_BOTTLE)
  737. cb->removeObject(this, h->getOwner());
  738. }
  739. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  740. {
  741. handler.serializeStruct("text", message);
  742. }
  743. const IOwnableObject * CGGarrison::asOwnable() const
  744. {
  745. return this;
  746. }
  747. ResourceSet CGGarrison::dailyIncome() const
  748. {
  749. return {};
  750. }
  751. std::vector<CreatureID> CGGarrison::providedCreatures() const
  752. {
  753. return {};
  754. }
  755. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  756. {
  757. auto relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  758. if (relations == PlayerRelations::ENEMIES && stacksCount() > 0) {
  759. //TODO: Find a way to apply magic garrison effects in battle.
  760. cb->startBattle(h, this);
  761. return;
  762. }
  763. //New owner.
  764. if (relations == PlayerRelations::ENEMIES)
  765. cb->setOwner(this, h->tempOwner);
  766. cb->showGarrisonDialog(id, h->id, removableUnits);
  767. }
  768. bool CGGarrison::passableFor(PlayerColor player) const
  769. {
  770. //FIXME: identical to same method in CGTownInstance
  771. if ( !stacksCount() )//empty - anyone can visit
  772. return true;
  773. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  774. return false;
  775. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  776. return true;
  777. return false;
  778. }
  779. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  780. {
  781. if (result.winner == BattleSide::ATTACKER)
  782. onHeroVisit(hero);
  783. }
  784. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  785. {
  786. handler.serializeBool("removableUnits", removableUnits);
  787. serializeJsonOwner(handler);
  788. CArmedInstance::serializeJsonOptions(handler);
  789. }
  790. void CGGarrison::initObj(vstd::RNG &rand)
  791. {
  792. if(this->subID == MapObjectSubID::decode(this->ID, "antiMagic"))
  793. addAntimagicGarrisonBonus();
  794. }
  795. void CGGarrison::addAntimagicGarrisonBonus()
  796. {
  797. auto bonus = std::make_shared<Bonus>();
  798. bonus->type = BonusType::BLOCK_ALL_MAGIC;
  799. bonus->source = BonusSource::OBJECT_TYPE;
  800. bonus->sid = BonusSourceID(this->ID);
  801. bonus->propagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE);
  802. bonus->duration = BonusDuration::PERMANENT;
  803. this->addNewBonus(bonus);
  804. }
  805. void CGMagi::initObj(vstd::RNG & rand)
  806. {
  807. if (ID == Obj::EYE_OF_MAGI)
  808. blockVisit = true;
  809. }
  810. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  811. {
  812. if (ID == Obj::HUT_OF_MAGI)
  813. {
  814. h->showInfoDialog(61);
  815. std::vector<const CGObjectInstance *> eyes;
  816. for (const auto & object : cb->gameState()->getMap().getObjects<CGMagi>())
  817. {
  818. if (object->ID == Obj::EYE_OF_MAGI && object->subID == this->subID)
  819. eyes.push_back(object);
  820. }
  821. if (!eyes.empty())
  822. {
  823. CenterView cv;
  824. cv.player = h->tempOwner;
  825. cv.focusTime = 2000;
  826. FoWChange fw;
  827. fw.player = h->tempOwner;
  828. fw.mode = ETileVisibility::REVEALED;
  829. fw.waitForDialogs = true;
  830. for(const auto & eye : eyes)
  831. {
  832. cb->getTilesInRange (fw.tiles, eye->visitablePos(), 10, ETileVisibility::HIDDEN, h->tempOwner);
  833. cb->sendAndApply(fw);
  834. cv.pos = eye->visitablePos();
  835. cb->sendAndApply(cv);
  836. }
  837. cv.pos = h->visitablePos();
  838. cv.focusTime = 0;
  839. cb->sendAndApply(cv);
  840. }
  841. }
  842. else if (ID == Obj::EYE_OF_MAGI)
  843. {
  844. h->showInfoDialog(48);
  845. }
  846. }
  847. CGBoat::CGBoat(IGameCallback * cb)
  848. : CGObjectInstance(cb)
  849. {
  850. direction = 4;
  851. layer = EPathfindingLayer::SAIL;
  852. }
  853. bool CGBoat::isCoastVisitable() const
  854. {
  855. return true;
  856. }
  857. void CGBoat::setBoardedHero(const CGHeroInstance * hero)
  858. {
  859. if (hero)
  860. boardedHeroID = hero->id;
  861. else
  862. boardedHeroID = ObjectInstanceID();
  863. }
  864. const CGHeroInstance * CGBoat::getBoardedHero() const
  865. {
  866. if (boardedHeroID.hasValue())
  867. return cb->getHero(boardedHeroID);
  868. else
  869. return nullptr;
  870. }
  871. void CGSirens::initObj(vstd::RNG & rand)
  872. {
  873. blockVisit = true;
  874. }
  875. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  876. {
  877. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID)));
  878. }
  879. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  880. {
  881. InfoWindow iw;
  882. iw.player = h->tempOwner;
  883. if(h->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID))) //has already visited Sirens
  884. {
  885. iw.type = EInfoWindowMode::AUTO;
  886. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  887. }
  888. else
  889. {
  890. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  891. TExpType xp = 0;
  892. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  893. {
  894. // 1-sized stacks are not affected by sirens
  895. if (i->second->count == 1)
  896. continue;
  897. // tested H3 behavior: 30% (rounded up) of stack drowns
  898. TQuantity drown = std::ceil(i->second->count * 0.3);
  899. if(drown)
  900. {
  901. cb->changeStackCount(StackLocation(h->id, i->first), -drown);
  902. xp += drown * i->second->getType()->getMaxHealth();
  903. }
  904. }
  905. if(xp)
  906. {
  907. xp = h->calculateXp(static_cast<int>(xp));
  908. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  909. iw.text.replaceNumber(static_cast<int>(xp));
  910. cb->giveExperience(h, xp);
  911. }
  912. else
  913. {
  914. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  915. }
  916. }
  917. cb->showInfoDialog(&iw);
  918. }
  919. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  920. {
  921. // H J L K I
  922. // A x S x B
  923. // C E G F D
  924. offsets = {
  925. {-2, 0, 0}, // A
  926. {+2, 0, 0}, // B
  927. {-2, 1, 0}, // C
  928. {+2, 1, 0}, // D
  929. {-1, 1, 0}, // E
  930. {+1, 1, 0}, // F
  931. {0, 1, 0}, // G
  932. {-2, -1, 0}, // H
  933. {+2, -1, 0}, // I
  934. {-1, -1, 0}, // G
  935. {+1, -1, 0}, // K
  936. {0, -1, 0}, // L
  937. };
  938. }
  939. const IObjectInterface * CGShipyard::getObject() const
  940. {
  941. return this;
  942. }
  943. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  944. {
  945. if(cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner) == PlayerRelations::ENEMIES)
  946. cb->setOwner(this, h->tempOwner);
  947. if(shipyardStatus() != IBoatGenerator::GOOD)
  948. {
  949. InfoWindow iw;
  950. iw.type = EInfoWindowMode::AUTO;
  951. iw.player = tempOwner;
  952. getProblemText(iw.text, h);
  953. cb->showInfoDialog(&iw);
  954. }
  955. else
  956. {
  957. cb->showObjectWindow(this, EOpenWindowMode::SHIPYARD_WINDOW, h, false);
  958. }
  959. }
  960. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  961. {
  962. serializeJsonOwner(handler);
  963. }
  964. BoatId CGShipyard::getBoatType() const
  965. {
  966. return createdBoat;
  967. }
  968. const IOwnableObject * CGShipyard::asOwnable() const
  969. {
  970. return this;
  971. }
  972. ResourceSet CGShipyard::dailyIncome() const
  973. {
  974. return {};
  975. }
  976. std::vector<CreatureID> CGShipyard::providedCreatures() const
  977. {
  978. return {};
  979. }
  980. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  981. {
  982. cb->showObjectWindow(this, EOpenWindowMode::THIEVES_GUILD, h, false);
  983. }
  984. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  985. {
  986. InfoWindow iw;
  987. iw.type = EInfoWindowMode::AUTO;
  988. iw.player = h->tempOwner;
  989. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  990. assert(ts);
  991. TeamID team = ts->id;
  992. if(!wasVisited(team))
  993. {
  994. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  995. cb->sendAndApply(iw);
  996. // increment general visited obelisks counter
  997. cb->setObjPropertyID(id, ObjProperty::OBELISK_VISITED, team);
  998. cb->showObjectWindow(this, EOpenWindowMode::PUZZLE_MAP, h, false);
  999. // mark that particular obelisk as visited for all players in the team
  1000. for(const auto & color : ts->players)
  1001. {
  1002. cb->setObjPropertyID(id, ObjProperty::VISITED, color);
  1003. }
  1004. }
  1005. else
  1006. {
  1007. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  1008. cb->sendAndApply(iw);
  1009. }
  1010. }
  1011. void CGObelisk::initObj(vstd::RNG & rand)
  1012. {
  1013. cb->gameState()->getMap().obeliskCount++;
  1014. }
  1015. std::string CGObelisk::getHoverText(PlayerColor player) const
  1016. {
  1017. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1018. }
  1019. std::string CGObelisk::getObjectDescription(PlayerColor player) const
  1020. {
  1021. return visitedTxt(wasVisited(player));
  1022. }
  1023. void CGObelisk::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  1024. {
  1025. switch(what)
  1026. {
  1027. case ObjProperty::OBELISK_VISITED:
  1028. {
  1029. auto progress = ++cb->gameState()->getMap().obelisksVisited[identifier.as<TeamID>()];
  1030. logGlobal->debug("Player %d: obelisk progress %d / %d", identifier.getNum(), static_cast<int>(progress) , static_cast<int>(cb->gameState()->getMap().obeliskCount));
  1031. if(progress > cb->gameState()->getMap().obeliskCount)
  1032. {
  1033. logGlobal->error("Visited %d of %d", static_cast<int>(progress), cb->gameState()->getMap().obeliskCount);
  1034. throw std::runtime_error("Player visited " + std::to_string(progress) + " obelisks out of " + std::to_string(cb->gameState()->getMap().obeliskCount) + " present on map!");
  1035. }
  1036. break;
  1037. }
  1038. default:
  1039. CTeamVisited::setPropertyDer(what, identifier);
  1040. break;
  1041. }
  1042. }
  1043. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1044. {
  1045. cb->showObjectWindow(this, EOpenWindowMode::HILL_FORT_WINDOW, h, false);
  1046. }
  1047. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1048. {
  1049. int32_t level = stack.getType()->getLevel();
  1050. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1051. int costModifier = upgradeCostPercentage[index];
  1052. for(const auto & nid : stack.getCreature()->upgrades)
  1053. {
  1054. info.addUpgrade(nid, stack.getType(), costModifier);
  1055. }
  1056. }
  1057. std::string HillFort::getPopupText(PlayerColor player) const
  1058. {
  1059. MetaString message = MetaString::createFromRawString("{%s}\r\n\r\n%s");
  1060. message.replaceName(ID, subID);
  1061. message.replaceTextID(getDescriptionToolTip());
  1062. return message.toString();
  1063. }
  1064. std::string HillFort::getPopupText(const CGHeroInstance * hero) const
  1065. {
  1066. return getPopupText(hero->getOwner());
  1067. }
  1068. std::string HillFort::getDescriptionToolTip() const
  1069. {
  1070. return TextIdentifier(getObjectHandler()->getBaseTextID(), "description").get();
  1071. }
  1072. std::string HillFort::getUnavailableUpgradeMessage() const
  1073. {
  1074. assert(getObjectHandler()->getModScope() != "core");
  1075. return TextIdentifier(getObjectHandler()->getBaseTextID(), "unavailableUpgradeMessage").get();
  1076. }
  1077. VCMI_LIB_NAMESPACE_END