CGameInfoCallback.cpp 28 KB

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