MiscObjects.cpp 35 KB

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