CGameInfoCallback.cpp 29 KB

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