CGameInfoCallback.cpp 28 KB

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