MiscObjects.cpp 35 KB

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