CGameInfoCallback.cpp 29 KB

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