2
0

MiscObjects.cpp 34 KB

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