MiscObjects.cpp 31 KB

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