CGameInfoCallback.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  379. // {
  380. // //std::shared_lock<std::shared_mutex> lock(*gameState()->mx);
  381. // if()
  382. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  383. // if(!armi)
  384. // return nullptr;
  385. // else
  386. // return armi;
  387. // }
  388. std::vector <const CGObjectInstance *> CGameInfoCallback::getBlockingObjs( int3 pos ) const
  389. {
  390. std::vector<const CGObjectInstance *> ret;
  391. const TerrainTile *t = getTile(pos);
  392. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  393. for(const auto & objID : t->blockingObjects)
  394. ret.push_back(getObj(objID));
  395. return ret;
  396. }
  397. std::vector <const CGObjectInstance *> CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  398. {
  399. std::vector<const CGObjectInstance *> ret;
  400. const TerrainTile *t = getTile(pos, verbose);
  401. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  402. for(const auto & objID : t->visitableObjects)
  403. {
  404. const auto & object = getObj(objID);
  405. if(!getPlayerID().has_value() || object->ID != Obj::EVENT) //hide events from players
  406. ret.push_back(object);
  407. }
  408. return ret;
  409. }
  410. std::vector<const CGObjectInstance *> CGameInfoCallback::getAllVisitableObjs() const
  411. {
  412. std::vector<const CGObjectInstance *> ret;
  413. for(auto & obj : gameState()->getMap().getObjects())
  414. if(obj->isVisitable() && obj->ID != Obj::EVENT && isVisible(obj))
  415. ret.push_back(obj);
  416. return ret;
  417. }
  418. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  419. {
  420. return vstd::backOrNull(getVisitableObjs(pos));
  421. }
  422. std::vector <const CGObjectInstance *> CGameInfoCallback::getFlaggableObjects(int3 pos) const
  423. {
  424. std::vector<const CGObjectInstance *> ret;
  425. const TerrainTile *t = getTile(pos);
  426. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  427. for(const auto & objectID : t->blockingObjects)
  428. {
  429. const auto * obj = getObj(objectID);
  430. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  431. ret.push_back(obj);
  432. }
  433. return ret;
  434. }
  435. int3 CGameInfoCallback::getMapSize() const
  436. {
  437. return int3(gameState()->getMap().width, gameState()->getMap().height, gameState()->getMap().twoLevel ? 2 : 1);
  438. }
  439. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  440. {
  441. ASSERT_IF_CALLED_WITH_PLAYER
  442. std::vector<const CGHeroInstance *> ret;
  443. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  444. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  445. const CGTownInstance * town = getTown(townOrTavern->id);
  446. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  447. return gameState()->heroesPool->getHeroesFor(*getPlayerID());
  448. return ret;
  449. }
  450. const TerrainTile * CGameInfoCallback::getTile(int3 tile, bool verbose) const
  451. {
  452. if(isVisible(tile))
  453. return &gameState()->getMap().getTile(tile);
  454. if(verbose)
  455. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  456. return nullptr;
  457. }
  458. const TerrainTile * CGameInfoCallback::getTileUnchecked(int3 tile) const
  459. {
  460. if (isInTheMap(tile))
  461. return &gameState()->getMap().getTile(tile);
  462. return nullptr;
  463. }
  464. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  465. {
  466. if(!isVisible(tile))
  467. return EDiggingStatus::UNKNOWN;
  468. for(const auto & object : gameState()->getMap().getObjects())
  469. {
  470. if(object->ID == Obj::HOLE && object->anchorPos() == tile)
  471. return EDiggingStatus::TILE_OCCUPIED;
  472. }
  473. return getTile(tile)->getDiggingStatus();
  474. }
  475. EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  476. {
  477. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  478. if(!t->getTown()->buildings.count(ID))
  479. return EBuildingState::BUILDING_ERROR;
  480. const auto & building = t->getTown()->buildings.at(ID);
  481. if(t->hasBuilt(ID)) //already built
  482. return EBuildingState::ALREADY_PRESENT;
  483. //can we build it?
  484. if(vstd::contains(t->forbiddenBuildings, ID))
  485. return EBuildingState::FORBIDDEN; //forbidden
  486. auto possiblyNotBuiltTest = [&](const BuildingID & id) -> bool
  487. {
  488. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  489. };
  490. std::function<bool(BuildingID id)> allowedTest = [&](const BuildingID & id) -> bool
  491. {
  492. return !vstd::contains(t->forbiddenBuildings, id);
  493. };
  494. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  495. return EBuildingState::FORBIDDEN;
  496. if(ID == BuildingID::CAPITOL)
  497. {
  498. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  499. if(ps)
  500. {
  501. for(const CGTownInstance *town : ps->getTowns())
  502. {
  503. if(town->hasBuilt(BuildingID::CAPITOL))
  504. {
  505. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  506. }
  507. }
  508. }
  509. }
  510. else if(ID == BuildingID::SHIPYARD)
  511. {
  512. const TerrainTile *tile = getTile(t->bestLocation(), false);
  513. if(!tile || !tile->isWater())
  514. return EBuildingState::NO_WATER; //lack of water
  515. }
  516. auto buildTest = [&](const BuildingID & id) -> bool
  517. {
  518. return t->hasBuilt(id);
  519. };
  520. if (!t->genBuildingRequirements(ID).test(buildTest))
  521. return EBuildingState::PREREQUIRES;
  522. if(t->built >= getSettings().getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  523. return EBuildingState::CANT_BUILD_TODAY; //building limit
  524. //checking resources
  525. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  526. return EBuildingState::NO_RESOURCES; //lack of res
  527. return EBuildingState::ALLOWED;
  528. }
  529. const CMapHeader * CGameInfoCallback::getMapHeader() const
  530. {
  531. return &gameState()->getMap();
  532. }
  533. bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
  534. {
  535. return !getPlayerID() || getPlayerID()->isSpectator() || gameState()->getPlayerRelations(*playerId, *getPlayerID()) != PlayerRelations::ENEMIES;
  536. }
  537. EPlayerStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  538. {
  539. const PlayerState *ps = gameState()->getPlayerState(player, verbose);
  540. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  541. return ps->status;
  542. }
  543. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  544. {
  545. MetaString text;
  546. text.appendLocalString(EMetaText::GENERAL_TXT, 216);
  547. std::string extraText;
  548. if(gameState()->currentRumor.type == RumorState::TYPE_NONE)
  549. return text.toString();
  550. auto rumor = gameState()->currentRumor.last.at(gameState()->currentRumor.type);
  551. switch(gameState()->currentRumor.type)
  552. {
  553. case RumorState::TYPE_SPECIAL:
  554. text.replaceLocalString(EMetaText::GENERAL_TXT, rumor.first);
  555. if(rumor.first == RumorState::RUMOR_GRAIL)
  556. text.replaceTextID(TextIdentifier("core", "arraytxt", 158 + rumor.second).get());
  557. else
  558. text.replaceTextID(TextIdentifier("core", "plcolors", rumor.second).get());
  559. break;
  560. case RumorState::TYPE_MAP:
  561. text.replaceRawString(gameState()->getMap().rumors[rumor.first].text.toString());
  562. break;
  563. case RumorState::TYPE_RAND:
  564. text.replaceTextID(TextIdentifier("core", "randtvrn", rumor.first).get());
  565. break;
  566. }
  567. return text.toString();
  568. }
  569. PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  570. {
  571. return gameState()->getPlayerRelations(color1, color2);
  572. }
  573. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  574. {
  575. return !obj || hasAccess(obj->tempOwner);
  576. }
  577. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  578. {
  579. int ret = 0;
  580. const PlayerState *p = gameState()->getPlayerState(player);
  581. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  582. if(includeGarrisoned)
  583. return static_cast<int>(p->getHeroes().size());
  584. else
  585. for(const auto & elem : p->getHeroes())
  586. if(!elem->isGarrisoned())
  587. ret++;
  588. return ret;
  589. }
  590. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  591. {
  592. if(canGetFullInfo(obj))
  593. return true;
  594. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  595. const ObjectInstanceID visitorID = t->visitableObjects.back(); //visitong hero if present or the object itself at last
  596. const CGObjectInstance * visitor = getObj(visitorID);
  597. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  598. }
  599. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  600. {
  601. return gameState()->actingPlayers.count(player);
  602. }
  603. int CPlayerSpecificInfoCallback::howManyTowns() const
  604. {
  605. //std::shared_lock<std::shared_mutex> lock(*gameState()->mx);
  606. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  607. return CGameInfoCallback::howManyTowns(*getPlayerID());
  608. }
  609. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  610. {
  611. //std::shared_lock<std::shared_mutex> lock(*gameState()->mx);
  612. auto ret = std::vector < const CGTownInstance *>();
  613. for(const auto & i : gameState()->players)
  614. {
  615. for(const auto & town : i.second.getTowns())
  616. {
  617. if(i.first == getPlayerID() || (!onlyOur && isVisible(town, getPlayerID())))
  618. {
  619. ret.push_back(town);
  620. }
  621. }
  622. } // for ( std::map<int, PlayerState>::iterator i=gameState()->players.begin() ; i!=gameState()->players.end();i++)
  623. return ret;
  624. }
  625. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo() const
  626. {
  627. const auto * playerState = gameState()->getPlayerState(*getPlayerID());
  628. return playerState->getHeroes();
  629. }
  630. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  631. {
  632. if (hero->isGarrisoned() && !includeGarrisoned)
  633. return -1;
  634. size_t index = 0;
  635. const auto & heroes = gameState()->players.at(*getPlayerID()).getHeroes();
  636. for (auto & possibleHero : heroes)
  637. {
  638. if (includeGarrisoned || !(possibleHero)->isGarrisoned())
  639. index++;
  640. if (possibleHero == hero)
  641. return static_cast<int>(index);
  642. }
  643. return -1;
  644. }
  645. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  646. {
  647. if (!getPlayerID() || gameState()->getMap().obeliskCount == 0)
  648. {
  649. *outKnownRatio = 0.0;
  650. }
  651. else
  652. {
  653. TeamID t = gameState()->getPlayerTeam(*getPlayerID())->id;
  654. double visited = 0.0;
  655. if(gameState()->getMap().obelisksVisited.count(t))
  656. visited = static_cast<double>(gameState()->getMap().obelisksVisited[t]);
  657. *outKnownRatio = visited / gameState()->getMap().obeliskCount;
  658. }
  659. return gameState()->getMap().grailPos;
  660. }
  661. std::vector < const CGObjectInstance * > CPlayerSpecificInfoCallback::getMyObjects() const
  662. {
  663. return gameState()->getPlayerState(*getPlayerID())->getOwnedObjects();
  664. }
  665. std::vector <QuestInfo> CPlayerSpecificInfoCallback::getMyQuests() const
  666. {
  667. return gameState()->getPlayerState(*getPlayerID())->quests;
  668. }
  669. int CPlayerSpecificInfoCallback::howManyHeroes(bool includeGarrisoned) const
  670. {
  671. //std::shared_lock<std::shared_mutex> lock(*gameState()->mx);
  672. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  673. return getHeroCount(*getPlayerID(), includeGarrisoned);
  674. }
  675. const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId, bool includeGarrisoned) const
  676. {
  677. ASSERT_IF_CALLED_WITH_PLAYER
  678. const PlayerState *p = getPlayerState(*getPlayerID());
  679. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  680. if (!includeGarrisoned)
  681. {
  682. for(ui32 i = 0; i < p->getHeroes().size() && static_cast<int>(i) <= serialId; i++)
  683. if(p->getHeroes()[i]->isGarrisoned())
  684. serialId++;
  685. }
  686. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->getHeroes().size(), "No player info", nullptr);
  687. return p->getHeroes()[serialId];
  688. }
  689. const CGTownInstance* CPlayerSpecificInfoCallback::getTownBySerial(int serialId) const
  690. {
  691. ASSERT_IF_CALLED_WITH_PLAYER
  692. const PlayerState *p = getPlayerState(*getPlayerID());
  693. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  694. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->getTowns().size(), "No player info", nullptr);
  695. return p->getTowns()[serialId];
  696. }
  697. int CPlayerSpecificInfoCallback::getResourceAmount(GameResID type) const
  698. {
  699. //std::shared_lock<std::shared_mutex> lock(*gameState()->mx);
  700. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  701. return getResource(*getPlayerID(), type);
  702. }
  703. TResources CPlayerSpecificInfoCallback::getResourceAmount() const
  704. {
  705. //std::shared_lock<std::shared_mutex> lock(*gameState()->mx);
  706. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", TResources());
  707. return gameState()->players.at(*getPlayerID()).resources;
  708. }
  709. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  710. {
  711. //rewritten by hand, AI calls this function a lot
  712. auto team = gameState()->teams.find(teamID);
  713. if (team != gameState()->teams.end())
  714. {
  715. const TeamState *ret = &team->second;
  716. if(!getPlayerID().has_value()) //neutral (or invalid) player
  717. return ret;
  718. else
  719. {
  720. if (vstd::contains(ret->players, *getPlayerID())) //specific player
  721. return ret;
  722. else
  723. {
  724. logGlobal->error("Illegal attempt to access team data!");
  725. return nullptr;
  726. }
  727. }
  728. }
  729. else
  730. {
  731. logGlobal->error("Cannot find info for team %d", teamID);
  732. return nullptr;
  733. }
  734. }
  735. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  736. {
  737. auto player = gameState()->players.find(color);
  738. if (player != gameState()->players.end())
  739. {
  740. return getTeam (player->second.team);
  741. }
  742. else
  743. {
  744. return nullptr;
  745. }
  746. }
  747. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  748. {
  749. return gameState()->getMap().isInTheMap(pos);
  750. }
  751. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  752. {
  753. gameState()->getTilesInRange(tiles, pos, radious, ETileVisibility::REVEALED, *getPlayerID(), distanceFormula);
  754. }
  755. void CGameInfoCallback::calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const
  756. {
  757. gameState()->calculatePaths(config);
  758. }
  759. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  760. {
  761. return gameState()->getMap().getArtifactInstance(aid);
  762. }
  763. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  764. {
  765. return gameState()->getMap().getObject((oid));
  766. }
  767. const CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  768. {
  769. return gameState()->getArtSet(loc);
  770. }
  771. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  772. {
  773. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  774. {
  775. const auto * obj = getObj(id, false);
  776. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->visitablePos(), player));
  777. });
  778. return ids;
  779. }
  780. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntrances(TeleportChannelID id, PlayerColor player) const
  781. {
  782. return getVisibleTeleportObjects(gameState()->getMap().teleportChannels.at(id)->entrances, player);
  783. }
  784. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  785. {
  786. return getVisibleTeleportObjects(gameState()->getMap().teleportChannels.at(id)->exits, player);
  787. }
  788. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  789. {
  790. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntrances(id, player);
  791. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  792. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  793. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  794. {
  795. return ETeleportChannelType::IMPASSABLE;
  796. }
  797. auto intersection = vstd::intersection(entrances, exits);
  798. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  799. return ETeleportChannelType::BIDIRECTIONAL;
  800. else if(intersection.empty())
  801. return ETeleportChannelType::UNIDIRECTIONAL;
  802. else
  803. return ETeleportChannelType::MIXED;
  804. }
  805. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  806. {
  807. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  808. }
  809. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  810. {
  811. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  812. }
  813. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  814. {
  815. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  816. }
  817. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  818. {
  819. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  820. }
  821. VCMI_LIB_NAMESPACE_END