CGameInfoCallback.cpp 29 KB

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