MiscObjects.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  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 "../StringConstants.h"
  13. #include "../NetPacks.h"
  14. #include "../CGeneralTextHandler.h"
  15. #include "../CSoundBase.h"
  16. #include "../CModHandler.h"
  17. #include "../CSkillHandler.h"
  18. #include "../spells/CSpellHandler.h"
  19. #include "../IGameCallback.h"
  20. #include "../CGameState.h"
  21. #include "../mapping/CMap.h"
  22. #include "../CPlayerState.h"
  23. #include "../serializer/JsonSerializeFormat.h"
  24. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  25. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  28. ui8 CGObelisk::obeliskCount = 0; //how many obelisks are on map
  29. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  30. ///helpers
  31. static std::string visitedTxt(const bool visited)
  32. {
  33. int id = visited ? 352 : 353;
  34. return VLC->generaltexth->allTexts[id];
  35. }
  36. void CTeamVisited::setPropertyDer(ui8 what, ui32 val)
  37. {
  38. if(what == CTeamVisited::OBJPROP_VISITED)
  39. players.insert(PlayerColor(val));
  40. }
  41. bool CTeamVisited::wasVisited(PlayerColor player) const
  42. {
  43. return wasVisited(cb->getPlayerState(player)->team);
  44. }
  45. bool CTeamVisited::wasVisited(const CGHeroInstance * h) const
  46. {
  47. return wasVisited(h->tempOwner);
  48. }
  49. bool CTeamVisited::wasVisited(const TeamID & team) const
  50. {
  51. for(const auto & i : players)
  52. {
  53. if(cb->getPlayerState(i)->team == team)
  54. return true;
  55. }
  56. return false;
  57. }
  58. //CGMine
  59. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  60. {
  61. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  62. if(relations == 2) //we're visiting our mine
  63. {
  64. cb->showGarrisonDialog(id,h->id,true);
  65. return;
  66. }
  67. else if (relations == 1)//ally
  68. return;
  69. if(stacksCount()) //Mine is guarded
  70. {
  71. BlockingDialog ynd(true,false);
  72. ynd.player = h->tempOwner;
  73. ynd.text.appendLocalString(EMetaText::ADVOB_TXT, subID == 7 ? 84 : 187);
  74. cb->showBlockingDialog(&ynd);
  75. return;
  76. }
  77. flagMine(h->tempOwner);
  78. }
  79. void CGMine::newTurn(CRandomGenerator & rand) const
  80. {
  81. if(cb->getDate() == 1)
  82. return;
  83. if (tempOwner == PlayerColor::NEUTRAL)
  84. return;
  85. cb->giveResource(tempOwner, producedResource, producedQuantity);
  86. }
  87. void CGMine::initObj(CRandomGenerator & rand)
  88. {
  89. if(isAbandoned())
  90. {
  91. //set guardians
  92. int howManyTroglodytes = rand.nextInt(100, 199);
  93. auto * troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  94. putStack(SlotID(0), troglodytes);
  95. assert(!abandonedMineResources.empty());
  96. producedResource = *RandomGeneratorUtil::nextItem(abandonedMineResources, rand);
  97. }
  98. else
  99. {
  100. producedResource = GameResID(subID);
  101. }
  102. producedQuantity = defaultResProduction();
  103. }
  104. bool CGMine::isAbandoned() const
  105. {
  106. return (subID >= 7);
  107. }
  108. std::string CGMine::getObjectName() const
  109. {
  110. return VLC->generaltexth->translate("core.minename", subID);
  111. }
  112. std::string CGMine::getHoverText(PlayerColor player) const
  113. {
  114. std::string hoverName = CArmedInstance::getHoverText(player);
  115. if (tempOwner != PlayerColor::NEUTRAL)
  116. hoverName += "\n(" + VLC->generaltexth->restypes[producedResource] + ")";
  117. if(stacksCount())
  118. {
  119. hoverName += "\n";
  120. hoverName += VLC->generaltexth->allTexts[202]; //Guarded by
  121. hoverName += " ";
  122. hoverName += getArmyDescription();
  123. }
  124. return hoverName;
  125. }
  126. void CGMine::flagMine(const PlayerColor & player) const
  127. {
  128. assert(tempOwner != player);
  129. cb->setOwner(this, player); //not ours? flag it!
  130. InfoWindow iw;
  131. iw.type = EInfoWindowMode::AUTO;
  132. iw.soundID = soundBase::FLAGMINE;
  133. iw.text.appendLocalString(EMetaText::MINE_EVNTS, producedResource); //not use subID, abandoned mines uses default mine texts
  134. iw.player = player;
  135. iw.components.emplace_back(Component::EComponentType::RESOURCE, producedResource, producedQuantity, -1);
  136. cb->showInfoDialog(&iw);
  137. }
  138. ui32 CGMine::defaultResProduction() const
  139. {
  140. switch(producedResource.toEnum())
  141. {
  142. case EGameResID::WOOD:
  143. case EGameResID::ORE:
  144. return 2;
  145. case EGameResID::GOLD:
  146. return 1000;
  147. default:
  148. return 1;
  149. }
  150. }
  151. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  152. {
  153. if(result.winner == 0) //attacker won
  154. {
  155. if(isAbandoned())
  156. {
  157. hero->showInfoDialog(85);
  158. }
  159. flagMine(hero->tempOwner);
  160. }
  161. }
  162. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  163. {
  164. if(answer)
  165. cb->startBattleI(hero, this);
  166. }
  167. void CGMine::serializeJsonOptions(JsonSerializeFormat & handler)
  168. {
  169. CCreatureSet::serializeJson(handler, "army", 7);
  170. if(isAbandoned())
  171. {
  172. if(handler.saving)
  173. {
  174. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  175. for(auto const & resID : abandonedMineResources)
  176. {
  177. JsonNode one(JsonNode::JsonType::DATA_STRING);
  178. one.String() = GameConstants::RESOURCE_NAMES[resID];
  179. node.Vector().push_back(one);
  180. }
  181. handler.serializeRaw("possibleResources", node, std::nullopt);
  182. }
  183. else
  184. {
  185. auto guard = handler.enterArray("possibleResources");
  186. const JsonNode & node = handler.getCurrent();
  187. auto names = node.convertTo<std::vector<std::string>>();
  188. for(const std::string & s : names)
  189. {
  190. int raw_res = vstd::find_pos(GameConstants::RESOURCE_NAMES, s);
  191. if(raw_res < 0)
  192. logGlobal->error("Invalid resource name: %s", s);
  193. else
  194. abandonedMineResources.emplace(raw_res);
  195. }
  196. }
  197. }
  198. else
  199. {
  200. serializeJsonOwner(handler);
  201. }
  202. }
  203. std::string CGResource::getHoverText(PlayerColor player) const
  204. {
  205. return VLC->generaltexth->restypes[subID];
  206. }
  207. void CGResource::initObj(CRandomGenerator & rand)
  208. {
  209. blockVisit = true;
  210. if(amount == CGResource::RANDOM_AMOUNT)
  211. {
  212. switch(static_cast<EGameResID>(subID))
  213. {
  214. case EGameResID::GOLD:
  215. amount = rand.nextInt(5, 10) * 100;
  216. break;
  217. case EGameResID::WOOD: case EGameResID::ORE:
  218. amount = rand.nextInt(6, 10);
  219. break;
  220. default:
  221. amount = rand.nextInt(3, 5);
  222. break;
  223. }
  224. }
  225. }
  226. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  227. {
  228. if(stacksCount())
  229. {
  230. if(!message.empty())
  231. {
  232. BlockingDialog ynd(true,false);
  233. ynd.player = h->getOwner();
  234. ynd.text.appendRawString(message);
  235. cb->showBlockingDialog(&ynd);
  236. }
  237. else
  238. {
  239. blockingDialogAnswered(h, true); //behave as if player accepted battle
  240. }
  241. }
  242. else
  243. collectRes(h->getOwner());
  244. }
  245. void CGResource::collectRes(const PlayerColor & player) const
  246. {
  247. cb->giveResource(player, static_cast<EGameResID>(subID), amount);
  248. InfoWindow sii;
  249. sii.player = player;
  250. if(!message.empty())
  251. {
  252. sii.type = EInfoWindowMode::AUTO;
  253. sii.text.appendRawString(message);
  254. }
  255. else
  256. {
  257. sii.type = EInfoWindowMode::INFO;
  258. sii.text.appendLocalString(EMetaText::ADVOB_TXT,113);
  259. sii.text.replaceLocalString(EMetaText::RES_NAMES, subID);
  260. }
  261. sii.components.emplace_back(Component::EComponentType::RESOURCE,subID,amount,0);
  262. sii.soundID = soundBase::pickup01 + CRandomGenerator::getDefault().nextInt(6);
  263. cb->showInfoDialog(&sii);
  264. cb->removeObject(this);
  265. }
  266. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  267. {
  268. if(result.winner == 0) //attacker won
  269. collectRes(hero->getOwner());
  270. }
  271. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  272. {
  273. if(answer)
  274. cb->startBattleI(hero, this);
  275. }
  276. void CGResource::serializeJsonOptions(JsonSerializeFormat & handler)
  277. {
  278. CCreatureSet::serializeJson(handler, "guards", 7);
  279. handler.serializeInt("amount", amount, 0);
  280. handler.serializeString("guardMessage", message);
  281. }
  282. bool CGTeleport::isEntrance() const
  283. {
  284. return type == BOTH || type == ENTRANCE;
  285. }
  286. bool CGTeleport::isExit() const
  287. {
  288. return type == BOTH || type == EXIT;
  289. }
  290. bool CGTeleport::isChannelEntrance(const ObjectInstanceID & id) const
  291. {
  292. return vstd::contains(getAllEntrances(), id);
  293. }
  294. bool CGTeleport::isChannelExit(const ObjectInstanceID & id) const
  295. {
  296. return vstd::contains(getAllExits(), id);
  297. }
  298. std::vector<ObjectInstanceID> CGTeleport::getAllEntrances(bool excludeCurrent) const
  299. {
  300. auto ret = cb->getTeleportChannelEntraces(channel);
  301. if(excludeCurrent)
  302. vstd::erase_if_present(ret, id);
  303. return ret;
  304. }
  305. std::vector<ObjectInstanceID> CGTeleport::getAllExits(bool excludeCurrent) const
  306. {
  307. auto ret = cb->getTeleportChannelExits(channel);
  308. if(excludeCurrent)
  309. vstd::erase_if_present(ret, id);
  310. return ret;
  311. }
  312. ObjectInstanceID CGTeleport::getRandomExit(const CGHeroInstance * h) const
  313. {
  314. auto passableExits = getPassableExits(cb->gameState(), h, getAllExits(true));
  315. if(!passableExits.empty())
  316. return *RandomGeneratorUtil::nextItem(passableExits, CRandomGenerator::getDefault());
  317. return ObjectInstanceID();
  318. }
  319. bool CGTeleport::isTeleport(const CGObjectInstance * obj)
  320. {
  321. return ((dynamic_cast<const CGTeleport *>(obj)));
  322. }
  323. bool CGTeleport::isConnected(const CGTeleport * src, const CGTeleport * dst)
  324. {
  325. return src && dst && src->isChannelExit(dst->id);
  326. }
  327. bool CGTeleport::isConnected(const CGObjectInstance * src, const CGObjectInstance * dst)
  328. {
  329. const auto * srcObj = dynamic_cast<const CGTeleport *>(src);
  330. const auto * dstObj = dynamic_cast<const CGTeleport *>(dst);
  331. return isConnected(srcObj, dstObj);
  332. }
  333. bool CGTeleport::isExitPassable(CGameState * gs, const CGHeroInstance * h, const CGObjectInstance * obj)
  334. {
  335. auto * objTopVisObj = gs->map->getTile(obj->visitablePos()).topVisitableObj();
  336. if(objTopVisObj->ID == Obj::HERO)
  337. {
  338. if(h->id == objTopVisObj->id) // Just to be sure it's won't happen.
  339. return false;
  340. // Check if it's friendly hero or not
  341. if(gs->getPlayerRelations(h->tempOwner, objTopVisObj->tempOwner) != PlayerRelations::ENEMIES)
  342. {
  343. // Exchange between heroes only possible via subterranean gates
  344. if(!dynamic_cast<const CGSubterraneanGate *>(obj))
  345. return false;
  346. }
  347. }
  348. return true;
  349. }
  350. std::vector<ObjectInstanceID> CGTeleport::getPassableExits(CGameState * gs, const CGHeroInstance * h, std::vector<ObjectInstanceID> exits)
  351. {
  352. vstd::erase_if(exits, [&](const ObjectInstanceID & exit) -> bool
  353. {
  354. return !isExitPassable(gs, h, gs->getObj(exit));
  355. });
  356. return exits;
  357. }
  358. void CGTeleport::addToChannel(std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > &channelsList, const CGTeleport * obj)
  359. {
  360. std::shared_ptr<TeleportChannel> tc;
  361. if(channelsList.find(obj->channel) == channelsList.end())
  362. {
  363. tc = std::make_shared<TeleportChannel>();
  364. channelsList.insert(std::make_pair(obj->channel, tc));
  365. }
  366. else
  367. tc = channelsList[obj->channel];
  368. if(obj->isEntrance() && !vstd::contains(tc->entrances, obj->id))
  369. tc->entrances.push_back(obj->id);
  370. if(obj->isExit() && !vstd::contains(tc->exits, obj->id))
  371. tc->exits.push_back(obj->id);
  372. if(!tc->entrances.empty() && !tc->exits.empty()
  373. && (tc->entrances.size() != 1 || tc->entrances != tc->exits))
  374. {
  375. tc->passability = TeleportChannel::PASSABLE;
  376. }
  377. }
  378. TeleportChannelID CGMonolith::findMeChannel(const std::vector<Obj> & IDs, int SubID) const
  379. {
  380. for(auto obj : cb->gameState()->map->objects)
  381. {
  382. if(!obj)
  383. continue;
  384. const auto * teleportObj = dynamic_cast<const CGTeleport *>(cb->getObj(obj->id));
  385. if(teleportObj && vstd::contains(IDs, teleportObj->ID) && teleportObj->subID == SubID)
  386. return teleportObj->channel;
  387. }
  388. return TeleportChannelID();
  389. }
  390. void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const
  391. {
  392. TeleportDialog td(h->tempOwner, channel);
  393. if(isEntrance())
  394. {
  395. if(cb->isTeleportChannelBidirectional(channel) && 1 < cb->getTeleportChannelExits(channel).size())
  396. {
  397. auto exits = cb->getTeleportChannelExits(channel);
  398. for(const auto & exit : exits)
  399. {
  400. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  401. }
  402. }
  403. if(cb->isTeleportChannelImpassable(channel))
  404. {
  405. logGlobal->debug("Cannot find corresponding exit monolith for %d at %s", id.getNum(), pos.toString());
  406. td.impassable = true;
  407. }
  408. else if(getRandomExit(h) == ObjectInstanceID())
  409. logGlobal->debug("All exits blocked for monolith %d at %s", id.getNum(), pos.toString());
  410. }
  411. else
  412. h->showInfoDialog(70);
  413. cb->showTeleportDialog(&td);
  414. }
  415. void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  416. {
  417. int3 dPos;
  418. auto randomExit = getRandomExit(hero);
  419. auto realExits = getAllExits(true);
  420. if(!isEntrance() // Do nothing if hero visited exit only object
  421. || (exits.empty() && realExits.empty()) // Do nothing if there no exits on this channel
  422. || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate
  423. {
  424. return;
  425. }
  426. else if(vstd::isValidIndex(exits, answer))
  427. dPos = exits[answer].second;
  428. else
  429. dPos = hero->convertFromVisitablePos(cb->getObj(randomExit)->visitablePos());
  430. cb->moveHero(hero->id, dPos, true);
  431. }
  432. void CGMonolith::initObj(CRandomGenerator & rand)
  433. {
  434. std::vector<Obj> IDs;
  435. IDs.push_back(ID);
  436. switch(ID)
  437. {
  438. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  439. type = ENTRANCE;
  440. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_EXIT);
  441. break;
  442. case Obj::MONOLITH_ONE_WAY_EXIT:
  443. type = EXIT;
  444. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_ENTRANCE);
  445. break;
  446. case Obj::MONOLITH_TWO_WAY:
  447. default:
  448. type = BOTH;
  449. break;
  450. }
  451. channel = findMeChannel(IDs, subID);
  452. if(channel == TeleportChannelID())
  453. channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  454. addToChannel(cb->gameState()->map->teleportChannels, this);
  455. }
  456. void CGSubterraneanGate::onHeroVisit( const CGHeroInstance * h ) const
  457. {
  458. TeleportDialog td(h->tempOwner, channel);
  459. if(cb->isTeleportChannelImpassable(channel))
  460. {
  461. h->showInfoDialog(153);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  462. logGlobal->debug("Cannot find exit subterranean gate for %d at %s", id.getNum(), pos.toString());
  463. td.impassable = true;
  464. }
  465. else
  466. {
  467. auto exit = getRandomExit(h);
  468. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  469. }
  470. cb->showTeleportDialog(&td);
  471. }
  472. void CGSubterraneanGate::initObj(CRandomGenerator & rand)
  473. {
  474. type = BOTH;
  475. }
  476. void CGSubterraneanGate::postInit() //matches subterranean gates into pairs
  477. {
  478. //split on underground and surface gates
  479. std::vector<CGSubterraneanGate *> gatesSplit[2]; //surface and underground gates
  480. for(auto & obj : cb->gameState()->map->objects)
  481. {
  482. if(!obj) // FIXME: Find out why there are nullptr objects right after initialization
  483. continue;
  484. auto * hlp = dynamic_cast<CGSubterraneanGate *>(cb->gameState()->getObjInstance(obj->id));
  485. if(hlp)
  486. gatesSplit[hlp->pos.z].push_back(hlp);
  487. }
  488. //sort by position
  489. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  490. {
  491. return a->pos < b->pos;
  492. });
  493. auto assignToChannel = [&](CGSubterraneanGate * obj)
  494. {
  495. if(obj->channel == TeleportChannelID())
  496. { // if object not linked to channel then create new channel
  497. obj->channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  498. addToChannel(cb->gameState()->map->teleportChannels, obj);
  499. }
  500. };
  501. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  502. {
  503. CGSubterraneanGate * objCurrent = gatesSplit[0][i];
  504. //find nearest underground exit
  505. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  506. for(int j = 0; j < gatesSplit[1].size(); j++)
  507. {
  508. CGSubterraneanGate *checked = gatesSplit[1][j];
  509. if(checked->channel != TeleportChannelID())
  510. continue;
  511. si32 hlp = checked->pos.dist2dSQ(objCurrent->pos);
  512. if(hlp < best.second)
  513. {
  514. best.first = j;
  515. best.second = hlp;
  516. }
  517. }
  518. assignToChannel(objCurrent);
  519. if(best.first >= 0) //found pair
  520. {
  521. gatesSplit[1][best.first]->channel = objCurrent->channel;
  522. addToChannel(cb->gameState()->map->teleportChannels, gatesSplit[1][best.first]);
  523. }
  524. }
  525. // we should assign empty channels to underground gates if they don't have matching overground gates
  526. for(auto & i : gatesSplit[1])
  527. assignToChannel(i);
  528. }
  529. void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const
  530. {
  531. TeleportDialog td(h->tempOwner, channel);
  532. if(cb->isTeleportChannelImpassable(channel))
  533. {
  534. logGlobal->debug("Cannot find exit whirlpool for %d at %s", id.getNum(), pos.toString());
  535. td.impassable = true;
  536. }
  537. else if(getRandomExit(h) == ObjectInstanceID())
  538. logGlobal->debug("All exits are blocked for whirlpool %d at %s", id.getNum(), pos.toString());
  539. if(!isProtected(h))
  540. {
  541. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  542. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  543. {
  544. if(h->getPower(targetstack) > h->getPower(i->first))
  545. targetstack = (i->first);
  546. }
  547. auto countToTake = static_cast<TQuantity>(h->getStackCount(targetstack) * 0.5);
  548. vstd::amax(countToTake, 1);
  549. InfoWindow iw;
  550. iw.type = EInfoWindowMode::AUTO;
  551. iw.player = h->tempOwner;
  552. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 168);
  553. iw.components.emplace_back(CStackBasicDescriptor(h->getCreature(targetstack), -countToTake));
  554. cb->showInfoDialog(&iw);
  555. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  556. }
  557. else
  558. {
  559. auto exits = getAllExits();
  560. for(const auto & exit : exits)
  561. {
  562. auto blockedPosList = cb->getObj(exit)->getBlockedPos();
  563. for(const auto & bPos : blockedPosList)
  564. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(bPos)));
  565. }
  566. }
  567. cb->showTeleportDialog(&td);
  568. }
  569. void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  570. {
  571. int3 dPos;
  572. auto realExits = getAllExits();
  573. if(exits.empty() && realExits.empty())
  574. return;
  575. else if(vstd::isValidIndex(exits, answer))
  576. dPos = exits[answer].second;
  577. else
  578. {
  579. auto exit = getRandomExit(hero);
  580. if(exit == ObjectInstanceID())
  581. return;
  582. const auto * obj = cb->getObj(exit);
  583. std::set<int3> tiles = obj->getBlockedPos();
  584. dPos = hero->convertFromVisitablePos(*RandomGeneratorUtil::nextItem(tiles, CRandomGenerator::getDefault()));
  585. }
  586. cb->moveHero(hero->id, dPos, true);
  587. }
  588. bool CGWhirlpool::isProtected(const CGHeroInstance * h)
  589. {
  590. return h->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION)
  591. || (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1);
  592. }
  593. void CGArtifact::initObj(CRandomGenerator & rand)
  594. {
  595. blockVisit = true;
  596. if(ID == Obj::ARTIFACT)
  597. {
  598. if (!storedArtifact)
  599. {
  600. auto * a = new CArtifactInstance();
  601. cb->gameState()->map->addNewArtifactInstance(a);
  602. storedArtifact = a;
  603. }
  604. if(!storedArtifact->artType)
  605. storedArtifact->setType(VLC->arth->objects[subID]);
  606. }
  607. if(ID == Obj::SPELL_SCROLL)
  608. subID = 1;
  609. assert(storedArtifact->artType);
  610. assert(storedArtifact->getParentNodes().size());
  611. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  612. }
  613. std::string CGArtifact::getObjectName() const
  614. {
  615. return VLC->artifacts()->getByIndex(subID)->getNameTranslated();
  616. }
  617. void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
  618. {
  619. if(!stacksCount())
  620. {
  621. InfoWindow iw;
  622. iw.type = EInfoWindowMode::AUTO;
  623. iw.player = h->tempOwner;
  624. if(storedArtifact->artType->canBePutAt(h))
  625. {
  626. switch (ID)
  627. {
  628. case Obj::ARTIFACT:
  629. {
  630. iw.components.emplace_back(Component::EComponentType::ARTIFACT, subID, 0, 0);
  631. if(message.length())
  632. iw.text.appendRawString(message);
  633. else
  634. iw.text.appendLocalString(EMetaText::ART_EVNTS, subID);
  635. }
  636. break;
  637. case Obj::SPELL_SCROLL:
  638. {
  639. int spellID = storedArtifact->getScrollSpellID();
  640. iw.components.emplace_back(Component::EComponentType::SPELL, spellID, 0, 0);
  641. if(message.length())
  642. iw.text.appendRawString(message);
  643. else
  644. {
  645. iw.text.appendLocalString(EMetaText::ADVOB_TXT,135);
  646. iw.text.replaceLocalString(EMetaText::SPELL_NAME, spellID);
  647. }
  648. }
  649. break;
  650. }
  651. }
  652. else
  653. {
  654. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 2);
  655. }
  656. cb->showInfoDialog(&iw);
  657. pick(h);
  658. }
  659. else
  660. {
  661. switch(ID)
  662. {
  663. case Obj::ARTIFACT:
  664. {
  665. BlockingDialog ynd(true,false);
  666. ynd.player = h->getOwner();
  667. if(message.length())
  668. ynd.text.appendRawString(message);
  669. else
  670. {
  671. // TODO: Guard text is more complex in H3, see mantis issue 2325 for details
  672. ynd.text.appendLocalString(EMetaText::GENERAL_TXT, 420);
  673. ynd.text.replaceRawString("");
  674. ynd.text.replaceRawString(getArmyDescription());
  675. ynd.text.replaceLocalString(EMetaText::GENERAL_TXT, 43); // creatures
  676. }
  677. cb->showBlockingDialog(&ynd);
  678. }
  679. break;
  680. case Obj::SPELL_SCROLL:
  681. {
  682. if(message.length())
  683. {
  684. BlockingDialog ynd(true,false);
  685. ynd.player = h->getOwner();
  686. ynd.text.appendRawString(message);
  687. cb->showBlockingDialog(&ynd);
  688. }
  689. else
  690. blockingDialogAnswered(h, true);
  691. }
  692. break;
  693. }
  694. }
  695. }
  696. void CGArtifact::pick(const CGHeroInstance * h) const
  697. {
  698. if(cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE))
  699. cb->removeObject(this);
  700. }
  701. BattleField CGArtifact::getBattlefield() const
  702. {
  703. return BattleField::NONE;
  704. }
  705. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  706. {
  707. if(result.winner == 0) //attacker won
  708. pick(hero);
  709. }
  710. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  711. {
  712. if(answer)
  713. cb->startBattleI(hero, this);
  714. }
  715. void CGArtifact::afterAddToMap(CMap * map)
  716. {
  717. //Artifacts from map objects are never removed
  718. //FIXME: This should be revertible in map editor
  719. if(ID == Obj::SPELL_SCROLL && storedArtifact && storedArtifact->id.getNum() < 0)
  720. map->addNewArtifactInstance(storedArtifact);
  721. }
  722. void CGArtifact::serializeJsonOptions(JsonSerializeFormat& handler)
  723. {
  724. handler.serializeString("guardMessage", message);
  725. CCreatureSet::serializeJson(handler, "guards" ,7);
  726. if(handler.saving && ID == Obj::SPELL_SCROLL)
  727. {
  728. const std::shared_ptr<Bonus> b = storedArtifact->getBonusLocalFirst(Selector::type()(BonusType::SPELL));
  729. SpellID spellId(b->subtype);
  730. handler.serializeId("spell", spellId, SpellID::NONE);
  731. }
  732. }
  733. void CGWitchHut::initObj(CRandomGenerator & rand)
  734. {
  735. if (allowedAbilities.empty()) //this can happen for RMG and RoE maps.
  736. {
  737. auto defaultAllowed = VLC->skillh->getDefaultAllowed();
  738. // Necromancy and Leadership can't be learned by default
  739. defaultAllowed[SecondarySkill::NECROMANCY] = false;
  740. defaultAllowed[SecondarySkill::LEADERSHIP] = false;
  741. for(int i = 0; i < defaultAllowed.size(); i++)
  742. if (defaultAllowed[i] && cb->isAllowed(2, i))
  743. allowedAbilities.insert(SecondarySkill(i));
  744. }
  745. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, rand);
  746. }
  747. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  748. {
  749. InfoWindow iw;
  750. iw.type = EInfoWindowMode::AUTO;
  751. iw.player = h->getOwner();
  752. if(!wasVisited(h->tempOwner))
  753. cb->setObjProperty(id, CGWitchHut::OBJPROP_VISITED, h->tempOwner.getNum());
  754. ui32 txt_id;
  755. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  756. {
  757. txt_id =172;
  758. }
  759. else if(!h->canLearnSkill()) //already all skills slots used
  760. {
  761. txt_id = 173;
  762. }
  763. else //give sec skill
  764. {
  765. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, ability, 1, 0);
  766. txt_id = 171;
  767. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  768. }
  769. iw.text.appendLocalString(EMetaText::ADVOB_TXT,txt_id);
  770. iw.text.replaceLocalString(EMetaText::SEC_SKILL_NAME, ability);
  771. cb->showInfoDialog(&iw);
  772. }
  773. std::string CGWitchHut::getHoverText(PlayerColor player) const
  774. {
  775. std::string hoverName = getObjectName();
  776. if(wasVisited(player))
  777. {
  778. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  779. boost::algorithm::replace_first(hoverName, "%s", VLC->skillh->getByIndex(ability)->getNameTranslated());
  780. }
  781. return hoverName;
  782. }
  783. std::string CGWitchHut::getHoverText(const CGHeroInstance * hero) const
  784. {
  785. std::string hoverName = getHoverText(hero->tempOwner);
  786. if(wasVisited(hero->tempOwner) && hero->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  787. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  788. return hoverName;
  789. }
  790. void CGWitchHut::serializeJsonOptions(JsonSerializeFormat & handler)
  791. {
  792. //TODO: unify allowed abilities with others - make them std::vector<bool>
  793. std::vector<bool> temp;
  794. size_t skillCount = VLC->skillh->size();
  795. temp.resize(skillCount, false);
  796. auto standard = VLC->skillh->getDefaultAllowed(); //todo: for WitchHut default is all except Leadership and Necromancy
  797. if(handler.saving)
  798. {
  799. for(si32 i = 0; i < skillCount; ++i)
  800. if(vstd::contains(allowedAbilities, i))
  801. temp[i] = true;
  802. }
  803. handler.serializeLIC("allowedSkills", &CSkillHandler::decodeSkill, &CSkillHandler::encodeSkill, standard, temp);
  804. if(!handler.saving)
  805. {
  806. allowedAbilities.clear();
  807. for(si32 i = 0; i < skillCount; ++i)
  808. if(temp[i])
  809. allowedAbilities.insert(SecondarySkill(i));
  810. }
  811. }
  812. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  813. {
  814. InfoWindow iw;
  815. iw.type = EInfoWindowMode::AUTO;
  816. iw.player = h->tempOwner;
  817. switch (ID)
  818. {
  819. case Obj::REDWOOD_OBSERVATORY:
  820. case Obj::PILLAR_OF_FIRE:
  821. {
  822. iw.text.appendLocalString(EMetaText::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  823. FoWChange fw;
  824. fw.player = h->tempOwner;
  825. fw.mode = 1;
  826. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  827. cb->sendAndApply (&fw);
  828. break;
  829. }
  830. case Obj::COVER_OF_DARKNESS:
  831. {
  832. iw.text.appendLocalString (EMetaText::ADVOB_TXT, 31);
  833. for (auto & player : cb->gameState()->players)
  834. {
  835. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  836. cb->getPlayerRelations(player.first, h->tempOwner) == PlayerRelations::ENEMIES)
  837. cb->changeFogOfWar(visitablePos(), 20, player.first, true);
  838. }
  839. break;
  840. }
  841. }
  842. cb->showInfoDialog(&iw);
  843. }
  844. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  845. {
  846. if(spell == SpellID::NONE)
  847. {
  848. logGlobal->error("Not initialized shrine visited!");
  849. return;
  850. }
  851. if(!wasVisited(h->tempOwner))
  852. cb->setObjProperty(id, CGShrine::OBJPROP_VISITED, h->tempOwner.getNum());
  853. InfoWindow iw;
  854. iw.type = EInfoWindowMode::AUTO;
  855. iw.player = h->getOwner();
  856. iw.text = visitText;
  857. iw.text.appendLocalString(EMetaText::SPELL_NAME,spell);
  858. iw.text.appendRawString(".");
  859. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  860. {
  861. iw.text.appendLocalString(EMetaText::ADVOB_TXT,131);
  862. }
  863. else if(h->spellbookContainsSpell(spell))//hero already knows the spell
  864. {
  865. iw.text.appendLocalString(EMetaText::ADVOB_TXT,174);
  866. }
  867. else if(spell.toSpell()->getLevel() > h->maxSpellLevel()) //it's third level spell and hero doesn't have wisdom
  868. {
  869. iw.text.appendLocalString(EMetaText::ADVOB_TXT,130);
  870. }
  871. else //give spell
  872. {
  873. std::set<SpellID> spells;
  874. spells.insert(spell);
  875. cb->changeSpells(h, true, spells);
  876. iw.components.emplace_back(Component::EComponentType::SPELL, spell, 0, 0);
  877. }
  878. cb->showInfoDialog(&iw);
  879. }
  880. void CGShrine::initObj(CRandomGenerator & rand)
  881. {
  882. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
  883. }
  884. std::string CGShrine::getHoverText(PlayerColor player) const
  885. {
  886. std::string hoverName = getObjectName();
  887. if(wasVisited(player))
  888. {
  889. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  890. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->getNameTranslated());
  891. }
  892. return hoverName;
  893. }
  894. std::string CGShrine::getHoverText(const CGHeroInstance * hero) const
  895. {
  896. std::string hoverName = getHoverText(hero->tempOwner);
  897. if(wasVisited(hero->tempOwner) && hero->spellbookContainsSpell(spell)) //know what spell there is and hero knows that spell
  898. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  899. return hoverName;
  900. }
  901. void CGShrine::serializeJsonOptions(JsonSerializeFormat & handler)
  902. {
  903. handler.serializeId("spell", spell, SpellID::NONE);
  904. }
  905. void CGSignBottle::initObj(CRandomGenerator & rand)
  906. {
  907. //if no text is set than we pick random from the predefined ones
  908. if(message.empty())
  909. {
  910. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randsign");
  911. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  912. message = VLC->generaltexth->translate(messageIdentifier);
  913. }
  914. if(ID == Obj::OCEAN_BOTTLE)
  915. {
  916. blockVisit = true;
  917. }
  918. }
  919. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  920. {
  921. InfoWindow iw;
  922. iw.player = h->getOwner();
  923. iw.text.appendRawString(message);
  924. cb->showInfoDialog(&iw);
  925. if(ID == Obj::OCEAN_BOTTLE)
  926. cb->removeObject(this);
  927. }
  928. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  929. {
  930. handler.serializeString("text", message);
  931. }
  932. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  933. {
  934. EBonusType type = bonusType;
  935. int bid = bonusID;
  936. //check if the bonus if applicable, if not - give primary skill (always possible)
  937. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  938. if((type == SECONDARY_SKILL && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  939. || (type == SPELL && !h->canLearnSpell(SpellID(bid).toSpell())))
  940. {
  941. type = PRIM_SKILL;
  942. bid = CRandomGenerator::getDefault().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  943. }
  944. InfoWindow iw;
  945. iw.type = EInfoWindowMode::AUTO;
  946. iw.player = h->getOwner();
  947. iw.text.appendLocalString(EMetaText::ADVOB_TXT,115);
  948. switch (type)
  949. {
  950. case PRIM_SKILL:
  951. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  952. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, bid, +1, 0);
  953. break;
  954. case SECONDARY_SKILL:
  955. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  956. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, bid, ssl + 1, 0);
  957. break;
  958. case SPELL:
  959. {
  960. std::set<SpellID> hlp;
  961. hlp.insert(SpellID(bid));
  962. cb->changeSpells(h,true,hlp);
  963. iw.components.emplace_back(Component::EComponentType::SPELL, bid, 0, 0);
  964. }
  965. break;
  966. default:
  967. logGlobal->error("Error: wrong bonus type (%d) for Scholar!\n", static_cast<int>(type));
  968. return;
  969. }
  970. cb->showInfoDialog(&iw);
  971. cb->removeObject(this);
  972. }
  973. void CGScholar::initObj(CRandomGenerator & rand)
  974. {
  975. blockVisit = true;
  976. if(bonusType == RANDOM)
  977. {
  978. bonusType = static_cast<EBonusType>(rand.nextInt(2));
  979. switch(bonusType)
  980. {
  981. case PRIM_SKILL:
  982. bonusID = rand.nextInt(GameConstants::PRIMARY_SKILLS -1);
  983. break;
  984. case SECONDARY_SKILL:
  985. bonusID = rand.nextInt(static_cast<int>(VLC->skillh->size()) - 1);
  986. break;
  987. case SPELL:
  988. std::vector<SpellID> possibilities;
  989. cb->getAllowedSpells (possibilities);
  990. bonusID = *RandomGeneratorUtil::nextItem(possibilities, rand);
  991. break;
  992. }
  993. }
  994. }
  995. void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
  996. {
  997. if(handler.saving)
  998. {
  999. std::string value;
  1000. switch(bonusType)
  1001. {
  1002. case PRIM_SKILL:
  1003. value = PrimarySkill::names[bonusID];
  1004. handler.serializeString("rewardPrimSkill", value);
  1005. break;
  1006. case SECONDARY_SKILL:
  1007. value = CSkillHandler::encodeSkill(bonusID);
  1008. handler.serializeString("rewardSkill", value);
  1009. break;
  1010. case SPELL:
  1011. value = SpellID::encode(bonusID);
  1012. handler.serializeString("rewardSpell", value);
  1013. break;
  1014. case RANDOM:
  1015. break;
  1016. }
  1017. }
  1018. else
  1019. {
  1020. //TODO: unify
  1021. const JsonNode & json = handler.getCurrent();
  1022. bonusType = RANDOM;
  1023. if(!json["rewardPrimSkill"].String().empty())
  1024. {
  1025. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "primSkill", json["rewardPrimSkill"].String());
  1026. if(raw)
  1027. {
  1028. bonusType = PRIM_SKILL;
  1029. bonusID = raw.value();
  1030. }
  1031. }
  1032. else if(!json["rewardSkill"].String().empty())
  1033. {
  1034. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "skill", json["rewardSkill"].String());
  1035. if(raw)
  1036. {
  1037. bonusType = SECONDARY_SKILL;
  1038. bonusID = raw.value();
  1039. }
  1040. }
  1041. else if(!json["rewardSpell"].String().empty())
  1042. {
  1043. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "spell", json["rewardSpell"].String());
  1044. if(raw)
  1045. {
  1046. bonusType = SPELL;
  1047. bonusID = raw.value();
  1048. }
  1049. }
  1050. }
  1051. }
  1052. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  1053. {
  1054. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  1055. if (!ally && stacksCount() > 0) {
  1056. //TODO: Find a way to apply magic garrison effects in battle.
  1057. cb->startBattleI(h, this);
  1058. return;
  1059. }
  1060. //New owner.
  1061. if (!ally)
  1062. cb->setOwner(this, h->tempOwner);
  1063. cb->showGarrisonDialog(id, h->id, removableUnits);
  1064. }
  1065. bool CGGarrison::passableFor(PlayerColor player) const
  1066. {
  1067. //FIXME: identical to same method in CGTownInstance
  1068. if ( !stacksCount() )//empty - anyone can visit
  1069. return true;
  1070. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1071. return false;
  1072. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1073. return true;
  1074. return false;
  1075. }
  1076. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1077. {
  1078. if (result.winner == 0)
  1079. onHeroVisit(hero);
  1080. }
  1081. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  1082. {
  1083. handler.serializeBool("removableUnits", removableUnits);
  1084. serializeJsonOwner(handler);
  1085. CCreatureSet::serializeJson(handler, "army", 7);
  1086. }
  1087. void CGMagi::reset()
  1088. {
  1089. eyelist.clear();
  1090. }
  1091. void CGMagi::initObj(CRandomGenerator & rand)
  1092. {
  1093. if (ID == Obj::EYE_OF_MAGI)
  1094. {
  1095. blockVisit = true;
  1096. eyelist[subID].push_back(id);
  1097. }
  1098. }
  1099. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1100. {
  1101. if (ID == Obj::HUT_OF_MAGI)
  1102. {
  1103. h->showInfoDialog(61);
  1104. if (!eyelist[subID].empty())
  1105. {
  1106. CenterView cv;
  1107. cv.player = h->tempOwner;
  1108. cv.focusTime = 2000;
  1109. FoWChange fw;
  1110. fw.player = h->tempOwner;
  1111. fw.mode = 1;
  1112. fw.waitForDialogs = true;
  1113. for(const auto & it : eyelist[subID])
  1114. {
  1115. const CGObjectInstance *eye = cb->getObj(it);
  1116. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1117. cb->sendAndApply(&fw);
  1118. cv.pos = eye->pos;
  1119. cb->sendAndApply(&cv);
  1120. }
  1121. cv.pos = h->visitablePos();
  1122. cv.focusTime = 0;
  1123. cb->sendAndApply(&cv);
  1124. }
  1125. }
  1126. else if (ID == Obj::EYE_OF_MAGI)
  1127. {
  1128. h->showInfoDialog(48);
  1129. }
  1130. }
  1131. CGBoat::CGBoat()
  1132. {
  1133. hero = nullptr;
  1134. direction = 4;
  1135. layer = EPathfindingLayer::EEPathfindingLayer::SAIL;
  1136. }
  1137. bool CGBoat::isCoastVisitable() const
  1138. {
  1139. return true;
  1140. }
  1141. void CGSirens::initObj(CRandomGenerator & rand)
  1142. {
  1143. blockVisit = true;
  1144. }
  1145. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1146. {
  1147. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT,ID));
  1148. }
  1149. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1150. {
  1151. InfoWindow iw;
  1152. iw.player = h->tempOwner;
  1153. if(h->hasBonusFrom(BonusSource::OBJECT,ID)) //has already visited Sirens
  1154. {
  1155. iw.type = EInfoWindowMode::AUTO;
  1156. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  1157. }
  1158. else
  1159. {
  1160. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  1161. TExpType xp = 0;
  1162. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1163. {
  1164. // 1-sized stacks are not affected by sirens
  1165. if (i->second->count == 1)
  1166. continue;
  1167. // tested H3 behavior: 30% (rounded up) of stack drowns
  1168. TQuantity drown = std::ceil(i->second->count * 0.3);
  1169. if(drown)
  1170. {
  1171. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1172. xp += drown * i->second->type->getMaxHealth();
  1173. }
  1174. }
  1175. if(xp)
  1176. {
  1177. xp = h->calculateXp(static_cast<int>(xp));
  1178. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  1179. iw.text.replaceNumber(static_cast<int>(xp));
  1180. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1181. }
  1182. else
  1183. {
  1184. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  1185. }
  1186. }
  1187. cb->showInfoDialog(&iw);
  1188. }
  1189. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1190. {
  1191. // H J L K I
  1192. // A x S x B
  1193. // C E G F D
  1194. offsets = {
  1195. {-2, 0, 0}, // A
  1196. {+2, 0, 0}, // B
  1197. {-2, 1, 0}, // C
  1198. {+2, 1, 0}, // D
  1199. {-1, 1, 0}, // E
  1200. {+1, 1, 0}, // F
  1201. {0, 1, 0}, // G
  1202. {-2, -1, 0}, // H
  1203. {+2, -1, 0}, // I
  1204. {-1, -1, 0}, // G
  1205. {+1, -1, 0}, // K
  1206. {0, -1, 0}, // L
  1207. };
  1208. }
  1209. const IObjectInterface * CGShipyard::getObject() const
  1210. {
  1211. return this;
  1212. }
  1213. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1214. {
  1215. if(cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner) == PlayerRelations::ENEMIES)
  1216. cb->setOwner(this, h->tempOwner);
  1217. if(shipyardStatus() != IBoatGenerator::GOOD)
  1218. {
  1219. InfoWindow iw;
  1220. iw.type = EInfoWindowMode::AUTO;
  1221. iw.player = tempOwner;
  1222. getProblemText(iw.text, h);
  1223. cb->showInfoDialog(&iw);
  1224. }
  1225. else
  1226. {
  1227. openWindow(EOpenWindowMode::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1228. }
  1229. }
  1230. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1231. {
  1232. serializeJsonOwner(handler);
  1233. }
  1234. BoatId CGShipyard::getBoatType() const
  1235. {
  1236. return createdBoat;
  1237. }
  1238. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1239. {
  1240. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1241. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1242. {
  1243. if (cb->getResource(h->tempOwner, EGameResID::GOLD) >= 1000) //if he can afford a map
  1244. {
  1245. //ask if he wants to buy one
  1246. int text=0;
  1247. switch (subID)
  1248. {
  1249. case 0:
  1250. text = 25;
  1251. break;
  1252. case 1:
  1253. text = 26;
  1254. break;
  1255. case 2:
  1256. text = 27;
  1257. break;
  1258. default:
  1259. logGlobal->warn("Unrecognized subtype of cartographer");
  1260. }
  1261. assert(text);
  1262. BlockingDialog bd (true, false);
  1263. bd.player = h->getOwner();
  1264. bd.text.appendLocalString (EMetaText::ADVOB_TXT, text);
  1265. cb->showBlockingDialog (&bd);
  1266. }
  1267. else //if he cannot afford
  1268. {
  1269. h->showInfoDialog(28);
  1270. }
  1271. }
  1272. else //if he already visited carographer
  1273. {
  1274. h->showInfoDialog(24);
  1275. }
  1276. }
  1277. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1278. {
  1279. if(answer) //if hero wants to buy map
  1280. {
  1281. cb->giveResource(hero->tempOwner, EGameResID::GOLD, -1000);
  1282. FoWChange fw;
  1283. fw.mode = 1;
  1284. fw.player = hero->tempOwner;
  1285. //subIDs of different types of cartographers:
  1286. //water = 0; land = 1; underground = 2;
  1287. IGameCallback::MapTerrainFilterMode tileFilterMode = IGameCallback::MapTerrainFilterMode::NONE;
  1288. switch(subID)
  1289. {
  1290. case 0:
  1291. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::WATER;
  1292. break;
  1293. case 1:
  1294. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::LAND_CARTOGRAPHER;
  1295. break;
  1296. case 2:
  1297. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::UNDERGROUND_CARTOGRAPHER;
  1298. break;
  1299. }
  1300. cb->getAllTiles(fw.tiles, hero->tempOwner, -1, tileFilterMode); //reveal appropriate tiles
  1301. cb->sendAndApply(&fw);
  1302. cb->setObjProperty(id, CCartographer::OBJPROP_VISITED, hero->tempOwner.getNum());
  1303. }
  1304. }
  1305. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1306. {
  1307. cb->showThievesGuildWindow(h->tempOwner, id);
  1308. }
  1309. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1310. {
  1311. InfoWindow iw;
  1312. iw.type = EInfoWindowMode::AUTO;
  1313. iw.player = h->tempOwner;
  1314. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1315. assert(ts);
  1316. TeamID team = ts->id;
  1317. if(!wasVisited(team))
  1318. {
  1319. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  1320. cb->sendAndApply(&iw);
  1321. // increment general visited obelisks counter
  1322. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  1323. openWindow(EOpenWindowMode::PUZZLE_MAP, h->tempOwner.getNum());
  1324. // mark that particular obelisk as visited for all players in the team
  1325. for(const auto & color : ts->players)
  1326. {
  1327. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  1328. }
  1329. }
  1330. else
  1331. {
  1332. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  1333. cb->sendAndApply(&iw);
  1334. }
  1335. }
  1336. void CGObelisk::initObj(CRandomGenerator & rand)
  1337. {
  1338. obeliskCount++;
  1339. }
  1340. void CGObelisk::reset()
  1341. {
  1342. obeliskCount = 0;
  1343. visited.clear();
  1344. }
  1345. std::string CGObelisk::getHoverText(PlayerColor player) const
  1346. {
  1347. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1348. }
  1349. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1350. {
  1351. switch(what)
  1352. {
  1353. case CGObelisk::OBJPROP_INC:
  1354. {
  1355. auto progress = ++visited[TeamID(val)];
  1356. logGlobal->debug("Player %d: obelisk progress %d / %d", val, static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1357. if(progress > obeliskCount)
  1358. {
  1359. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1360. throw std::runtime_error("internal error");
  1361. }
  1362. break;
  1363. }
  1364. default:
  1365. CTeamVisited::setPropertyDer(what, val);
  1366. break;
  1367. }
  1368. }
  1369. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1370. {
  1371. if(h->tempOwner != tempOwner)
  1372. {
  1373. PlayerColor oldOwner = tempOwner;
  1374. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1375. h->showInfoDialog(69);
  1376. giveBonusTo(h->tempOwner);
  1377. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1378. {
  1379. RemoveBonus rb(GiveBonus::ETarget::PLAYER);
  1380. rb.whoID = oldOwner.getNum();
  1381. rb.source = vstd::to_underlying(BonusSource::OBJECT);
  1382. rb.id = id.getNum();
  1383. cb->sendAndApply(&rb);
  1384. }
  1385. }
  1386. }
  1387. void CGLighthouse::initObj(CRandomGenerator & rand)
  1388. {
  1389. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1390. {
  1391. // FIXME: This is dirty hack
  1392. giveBonusTo(tempOwner, true);
  1393. }
  1394. }
  1395. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1396. {
  1397. GiveBonus gb(GiveBonus::ETarget::PLAYER);
  1398. gb.bonus.type = BonusType::MOVEMENT;
  1399. gb.bonus.val = 500;
  1400. gb.id = player.getNum();
  1401. gb.bonus.duration = BonusDuration::PERMANENT;
  1402. gb.bonus.source = BonusSource::OBJECT;
  1403. gb.bonus.sid = id.getNum();
  1404. gb.bonus.subtype = 0;
  1405. // FIXME: This is really dirty hack
  1406. // Proper fix would be to make CGLighthouse into bonus system node
  1407. // Unfortunately this will cause saves breakage
  1408. if(onInit)
  1409. gb.applyGs(cb->gameState());
  1410. else
  1411. cb->sendAndApply(&gb);
  1412. }
  1413. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1414. {
  1415. serializeJsonOwner(handler);
  1416. }
  1417. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1418. {
  1419. openWindow(EOpenWindowMode::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  1420. }
  1421. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1422. {
  1423. int32_t level = stack.type->getLevel();
  1424. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1425. int costModifier = upgradeCostPercentage[index];
  1426. if (costModifier < 0)
  1427. return; // upgrade not allowed
  1428. for(const auto & nid : stack.type->upgrades)
  1429. {
  1430. info.newID.push_back(nid);
  1431. info.cost.push_back((nid.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost()) * costModifier / 100);
  1432. }
  1433. }
  1434. VCMI_LIB_NAMESPACE_END