2
0

CGameInfoCallback.cpp 29 KB

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