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