MiscObjects.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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() //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) // FIXME: Find out why there are nullptr objects right after initialization
  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()
  944. {
  945. hero = nullptr;
  946. direction = 4;
  947. layer = EPathfindingLayer::SAIL;
  948. }
  949. bool CGBoat::isCoastVisitable() const
  950. {
  951. return true;
  952. }
  953. void CGSirens::initObj(CRandomGenerator & rand)
  954. {
  955. blockVisit = true;
  956. }
  957. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  958. {
  959. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID)));
  960. }
  961. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  962. {
  963. InfoWindow iw;
  964. iw.player = h->tempOwner;
  965. if(h->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID))) //has already visited Sirens
  966. {
  967. iw.type = EInfoWindowMode::AUTO;
  968. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  969. }
  970. else
  971. {
  972. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  973. TExpType xp = 0;
  974. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  975. {
  976. // 1-sized stacks are not affected by sirens
  977. if (i->second->count == 1)
  978. continue;
  979. // tested H3 behavior: 30% (rounded up) of stack drowns
  980. TQuantity drown = std::ceil(i->second->count * 0.3);
  981. if(drown)
  982. {
  983. cb->changeStackCount(StackLocation(h, i->first), -drown);
  984. xp += drown * i->second->type->getMaxHealth();
  985. }
  986. }
  987. if(xp)
  988. {
  989. xp = h->calculateXp(static_cast<int>(xp));
  990. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  991. iw.text.replaceNumber(static_cast<int>(xp));
  992. cb->giveExperience(h, xp);
  993. }
  994. else
  995. {
  996. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  997. }
  998. }
  999. cb->showInfoDialog(&iw);
  1000. }
  1001. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1002. {
  1003. // H J L K I
  1004. // A x S x B
  1005. // C E G F D
  1006. offsets = {
  1007. {-2, 0, 0}, // A
  1008. {+2, 0, 0}, // B
  1009. {-2, 1, 0}, // C
  1010. {+2, 1, 0}, // D
  1011. {-1, 1, 0}, // E
  1012. {+1, 1, 0}, // F
  1013. {0, 1, 0}, // G
  1014. {-2, -1, 0}, // H
  1015. {+2, -1, 0}, // I
  1016. {-1, -1, 0}, // G
  1017. {+1, -1, 0}, // K
  1018. {0, -1, 0}, // L
  1019. };
  1020. }
  1021. const IObjectInterface * CGShipyard::getObject() const
  1022. {
  1023. return this;
  1024. }
  1025. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1026. {
  1027. if(cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner) == PlayerRelations::ENEMIES)
  1028. cb->setOwner(this, h->tempOwner);
  1029. if(shipyardStatus() != IBoatGenerator::GOOD)
  1030. {
  1031. InfoWindow iw;
  1032. iw.type = EInfoWindowMode::AUTO;
  1033. iw.player = tempOwner;
  1034. getProblemText(iw.text, h);
  1035. cb->showInfoDialog(&iw);
  1036. }
  1037. else
  1038. {
  1039. cb->showObjectWindow(this, EOpenWindowMode::SHIPYARD_WINDOW, h, false);
  1040. }
  1041. }
  1042. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1043. {
  1044. serializeJsonOwner(handler);
  1045. }
  1046. BoatId CGShipyard::getBoatType() const
  1047. {
  1048. return createdBoat;
  1049. }
  1050. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1051. {
  1052. cb->showObjectWindow(this, EOpenWindowMode::THIEVES_GUILD, h, false);
  1053. }
  1054. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1055. {
  1056. InfoWindow iw;
  1057. iw.type = EInfoWindowMode::AUTO;
  1058. iw.player = h->tempOwner;
  1059. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1060. assert(ts);
  1061. TeamID team = ts->id;
  1062. if(!wasVisited(team))
  1063. {
  1064. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  1065. cb->sendAndApply(&iw);
  1066. // increment general visited obelisks counter
  1067. cb->setObjPropertyID(id, ObjProperty::OBELISK_VISITED, team);
  1068. cb->showObjectWindow(this, EOpenWindowMode::PUZZLE_MAP, h, false);
  1069. // mark that particular obelisk as visited for all players in the team
  1070. for(const auto & color : ts->players)
  1071. {
  1072. cb->setObjPropertyID(id, ObjProperty::VISITED, color);
  1073. }
  1074. }
  1075. else
  1076. {
  1077. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  1078. cb->sendAndApply(&iw);
  1079. }
  1080. }
  1081. void CGObelisk::initObj(CRandomGenerator & rand)
  1082. {
  1083. obeliskCount++;
  1084. }
  1085. void CGObelisk::reset()
  1086. {
  1087. obeliskCount = 0;
  1088. visited.clear();
  1089. }
  1090. std::string CGObelisk::getHoverText(PlayerColor player) const
  1091. {
  1092. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1093. }
  1094. void CGObelisk::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  1095. {
  1096. switch(what)
  1097. {
  1098. case ObjProperty::OBELISK_VISITED:
  1099. {
  1100. auto progress = ++visited[identifier.as<TeamID>()];
  1101. logGlobal->debug("Player %d: obelisk progress %d / %d", identifier.getNum(), static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1102. if(progress > obeliskCount)
  1103. {
  1104. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1105. throw std::runtime_error("Player visited more obelisks than present on map!");
  1106. }
  1107. break;
  1108. }
  1109. default:
  1110. CTeamVisited::setPropertyDer(what, identifier);
  1111. break;
  1112. }
  1113. }
  1114. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1115. {
  1116. if(h->tempOwner != tempOwner)
  1117. {
  1118. PlayerColor oldOwner = tempOwner;
  1119. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1120. h->showInfoDialog(69);
  1121. giveBonusTo(h->tempOwner);
  1122. if(oldOwner.isValidPlayer()) //remove bonus from old owner
  1123. {
  1124. RemoveBonus rb(GiveBonus::ETarget::PLAYER);
  1125. rb.whoID = oldOwner;
  1126. rb.source = BonusSource::OBJECT_INSTANCE;
  1127. rb.id = BonusSourceID(id);
  1128. cb->sendAndApply(&rb);
  1129. }
  1130. }
  1131. }
  1132. void CGLighthouse::initObj(CRandomGenerator & rand)
  1133. {
  1134. if(tempOwner.isValidPlayer())
  1135. {
  1136. // FIXME: This is dirty hack
  1137. giveBonusTo(tempOwner, true);
  1138. }
  1139. }
  1140. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1141. {
  1142. GiveBonus gb(GiveBonus::ETarget::PLAYER);
  1143. gb.bonus.type = BonusType::MOVEMENT;
  1144. gb.bonus.val = 500;
  1145. gb.id = player;
  1146. gb.bonus.duration = BonusDuration::PERMANENT;
  1147. gb.bonus.source = BonusSource::OBJECT_INSTANCE;
  1148. gb.bonus.sid = BonusSourceID(id);
  1149. gb.bonus.subtype = BonusCustomSubtype::heroMovementSea;
  1150. // FIXME: This is really dirty hack
  1151. // Proper fix would be to make CGLighthouse into bonus system node
  1152. // Unfortunately this will cause saves breakage
  1153. if(onInit)
  1154. gb.applyGs(cb->gameState());
  1155. else
  1156. cb->sendAndApply(&gb);
  1157. }
  1158. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1159. {
  1160. serializeJsonOwner(handler);
  1161. }
  1162. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1163. {
  1164. cb->showObjectWindow(this, EOpenWindowMode::HILL_FORT_WINDOW, h, false);
  1165. }
  1166. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1167. {
  1168. int32_t level = stack.type->getLevel();
  1169. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1170. int costModifier = upgradeCostPercentage[index];
  1171. if (costModifier < 0)
  1172. return; // upgrade not allowed
  1173. for(const auto & nid : stack.type->upgrades)
  1174. {
  1175. info.newID.push_back(nid);
  1176. info.cost.push_back((nid.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost()) * costModifier / 100);
  1177. }
  1178. }
  1179. VCMI_LIB_NAMESPACE_END