CGameInfoCallback.cpp 30 KB

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