CGameInfoCallback.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /*
  2. * CGameInfoCallback.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 "CGameInfoCallback.h"
  12. #include "../entities/building/CBuilding.h"
  13. #include "../gameState/CGameState.h"
  14. #include "../gameState/UpgradeInfo.h"
  15. #include "../gameState/InfoAboutArmy.h"
  16. #include "../gameState/TavernHeroesPool.h"
  17. #include "../mapObjects/CGHeroInstance.h"
  18. #include "../mapObjects/CGTownInstance.h"
  19. #include "../mapObjects/MiscObjects.h"
  20. #include "../StartInfo.h"
  21. #include "../battle/BattleInfo.h"
  22. #include "../IGameSettings.h"
  23. #include "../spells/CSpellHandler.h"
  24. #include "../mapping/CMap.h"
  25. #include "../CPlayerState.h"
  26. #define ASSERT_IF_CALLED_WITH_PLAYER if(!getPlayerID()) {logGlobal->error(BOOST_CURRENT_FUNCTION); assert(0);}
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. //TODO make clean
  29. #define ERROR_VERBOSE_OR_NOT_RET_VAL_IF(cond, verbose, txt, retVal) do {if(cond){if(verbose)logGlobal->error("%s: %s",BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  30. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return;}} while(0)
  31. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  32. PlayerColor CGameInfoCallback::getOwner(ObjectInstanceID heroID) const
  33. {
  34. const CGObjectInstance *obj = getObj(heroID);
  35. ERROR_RET_VAL_IF(!obj, "No such object!", PlayerColor::CANNOT_DETERMINE);
  36. return obj->tempOwner;
  37. }
  38. int CGameInfoCallback::getResource(PlayerColor Player, GameResID which) const
  39. {
  40. const PlayerState *p = getPlayerState(Player);
  41. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  42. ERROR_RET_VAL_IF(p->resources.size() <= which.getNum() || which.getNum() < 0, "No such resource!", -1);
  43. return p->resources[which];
  44. }
  45. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  46. {
  47. return &gameState().getStartInfo()->getIthPlayersSettings(color);
  48. }
  49. bool CGameInfoCallback::isAllowed(SpellID id) const
  50. {
  51. return gameState().getMap().allowedSpells.count(id) != 0;
  52. }
  53. bool CGameInfoCallback::isAllowed(ArtifactID id) const
  54. {
  55. return gameState().getMap().allowedArtifact.count(id) != 0;
  56. }
  57. bool CGameInfoCallback::isAllowed(SecondarySkill id) const
  58. {
  59. return gameState().getMap().allowedAbilities.count(id) != 0;
  60. }
  61. std::optional<PlayerColor> CGameInfoCallback::getPlayerID() const
  62. {
  63. return std::nullopt;
  64. }
  65. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  66. {
  67. return getPlayerState(color, false);
  68. }
  69. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  70. {
  71. //function written from scratch since it's accessed A LOT by AI
  72. if(!color.isValidPlayer())
  73. {
  74. return nullptr;
  75. }
  76. auto player = gameState().players.find(color);
  77. if (player != gameState().players.end())
  78. {
  79. if (hasAccess(color))
  80. return &player->second;
  81. else
  82. {
  83. if (verbose)
  84. logGlobal->error("Cannot access player %d info!", color);
  85. return nullptr;
  86. }
  87. }
  88. else
  89. {
  90. if (verbose)
  91. logGlobal->error("Cannot find player %d info!", color);
  92. return nullptr;
  93. }
  94. }
  95. TurnTimerInfo CGameInfoCallback::getPlayerTurnTime(PlayerColor color) const
  96. {
  97. if(!color.isValidPlayer())
  98. {
  99. return TurnTimerInfo{};
  100. }
  101. auto player = gameState().players.find(color);
  102. if(player != gameState().players.end())
  103. {
  104. return player->second.turnTimer;
  105. }
  106. return TurnTimerInfo{};
  107. }
  108. /************************************************************************/
  109. /* */
  110. /************************************************************************/
  111. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  112. {
  113. if (!objid.hasValue())
  114. {
  115. if(verbose)
  116. logGlobal->error("Cannot get object with id %d. No such object", objid.getNum());
  117. return nullptr;
  118. }
  119. const CGObjectInstance *ret = gameState().getMap().getObject(objid);
  120. if(!ret)
  121. {
  122. if(verbose)
  123. logGlobal->error("Cannot get object with id %d. Object was removed", objid.getNum());
  124. return nullptr;
  125. }
  126. if(getPlayerID().has_value() && !isVisibleFor(ret, *getPlayerID()) && ret->tempOwner != getPlayerID())
  127. {
  128. if(verbose)
  129. logGlobal->error("Cannot get object with id %d. Object is not visible.", objid.getNum());
  130. return nullptr;
  131. }
  132. return ret;
  133. }
  134. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  135. {
  136. const CGObjectInstance *obj = getObj(objid, false);
  137. if(obj)
  138. return dynamic_cast<const CGHeroInstance*>(obj);
  139. else
  140. return nullptr;
  141. }
  142. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  143. {
  144. const CGObjectInstance *obj = getObj(objid, false);
  145. if(obj)
  146. return dynamic_cast<const CGTownInstance*>(obj);
  147. else
  148. return nullptr;
  149. }
  150. const IMarket * CGameInfoCallback::getMarket(ObjectInstanceID objid) const
  151. {
  152. const CGObjectInstance * obj = getObj(objid, false);
  153. if(obj)
  154. return dynamic_cast<const IMarket*>(obj);
  155. else
  156. return nullptr;
  157. }
  158. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo & out) const
  159. {
  160. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  161. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  162. const auto & stack = obj->getStack(stackPos);
  163. const CCreature *base = stack.getCreature();
  164. UpgradeInfo ret(base->getId());
  165. if (stack.getArmy()->ID == Obj::HERO)
  166. {
  167. auto hero = dynamic_cast<const CGHeroInstance *>(stack.getArmy());
  168. hero->fillUpgradeInfo(ret, stack);
  169. if (hero->getVisitedTown())
  170. {
  171. hero->getVisitedTown()->fillUpgradeInfo(ret, stack);
  172. }
  173. else
  174. {
  175. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  176. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  177. if (object != hero && upgradeSource != nullptr)
  178. upgradeSource->fillUpgradeInfo(ret, stack);
  179. }
  180. }
  181. if (stack.getArmy()->ID == Obj::TOWN)
  182. {
  183. auto town = dynamic_cast<const CGTownInstance *>(stack.getArmy());
  184. town->fillUpgradeInfo(ret, stack);
  185. }
  186. out = ret;
  187. }
  188. const StartInfo * CGameInfoCallback::getStartInfo() const
  189. {
  190. return gameState().getStartInfo();
  191. }
  192. const StartInfo * CGameInfoCallback::getInitialStartInfo() const
  193. {
  194. return gameState().getInitialStartInfo();
  195. }
  196. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  197. {
  198. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  199. //if there is a battle
  200. auto casterBattle = gameState().getBattle(caster->getOwner());
  201. if(casterBattle)
  202. return casterBattle->battleGetSpellCost(sp, caster);
  203. //if there is no battle
  204. return caster->getSpellCost(sp);
  205. }
  206. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  207. {
  208. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  209. if(hero) //we see hero's spellbook
  210. return sp->calculateDamage(hero);
  211. else
  212. return 0; //mage guild
  213. }
  214. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  215. {
  216. ERROR_RET_IF(!obj, "No guild object!");
  217. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  218. //TODO: advmap object -> check if they're visited by our hero
  219. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  220. {
  221. int taverns = gameState().players.at(*getPlayerID()).valOfBonuses(BonusType::THIEVES_GUILD_ACCESS);
  222. gameState().obtainPlayersStats(thi, taverns);
  223. }
  224. else if(obj->ID == Obj::DEN_OF_THIEVES)
  225. {
  226. gameState().obtainPlayersStats(thi, 20);
  227. }
  228. }
  229. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  230. {
  231. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  232. return static_cast<int>(gameState().players.at(Player).getTowns().size());
  233. }
  234. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  235. {
  236. ERROR_RET_VAL_IF(getPlayerID().has_value() && !isVisibleFor(town, *getPlayerID()), "Town is not visible!", false); //it's not a town or it's not visible for layer
  237. bool detailed = hasAccess(town->tempOwner);
  238. if(town->ID == Obj::TOWN)
  239. {
  240. if(!detailed && nullptr != selectedObject)
  241. {
  242. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  243. if(nullptr != selectedHero)
  244. detailed = selectedHero->hasVisions(town, BonusCustomSubtype::visionsTowns);
  245. }
  246. dest.initFromTown(dynamic_cast<const CGTownInstance *>(town), detailed);
  247. }
  248. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  249. dest.initFromArmy(dynamic_cast<const CArmedInstance *>(town), detailed);
  250. else
  251. return false;
  252. return true;
  253. }
  254. const IGameSettings & CGameInfoCallback::getSettings() const
  255. {
  256. return gameState().getSettings();
  257. }
  258. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const
  259. {
  260. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  261. return gameState().getMap().guardingCreaturePositions[pos.z][pos.x][pos.y];
  262. }
  263. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  264. {
  265. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  266. std::vector<const CGObjectInstance*> ret;
  267. for(auto * cr : gameState().guardingCreatures(pos))
  268. {
  269. ret.push_back(cr);
  270. }
  271. return ret;
  272. }
  273. bool CGameInfoCallback::isTileGuardedUnchecked(int3 tile) const
  274. {
  275. return !gameState().guardingCreatures(tile).empty();
  276. }
  277. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  278. {
  279. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  280. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  281. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  282. if(hasAccess(h->tempOwner))
  283. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  284. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  285. {
  286. auto ourBattle = gameState().getBattle(*getPlayerID());
  287. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  288. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  289. else
  290. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  291. }
  292. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  293. {
  294. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  295. if(nullptr != selectedHero)
  296. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  297. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  298. }
  299. dest.initFromHero(h, infoLevel);
  300. //DISGUISED bonus implementation
  301. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  302. {
  303. //todo: bonus cashing
  304. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  305. auto doBasicDisguise = [](InfoAboutHero & info)
  306. {
  307. int maxAIValue = 0;
  308. const CCreature * mostStrong = nullptr;
  309. for(auto & elem : info.army)
  310. {
  311. if(static_cast<int>(elem.second.getCreature()->getAIValue()) > maxAIValue)
  312. {
  313. maxAIValue = elem.second.getCreature()->getAIValue();
  314. mostStrong = elem.second.getCreature();
  315. }
  316. }
  317. if(nullptr == mostStrong)//just in case
  318. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  319. else
  320. for(auto & elem : info.army)
  321. {
  322. elem.second.setType(mostStrong);
  323. }
  324. };
  325. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  326. {
  327. doBasicDisguise(info);
  328. for(auto & elem : info.army)
  329. elem.second.setCount(0);
  330. };
  331. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  332. {
  333. for(auto & elem : info.army)
  334. elem.second.setCount(0);
  335. const auto factionIndex = getStartInfo()->playerInfos.at(h->tempOwner).castle;
  336. int maxAIValue = 0;
  337. const CCreature * mostStrong = nullptr;
  338. for(const auto & creature : LIBRARY->creh->objects)
  339. {
  340. if(creature->getFactionID() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  341. {
  342. maxAIValue = creature->getAIValue();
  343. mostStrong = creature.get();
  344. }
  345. }
  346. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  347. for(auto & elem : info.army)
  348. elem.second.setType(mostStrong);
  349. };
  350. switch (disguiseLevel)
  351. {
  352. case 0:
  353. //no bonus at all - do nothing
  354. break;
  355. case 1:
  356. doBasicDisguise(dest);
  357. break;
  358. case 2:
  359. doAdvancedDisguise(dest);
  360. break;
  361. case 3:
  362. doExpertDisguise(dest);
  363. break;
  364. default:
  365. //invalid value
  366. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  367. break;
  368. }
  369. }
  370. return true;
  371. }
  372. int CGameInfoCallback::getDate(Date mode) const
  373. {
  374. return gameState().getDate(mode);
  375. }
  376. bool CGameInfoCallback::isVisibleFor(int3 pos, PlayerColor player) const
  377. {
  378. return gameState().isVisibleFor(pos, player);
  379. }
  380. bool CGameInfoCallback::isVisible(int3 pos) const
  381. {
  382. if (!getPlayerID().has_value())
  383. return true; // weird, but we do have such calls
  384. return gameState().isVisibleFor(pos, *getPlayerID());
  385. }
  386. bool CGameInfoCallback::isVisibleFor(const CGObjectInstance * obj, PlayerColor player) const
  387. {
  388. return gameState().isVisibleFor(obj, player);
  389. }
  390. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  391. {
  392. if (!getPlayerID().has_value())
  393. return true; // weird, but we do have such calls
  394. return gameState().isVisibleFor(obj, *getPlayerID());
  395. }
  396. std::vector <const CGObjectInstance *> CGameInfoCallback::getBlockingObjs( int3 pos ) const
  397. {
  398. std::vector<const CGObjectInstance *> ret;
  399. const TerrainTile *t = getTile(pos);
  400. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  401. for(const auto & objID : t->blockingObjects)
  402. ret.push_back(getObj(objID));
  403. return ret;
  404. }
  405. std::vector <const CGObjectInstance *> CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  406. {
  407. std::vector<const CGObjectInstance *> ret;
  408. const TerrainTile *t = getTile(pos, verbose);
  409. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  410. for(const auto & objID : t->visitableObjects)
  411. {
  412. const auto & object = getObj(objID, false);
  413. if (!object)
  414. continue; // event - visitable, but not visible
  415. if(!getPlayerID().has_value() || object->ID != Obj::EVENT) //hide events from players
  416. ret.push_back(object);
  417. }
  418. return ret;
  419. }
  420. std::vector<const CGObjectInstance *> CGameInfoCallback::getAllVisitableObjs() const
  421. {
  422. std::vector<const CGObjectInstance *> ret;
  423. for(auto & obj : gameState().getMap().getObjects())
  424. if(obj->isVisitable() && obj->ID != Obj::EVENT && isVisible(obj))
  425. ret.push_back(obj);
  426. return ret;
  427. }
  428. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  429. {
  430. return vstd::backOrNull(getVisitableObjs(pos));
  431. }
  432. std::vector <const CGObjectInstance *> CGameInfoCallback::getFlaggableObjects(int3 pos) const
  433. {
  434. std::vector<const CGObjectInstance *> ret;
  435. const TerrainTile *t = getTile(pos);
  436. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  437. for(const auto & objectID : t->blockingObjects)
  438. {
  439. const auto * obj = getObj(objectID);
  440. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  441. ret.push_back(obj);
  442. }
  443. return ret;
  444. }
  445. int3 CGameInfoCallback::getMapSize() const
  446. {
  447. return int3(gameState().getMap().width, gameState().getMap().height, gameState().getMap().twoLevel ? 2 : 1);
  448. }
  449. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  450. {
  451. ASSERT_IF_CALLED_WITH_PLAYER
  452. std::vector<const CGHeroInstance *> ret;
  453. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  454. const CGTownInstance * town = getTown(townOrTavern->id);
  455. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  456. return gameState().heroesPool->getHeroesFor(*getPlayerID());
  457. return ret;
  458. }
  459. const TerrainTile * CGameInfoCallback::getTile(int3 tile, bool verbose) const
  460. {
  461. if(isVisible(tile))
  462. return &gameState().getMap().getTile(tile);
  463. if(verbose)
  464. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  465. return nullptr;
  466. }
  467. const TerrainTile * CGameInfoCallback::getTileUnchecked(int3 tile) const
  468. {
  469. if (isInTheMap(tile))
  470. return &gameState().getMap().getTile(tile);
  471. return nullptr;
  472. }
  473. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  474. {
  475. if(!isVisible(tile))
  476. return EDiggingStatus::UNKNOWN;
  477. for(const auto & object : gameState().getMap().getObjects())
  478. {
  479. if(object->ID == Obj::HOLE && object->anchorPos() == tile)
  480. return EDiggingStatus::TILE_OCCUPIED;
  481. }
  482. return getTile(tile)->getDiggingStatus();
  483. }
  484. EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  485. {
  486. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  487. if(!t->getTown()->buildings.count(ID))
  488. return EBuildingState::BUILDING_ERROR;
  489. const auto & building = t->getTown()->buildings.at(ID);
  490. if(t->hasBuilt(ID)) //already built
  491. return EBuildingState::ALREADY_PRESENT;
  492. //can we build it?
  493. if(vstd::contains(t->forbiddenBuildings, ID))
  494. return EBuildingState::FORBIDDEN; //forbidden
  495. auto possiblyNotBuiltTest = [&](const BuildingID & id) -> bool
  496. {
  497. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  498. };
  499. std::function<bool(BuildingID id)> allowedTest = [&](const BuildingID & id) -> bool
  500. {
  501. return !vstd::contains(t->forbiddenBuildings, id);
  502. };
  503. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  504. return EBuildingState::FORBIDDEN;
  505. if(ID == BuildingID::CAPITOL)
  506. {
  507. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  508. if(ps)
  509. {
  510. for(const CGTownInstance *town : ps->getTowns())
  511. {
  512. if(town->hasBuilt(BuildingID::CAPITOL))
  513. {
  514. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  515. }
  516. }
  517. }
  518. }
  519. else if(ID == BuildingID::SHIPYARD)
  520. {
  521. const TerrainTile *tile = getTile(t->bestLocation(), false);
  522. if(!tile || !tile->isWater())
  523. return EBuildingState::NO_WATER; //lack of water
  524. }
  525. auto buildTest = [&](const BuildingID & id) -> bool
  526. {
  527. return t->hasBuilt(id);
  528. };
  529. if (!t->genBuildingRequirements(ID).test(buildTest))
  530. return EBuildingState::PREREQUIRES;
  531. if(t->built >= getSettings().getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  532. return EBuildingState::CANT_BUILD_TODAY; //building limit
  533. //checking resources
  534. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  535. return EBuildingState::NO_RESOURCES; //lack of res
  536. return EBuildingState::ALLOWED;
  537. }
  538. const CMapHeader * CGameInfoCallback::getMapHeader() const
  539. {
  540. return &gameState().getMap();
  541. }
  542. bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
  543. {
  544. return !getPlayerID() || getPlayerID()->isSpectator() || getPlayerRelations(*playerId, *getPlayerID()) != PlayerRelations::ENEMIES;
  545. }
  546. EPlayerStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  547. {
  548. const PlayerState *ps = gameState().getPlayerState(player, verbose);
  549. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  550. return ps->status;
  551. }
  552. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  553. {
  554. MetaString text;
  555. text.appendLocalString(EMetaText::GENERAL_TXT, 216);
  556. std::string extraText;
  557. if(gameState().currentRumor.type == RumorState::TYPE_NONE)
  558. return text.toString();
  559. auto rumor = gameState().currentRumor.last.at(gameState().currentRumor.type);
  560. switch(gameState().currentRumor.type)
  561. {
  562. case RumorState::TYPE_SPECIAL:
  563. text.replaceLocalString(EMetaText::GENERAL_TXT, rumor.first);
  564. if(rumor.first == RumorState::RUMOR_GRAIL)
  565. text.replaceTextID(TextIdentifier("core", "arraytxt", 158 + rumor.second).get());
  566. else
  567. text.replaceTextID(TextIdentifier("core", "plcolors", rumor.second).get());
  568. break;
  569. case RumorState::TYPE_MAP:
  570. text.replaceRawString(gameState().getMap().rumors[rumor.first].text.toString());
  571. break;
  572. case RumorState::TYPE_RAND:
  573. text.replaceTextID(TextIdentifier("core", "randtvrn", rumor.first).get());
  574. break;
  575. }
  576. return text.toString();
  577. }
  578. PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  579. {
  580. return gameState().getPlayerRelations(color1, color2);
  581. }
  582. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  583. {
  584. return !obj || hasAccess(obj->tempOwner);
  585. }
  586. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  587. {
  588. int ret = 0;
  589. const PlayerState *p = gameState().getPlayerState(player);
  590. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  591. if(includeGarrisoned)
  592. return static_cast<int>(p->getHeroes().size());
  593. else
  594. for(const auto & elem : p->getHeroes())
  595. if(!elem->isGarrisoned())
  596. ret++;
  597. return ret;
  598. }
  599. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  600. {
  601. return gameState().actingPlayers.count(player);
  602. }
  603. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  604. {
  605. //rewritten by hand, AI calls this function a lot
  606. auto team = gameState().teams.find(teamID);
  607. if (team != gameState().teams.end())
  608. {
  609. const TeamState *ret = &team->second;
  610. if(!getPlayerID().has_value()) //neutral (or invalid) player
  611. return ret;
  612. else
  613. {
  614. if (vstd::contains(ret->players, *getPlayerID())) //specific player
  615. return ret;
  616. else
  617. {
  618. logGlobal->error("Illegal attempt to access team data!");
  619. return nullptr;
  620. }
  621. }
  622. }
  623. else
  624. {
  625. logGlobal->error("Cannot find info for team %d", teamID);
  626. return nullptr;
  627. }
  628. }
  629. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  630. {
  631. auto player = gameState().players.find(color);
  632. if (player != gameState().players.end())
  633. {
  634. return getTeam (player->second.team);
  635. }
  636. else
  637. {
  638. return nullptr;
  639. }
  640. }
  641. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  642. {
  643. return gameState().getMap().isInTheMap(pos);
  644. }
  645. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  646. {
  647. gameState().getTilesInRange(tiles, pos, radious, ETileVisibility::REVEALED, *getPlayerID(), distanceFormula);
  648. }
  649. void CGameInfoCallback::calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const
  650. {
  651. gameState().calculatePaths(config);
  652. }
  653. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  654. {
  655. return gameState().getMap().getArtifactInstance(aid);
  656. }
  657. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  658. {
  659. return gameState().getMap().getObject((oid));
  660. }
  661. const CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  662. {
  663. auto & gs = const_cast<CGameState&>(gameState());
  664. return gs.getArtSet(loc);
  665. }
  666. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  667. {
  668. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  669. {
  670. const auto * obj = getObj(id, false);
  671. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisibleFor(obj->visitablePos(), player));
  672. });
  673. return ids;
  674. }
  675. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntrances(TeleportChannelID id, PlayerColor player) const
  676. {
  677. return getVisibleTeleportObjects(gameState().getMap().teleportChannels.at(id)->entrances, player);
  678. }
  679. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  680. {
  681. return getVisibleTeleportObjects(gameState().getMap().teleportChannels.at(id)->exits, player);
  682. }
  683. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  684. {
  685. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntrances(id, player);
  686. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  687. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  688. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  689. {
  690. return ETeleportChannelType::IMPASSABLE;
  691. }
  692. auto intersection = vstd::intersection(entrances, exits);
  693. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  694. return ETeleportChannelType::BIDIRECTIONAL;
  695. else if(intersection.empty())
  696. return ETeleportChannelType::UNIDIRECTIONAL;
  697. else
  698. return ETeleportChannelType::MIXED;
  699. }
  700. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  701. {
  702. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  703. }
  704. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  705. {
  706. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  707. }
  708. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  709. {
  710. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  711. }
  712. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  713. {
  714. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  715. }
  716. void CGameInfoCallback::getFreeTiles(std::vector<int3> & tiles) const
  717. {
  718. std::vector<int> floors;
  719. floors.reserve(gameState().getMap().levels());
  720. for(int b = 0; b < gameState().getMap().levels(); ++b)
  721. {
  722. floors.push_back(b);
  723. }
  724. const TerrainTile * tinfo = nullptr;
  725. for (auto zd : floors)
  726. {
  727. for (int xd = 0; xd < gameState().getMap().width; xd++)
  728. {
  729. for (int yd = 0; yd < gameState().getMap().height; yd++)
  730. {
  731. tinfo = getTile(int3 (xd,yd,zd));
  732. if (tinfo->isLand() && tinfo->getTerrain()->isPassable() && !tinfo->blocked()) //land and free
  733. tiles.emplace_back(xd, yd, zd);
  734. }
  735. }
  736. }
  737. }
  738. void CGameInfoCallback::getTilesInRange(std::unordered_set<int3> & tiles,
  739. const int3 & pos,
  740. int radious,
  741. ETileVisibility mode,
  742. std::optional<PlayerColor> player,
  743. int3::EDistanceFormula distanceFormula) const
  744. {
  745. if(player.has_value() && !player->isValidPlayer())
  746. {
  747. logGlobal->error("Illegal call to getTilesInRange!");
  748. return;
  749. }
  750. if(radious == CBuilding::HEIGHT_SKYSHIP) //reveal entire map
  751. getAllTiles (tiles, player, -1, [](auto * tile){return true;});
  752. else
  753. {
  754. const TeamState * team = !player ? nullptr : gameState().getPlayerTeam(*player);
  755. for (int xd = std::max<int>(pos.x - radious , 0); xd <= std::min<int>(pos.x + radious, gameState().getMap().width - 1); xd++)
  756. {
  757. for (int yd = std::max<int>(pos.y - radious, 0); yd <= std::min<int>(pos.y + radious, gameState().getMap().height - 1); yd++)
  758. {
  759. int3 tilePos(xd,yd,pos.z);
  760. int distance = pos.dist(tilePos, distanceFormula);
  761. if(distance <= radious)
  762. {
  763. if(!player
  764. || (mode == ETileVisibility::HIDDEN && team->fogOfWarMap[pos.z][xd][yd] == 0)
  765. || (mode == ETileVisibility::REVEALED && team->fogOfWarMap[pos.z][xd][yd] == 1)
  766. )
  767. tiles.insert(int3(xd,yd,pos.z));
  768. }
  769. }
  770. }
  771. }
  772. }
  773. void CGameInfoCallback::getAllTiles(std::unordered_set<int3> & tiles, std::optional<PlayerColor> Player, int level, std::function<bool(const TerrainTile *)> filter) const
  774. {
  775. if(Player.has_value() && !Player->isValidPlayer())
  776. {
  777. logGlobal->error("Illegal call to getAllTiles !");
  778. return;
  779. }
  780. std::vector<int> floors;
  781. if(level == -1)
  782. {
  783. for(int b = 0; b < gameState().getMap().levels(); ++b)
  784. {
  785. floors.push_back(b);
  786. }
  787. }
  788. else
  789. floors.push_back(level);
  790. for(auto zd: floors)
  791. {
  792. for(int xd = 0; xd < gameState().getMap().width; xd++)
  793. {
  794. for(int yd = 0; yd < gameState().getMap().height; yd++)
  795. {
  796. int3 coordinates(xd, yd, zd);
  797. if (filter(getTile(coordinates)))
  798. tiles.insert(coordinates);
  799. }
  800. }
  801. }
  802. }
  803. void CGameInfoCallback::pickAllowedArtsSet(std::vector<ArtifactID> & out, vstd::RNG & rand)
  804. {
  805. for (int j = 0; j < 3 ; j++)
  806. out.push_back(gameState().pickRandomArtifact(rand, EArtifactClass::ART_TREASURE));
  807. for (int j = 0; j < 3 ; j++)
  808. out.push_back(gameState().pickRandomArtifact(rand, EArtifactClass::ART_MINOR));
  809. out.push_back(gameState().pickRandomArtifact(rand, EArtifactClass::ART_MAJOR));
  810. }
  811. void CGameInfoCallback::getAllowedSpells(std::vector<SpellID> & out, std::optional<ui16> level)
  812. {
  813. for (auto const & spellID : gameState().getMap().allowedSpells)
  814. {
  815. const auto * spell = spellID.toEntity(LIBRARY);
  816. if (!isAllowed(spellID))
  817. continue;
  818. if (level.has_value() && spell->getLevel() != level)
  819. continue;
  820. out.push_back(spellID);
  821. }
  822. }
  823. #if SCRIPTING_ENABLED
  824. scripting::Pool * CGameInfoCallback::getGlobalContextPool() const
  825. {
  826. return nullptr; // TODO
  827. }
  828. #endif
  829. VCMI_LIB_NAMESPACE_END