CGameInfoCallback.cpp 29 KB

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