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