MiscObjects.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  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. int3 CGBoat::translatePos(const int3& pos, bool reverse /* = false */)
  1138. {
  1139. //pos - offset we want to place the boat at the map
  1140. //returned value - actual position as seen by game mechanics
  1141. //If reverse = true, then it's the opposite.
  1142. if (!reverse)
  1143. {
  1144. return pos + int3(1, 0, 0);
  1145. }
  1146. else
  1147. {
  1148. return pos - int3(1, 0, 0);
  1149. }
  1150. }
  1151. void CGSirens::initObj(CRandomGenerator & rand)
  1152. {
  1153. blockVisit = true;
  1154. }
  1155. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1156. {
  1157. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT,ID));
  1158. }
  1159. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1160. {
  1161. InfoWindow iw;
  1162. iw.player = h->tempOwner;
  1163. if(h->hasBonusFrom(BonusSource::OBJECT,ID)) //has already visited Sirens
  1164. {
  1165. iw.type = EInfoWindowMode::AUTO;
  1166. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  1167. }
  1168. else
  1169. {
  1170. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  1171. TExpType xp = 0;
  1172. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1173. {
  1174. // 1-sized stacks are not affected by sirens
  1175. if (i->second->count == 1)
  1176. continue;
  1177. // tested H3 behavior: 30% (rounded up) of stack drowns
  1178. TQuantity drown = std::ceil(i->second->count * 0.3);
  1179. if(drown)
  1180. {
  1181. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1182. xp += drown * i->second->type->getMaxHealth();
  1183. }
  1184. }
  1185. if(xp)
  1186. {
  1187. xp = h->calculateXp(static_cast<int>(xp));
  1188. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  1189. iw.text.replaceNumber(static_cast<int>(xp));
  1190. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1191. }
  1192. else
  1193. {
  1194. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  1195. }
  1196. }
  1197. cb->showInfoDialog(&iw);
  1198. }
  1199. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1200. {
  1201. // H J L K I
  1202. // A x S x B
  1203. // C E G F D
  1204. offsets = {
  1205. int3(-3,0,0), int3(1,0,0), //AB
  1206. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  1207. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0) //HIJKL
  1208. };
  1209. }
  1210. const IObjectInterface * CGShipyard::getObject() const
  1211. {
  1212. return this;
  1213. }
  1214. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1215. {
  1216. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  1217. cb->setOwner(this, h->tempOwner);
  1218. auto s = shipyardStatus();
  1219. if(s != IBoatGenerator::GOOD)
  1220. {
  1221. InfoWindow iw;
  1222. iw.type = EInfoWindowMode::AUTO;
  1223. iw.player = tempOwner;
  1224. getProblemText(iw.text, h);
  1225. cb->showInfoDialog(&iw);
  1226. }
  1227. else
  1228. {
  1229. openWindow(EOpenWindowMode::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1230. }
  1231. }
  1232. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1233. {
  1234. serializeJsonOwner(handler);
  1235. }
  1236. BoatId CGShipyard::getBoatType() const
  1237. {
  1238. // In H3, external shipyard will always create same boat as castle
  1239. return EBoatId::CASTLE;
  1240. }
  1241. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1242. {
  1243. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1244. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1245. {
  1246. if (cb->getResource(h->tempOwner, EGameResID::GOLD) >= 1000) //if he can afford a map
  1247. {
  1248. //ask if he wants to buy one
  1249. int text=0;
  1250. switch (subID)
  1251. {
  1252. case 0:
  1253. text = 25;
  1254. break;
  1255. case 1:
  1256. text = 26;
  1257. break;
  1258. case 2:
  1259. text = 27;
  1260. break;
  1261. default:
  1262. logGlobal->warn("Unrecognized subtype of cartographer");
  1263. }
  1264. assert(text);
  1265. BlockingDialog bd (true, false);
  1266. bd.player = h->getOwner();
  1267. bd.text.appendLocalString (EMetaText::ADVOB_TXT, text);
  1268. cb->showBlockingDialog (&bd);
  1269. }
  1270. else //if he cannot afford
  1271. {
  1272. h->showInfoDialog(28);
  1273. }
  1274. }
  1275. else //if he already visited carographer
  1276. {
  1277. h->showInfoDialog(24);
  1278. }
  1279. }
  1280. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1281. {
  1282. if(answer) //if hero wants to buy map
  1283. {
  1284. cb->giveResource(hero->tempOwner, EGameResID::GOLD, -1000);
  1285. FoWChange fw;
  1286. fw.mode = 1;
  1287. fw.player = hero->tempOwner;
  1288. //subIDs of different types of cartographers:
  1289. //water = 0; land = 1; underground = 2;
  1290. IGameCallback::MapTerrainFilterMode tileFilterMode = IGameCallback::MapTerrainFilterMode::NONE;
  1291. switch(subID)
  1292. {
  1293. case 0:
  1294. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::WATER;
  1295. break;
  1296. case 1:
  1297. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::LAND_CARTOGRAPHER;
  1298. break;
  1299. case 2:
  1300. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::UNDERGROUND_CARTOGRAPHER;
  1301. break;
  1302. }
  1303. cb->getAllTiles(fw.tiles, hero->tempOwner, -1, tileFilterMode); //reveal appropriate tiles
  1304. cb->sendAndApply(&fw);
  1305. cb->setObjProperty(id, CCartographer::OBJPROP_VISITED, hero->tempOwner.getNum());
  1306. }
  1307. }
  1308. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1309. {
  1310. cb->showThievesGuildWindow(h->tempOwner, id);
  1311. }
  1312. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1313. {
  1314. InfoWindow iw;
  1315. iw.type = EInfoWindowMode::AUTO;
  1316. iw.player = h->tempOwner;
  1317. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1318. assert(ts);
  1319. TeamID team = ts->id;
  1320. if(!wasVisited(team))
  1321. {
  1322. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  1323. cb->sendAndApply(&iw);
  1324. // increment general visited obelisks counter
  1325. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  1326. openWindow(EOpenWindowMode::PUZZLE_MAP, h->tempOwner.getNum());
  1327. // mark that particular obelisk as visited for all players in the team
  1328. for(const auto & color : ts->players)
  1329. {
  1330. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  1331. }
  1332. }
  1333. else
  1334. {
  1335. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  1336. cb->sendAndApply(&iw);
  1337. }
  1338. }
  1339. void CGObelisk::initObj(CRandomGenerator & rand)
  1340. {
  1341. obeliskCount++;
  1342. }
  1343. void CGObelisk::reset()
  1344. {
  1345. obeliskCount = 0;
  1346. visited.clear();
  1347. }
  1348. std::string CGObelisk::getHoverText(PlayerColor player) const
  1349. {
  1350. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1351. }
  1352. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1353. {
  1354. switch(what)
  1355. {
  1356. case CGObelisk::OBJPROP_INC:
  1357. {
  1358. auto progress = ++visited[TeamID(val)];
  1359. logGlobal->debug("Player %d: obelisk progress %d / %d", val, static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1360. if(progress > obeliskCount)
  1361. {
  1362. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1363. throw std::runtime_error("internal error");
  1364. }
  1365. break;
  1366. }
  1367. default:
  1368. CTeamVisited::setPropertyDer(what, val);
  1369. break;
  1370. }
  1371. }
  1372. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1373. {
  1374. if(h->tempOwner != tempOwner)
  1375. {
  1376. PlayerColor oldOwner = tempOwner;
  1377. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1378. h->showInfoDialog(69);
  1379. giveBonusTo(h->tempOwner);
  1380. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1381. {
  1382. RemoveBonus rb(GiveBonus::ETarget::PLAYER);
  1383. rb.whoID = oldOwner.getNum();
  1384. rb.source = vstd::to_underlying(BonusSource::OBJECT);
  1385. rb.id = id.getNum();
  1386. cb->sendAndApply(&rb);
  1387. }
  1388. }
  1389. }
  1390. void CGLighthouse::initObj(CRandomGenerator & rand)
  1391. {
  1392. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1393. {
  1394. // FIXME: This is dirty hack
  1395. giveBonusTo(tempOwner, true);
  1396. }
  1397. }
  1398. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1399. {
  1400. GiveBonus gb(GiveBonus::ETarget::PLAYER);
  1401. gb.bonus.type = BonusType::MOVEMENT;
  1402. gb.bonus.val = 500;
  1403. gb.id = player.getNum();
  1404. gb.bonus.duration = BonusDuration::PERMANENT;
  1405. gb.bonus.source = BonusSource::OBJECT;
  1406. gb.bonus.sid = id.getNum();
  1407. gb.bonus.subtype = 0;
  1408. // FIXME: This is really dirty hack
  1409. // Proper fix would be to make CGLighthouse into bonus system node
  1410. // Unfortunately this will cause saves breakage
  1411. if(onInit)
  1412. gb.applyGs(cb->gameState());
  1413. else
  1414. cb->sendAndApply(&gb);
  1415. }
  1416. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1417. {
  1418. serializeJsonOwner(handler);
  1419. }
  1420. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1421. {
  1422. openWindow(EOpenWindowMode::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  1423. }
  1424. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1425. {
  1426. int32_t level = stack.type->getLevel();
  1427. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1428. int costModifier = upgradeCostPercentage[index];
  1429. if (costModifier < 0)
  1430. return; // upgrade not allowed
  1431. for(const auto & nid : stack.type->upgrades)
  1432. {
  1433. info.newID.push_back(nid);
  1434. info.cost.push_back((nid.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost()) * costModifier / 100);
  1435. }
  1436. }
  1437. VCMI_LIB_NAMESPACE_END