MiscObjects.cpp 34 KB

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