MiscObjects.cpp 34 KB

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