MiscObjects.cpp 34 KB

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