CGameInfoCallback.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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 "entities/building/CBuilding.h"
  13. #include "gameState/CGameState.h"
  14. #include "gameState/InfoAboutArmy.h"
  15. #include "gameState/SThievesGuildInfo.h"
  16. #include "gameState/TavernHeroesPool.h"
  17. #include "gameState/QuestInfo.h"
  18. #include "mapObjects/CGHeroInstance.h"
  19. #include "mapObjects/CGTownInstance.h"
  20. #include "mapObjects/MiscObjects.h"
  21. #include "networkPacks/ArtifactLocation.h"
  22. #include "texts/CGeneralTextHandler.h"
  23. #include "StartInfo.h" // for StartInfo
  24. #include "battle/BattleInfo.h" // for BattleInfo
  25. #include "GameSettings.h"
  26. #include "TerrainHandler.h"
  27. #include "spells/CSpellHandler.h"
  28. #include "mapping/CMap.h"
  29. #include "CPlayerState.h"
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. //TODO make clean
  32. #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)
  33. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return;}} while(0)
  34. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  35. PlayerColor CGameInfoCallback::getOwner(ObjectInstanceID heroID) const
  36. {
  37. const CGObjectInstance *obj = getObj(heroID);
  38. ERROR_RET_VAL_IF(!obj, "No such object!", PlayerColor::CANNOT_DETERMINE);
  39. return obj->tempOwner;
  40. }
  41. int CGameInfoCallback::getResource(PlayerColor Player, GameResID which) const
  42. {
  43. const PlayerState *p = getPlayerState(Player);
  44. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  45. ERROR_RET_VAL_IF(p->resources.size() <= which.getNum() || which.getNum() < 0, "No such resource!", -1);
  46. return p->resources[which];
  47. }
  48. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  49. {
  50. return &gs->scenarioOps->getIthPlayersSettings(color);
  51. }
  52. bool CGameInfoCallback::isAllowed(SpellID id) const
  53. {
  54. return gs->map->allowedSpells.count(id) != 0;
  55. }
  56. bool CGameInfoCallback::isAllowed(ArtifactID id) const
  57. {
  58. return gs->map->allowedArtifact.count(id) != 0;
  59. }
  60. bool CGameInfoCallback::isAllowed(SecondarySkill id) const
  61. {
  62. return gs->map->allowedAbilities.count(id) != 0;
  63. }
  64. std::optional<PlayerColor> CGameInfoCallback::getPlayerID() const
  65. {
  66. return std::nullopt;
  67. }
  68. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  69. {
  70. return getPlayerState(color, false);
  71. }
  72. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  73. {
  74. //function written from scratch since it's accessed A LOT by AI
  75. if(!color.isValidPlayer())
  76. {
  77. return nullptr;
  78. }
  79. auto player = gs->players.find(color);
  80. if (player != gs->players.end())
  81. {
  82. if (hasAccess(color))
  83. return &player->second;
  84. else
  85. {
  86. if (verbose)
  87. logGlobal->error("Cannot access player %d info!", color);
  88. return nullptr;
  89. }
  90. }
  91. else
  92. {
  93. if (verbose)
  94. logGlobal->error("Cannot find player %d info!", color);
  95. return nullptr;
  96. }
  97. }
  98. TurnTimerInfo CGameInfoCallback::getPlayerTurnTime(PlayerColor color) const
  99. {
  100. if(!color.isValidPlayer())
  101. {
  102. return TurnTimerInfo{};
  103. }
  104. auto player = gs->players.find(color);
  105. if(player != gs->players.end())
  106. {
  107. return player->second.turnTimer;
  108. }
  109. return TurnTimerInfo{};
  110. }
  111. /************************************************************************/
  112. /* */
  113. /************************************************************************/
  114. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  115. {
  116. si32 oid = objid.num;
  117. if(oid < 0 || oid >= gs->map->objects.size())
  118. {
  119. if(verbose)
  120. logGlobal->error("Cannot get object with id %d", oid);
  121. return nullptr;
  122. }
  123. const CGObjectInstance *ret = gs->map->objects[oid];
  124. if(!ret)
  125. {
  126. if(verbose)
  127. logGlobal->error("Cannot get object with id %d. Object was removed", oid);
  128. return nullptr;
  129. }
  130. if(!isVisible(ret, getPlayerID()) && ret->tempOwner != getPlayerID())
  131. {
  132. if(verbose)
  133. logGlobal->error("Cannot get object with id %d. Object is not visible.", oid);
  134. return nullptr;
  135. }
  136. return ret;
  137. }
  138. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  139. {
  140. const CGObjectInstance *obj = getObj(objid, false);
  141. if(obj)
  142. return dynamic_cast<const CGHeroInstance*>(obj);
  143. else
  144. return nullptr;
  145. }
  146. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  147. {
  148. const CGObjectInstance *obj = getObj(objid, false);
  149. if(obj)
  150. return dynamic_cast<const CGTownInstance*>(obj);
  151. else
  152. return nullptr;
  153. }
  154. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  155. {
  156. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  157. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  158. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  159. gs->fillUpgradeInfo(obj, stackPos, out);
  160. //return gs->fillUpgradeInfo(obj->getStack(stackPos));
  161. }
  162. const StartInfo * CGameInfoCallback::getStartInfo(bool beforeRandomization) const
  163. {
  164. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  165. if(beforeRandomization)
  166. return gs->initialOpts;
  167. else
  168. return gs->scenarioOps;
  169. }
  170. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  171. {
  172. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  173. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  174. //if there is a battle
  175. auto casterBattle = gs->getBattle(caster->getOwner());
  176. if(casterBattle)
  177. return casterBattle->battleGetSpellCost(sp, caster);
  178. //if there is no battle
  179. return caster->getSpellCost(sp);
  180. }
  181. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  182. {
  183. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  184. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  185. if(hero) //we see hero's spellbook
  186. return sp->calculateDamage(hero);
  187. else
  188. return 0; //mage guild
  189. }
  190. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  191. {
  192. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  193. ERROR_RET_IF(!obj, "No guild object!");
  194. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  195. //TODO: advmap object -> check if they're visited by our hero
  196. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  197. {
  198. int taverns = 0;
  199. for(auto town : gs->players[*getPlayerID()].towns)
  200. {
  201. if(town->hasBuilt(BuildingID::TAVERN))
  202. taverns++;
  203. if(town->hasBuilt(BuildingSubID::THIEVES_GUILD))
  204. taverns += 2;
  205. }
  206. gs->obtainPlayersStats(thi, taverns);
  207. }
  208. else if(obj->ID == Obj::DEN_OF_THIEVES)
  209. {
  210. gs->obtainPlayersStats(thi, 20);
  211. }
  212. }
  213. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  214. {
  215. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  216. return static_cast<int>(gs->players[Player].towns.size());
  217. }
  218. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  219. {
  220. ERROR_RET_VAL_IF(!isVisible(town, getPlayerID()), "Town is not visible!", false); //it's not a town or it's not visible for layer
  221. bool detailed = hasAccess(town->tempOwner);
  222. if(town->ID == Obj::TOWN)
  223. {
  224. if(!detailed && nullptr != selectedObject)
  225. {
  226. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  227. if(nullptr != selectedHero)
  228. detailed = selectedHero->hasVisions(town, BonusCustomSubtype::visionsTowns);
  229. }
  230. dest.initFromTown(dynamic_cast<const CGTownInstance *>(town), detailed);
  231. }
  232. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  233. dest.initFromArmy(dynamic_cast<const CArmedInstance *>(town), detailed);
  234. else
  235. return false;
  236. return true;
  237. }
  238. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const //FIXME: redundant?
  239. {
  240. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  241. return gs->guardingCreaturePosition(pos);
  242. }
  243. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  244. {
  245. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  246. std::vector<const CGObjectInstance*> ret;
  247. for(auto * cr : gs->guardingCreatures(pos))
  248. {
  249. ret.push_back(cr);
  250. }
  251. return ret;
  252. }
  253. bool CGameInfoCallback::isTileGuardedUnchecked(int3 tile) const
  254. {
  255. return !gs->guardingCreatures(tile).empty();
  256. }
  257. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  258. {
  259. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  260. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  261. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  262. if(hasAccess(h->tempOwner))
  263. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  264. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  265. {
  266. auto ourBattle = gs->getBattle(*getPlayerID());
  267. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  268. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  269. else
  270. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  271. }
  272. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  273. {
  274. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  275. if(nullptr != selectedHero)
  276. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  277. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  278. }
  279. dest.initFromHero(h, infoLevel);
  280. //DISGUISED bonus implementation
  281. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  282. {
  283. //todo: bonus cashing
  284. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  285. auto doBasicDisguise = [](InfoAboutHero & info)
  286. {
  287. int maxAIValue = 0;
  288. const CCreature * mostStrong = nullptr;
  289. for(auto & elem : info.army)
  290. {
  291. if(static_cast<int>(elem.second.type->getAIValue()) > maxAIValue)
  292. {
  293. maxAIValue = elem.second.type->getAIValue();
  294. mostStrong = elem.second.type;
  295. }
  296. }
  297. if(nullptr == mostStrong)//just in case
  298. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  299. else
  300. for(auto & elem : info.army)
  301. {
  302. elem.second.type = mostStrong;
  303. }
  304. };
  305. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  306. {
  307. doBasicDisguise(info);
  308. for(auto & elem : info.army)
  309. elem.second.count = 0;
  310. };
  311. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  312. {
  313. for(auto & elem : info.army)
  314. elem.second.count = 0;
  315. const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle;
  316. int maxAIValue = 0;
  317. const CCreature * mostStrong = nullptr;
  318. for(const auto & creature : VLC->creh->objects)
  319. {
  320. if(creature->getFaction() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  321. {
  322. maxAIValue = creature->getAIValue();
  323. mostStrong = creature.get();
  324. }
  325. }
  326. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  327. for(auto & elem : info.army)
  328. elem.second.type = mostStrong;
  329. };
  330. switch (disguiseLevel)
  331. {
  332. case 0:
  333. //no bonus at all - do nothing
  334. break;
  335. case 1:
  336. doBasicDisguise(dest);
  337. break;
  338. case 2:
  339. doAdvancedDisguise(dest);
  340. break;
  341. case 3:
  342. doExpertDisguise(dest);
  343. break;
  344. default:
  345. //invalid value
  346. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  347. break;
  348. }
  349. }
  350. return true;
  351. }
  352. int CGameInfoCallback::getDate(Date mode) const
  353. {
  354. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  355. return gs->getDate(mode);
  356. }
  357. bool CGameInfoCallback::isVisible(int3 pos, const std::optional<PlayerColor> & Player) const
  358. {
  359. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  360. return gs->isVisible(pos, Player);
  361. }
  362. bool CGameInfoCallback::isVisible(int3 pos) const
  363. {
  364. return isVisible(pos, getPlayerID());
  365. }
  366. bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const
  367. {
  368. return gs->isVisible(obj, Player);
  369. }
  370. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  371. {
  372. return isVisible(obj, getPlayerID());
  373. }
  374. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  375. // {
  376. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  377. // if()
  378. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  379. // if(!armi)
  380. // return nullptr;
  381. // else
  382. // return armi;
  383. // }
  384. std::vector <const CGObjectInstance *> CGameInfoCallback::getBlockingObjs( int3 pos ) const
  385. {
  386. std::vector<const CGObjectInstance *> ret;
  387. const TerrainTile *t = getTile(pos);
  388. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  389. for(const CGObjectInstance * obj : t->blockingObjects)
  390. ret.push_back(obj);
  391. return ret;
  392. }
  393. std::vector <const CGObjectInstance *> CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  394. {
  395. std::vector<const CGObjectInstance *> ret;
  396. const TerrainTile *t = getTile(pos, verbose);
  397. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  398. for(const CGObjectInstance * obj : t->visitableObjects)
  399. {
  400. if(getPlayerID() || obj->ID != Obj::EVENT) //hide events from players
  401. ret.push_back(obj);
  402. }
  403. return ret;
  404. }
  405. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  406. {
  407. return vstd::backOrNull(getVisitableObjs(pos));
  408. }
  409. std::vector <const CGObjectInstance *> CGameInfoCallback::getFlaggableObjects(int3 pos) const
  410. {
  411. std::vector<const CGObjectInstance *> ret;
  412. const TerrainTile *t = getTile(pos);
  413. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  414. for(const CGObjectInstance *obj : t->blockingObjects)
  415. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  416. ret.push_back(obj);
  417. return ret;
  418. }
  419. int3 CGameInfoCallback::getMapSize() const
  420. {
  421. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  422. }
  423. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  424. {
  425. ASSERT_IF_CALLED_WITH_PLAYER
  426. std::vector<const CGHeroInstance *> ret;
  427. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  428. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  429. const CGTownInstance * town = getTown(townOrTavern->id);
  430. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  431. return gs->heroesPool->getHeroesFor(*getPlayerID());
  432. return ret;
  433. }
  434. const TerrainTile * CGameInfoCallback::getTile(int3 tile, bool verbose) const
  435. {
  436. if(isVisible(tile))
  437. return &gs->map->getTile(tile);
  438. if(verbose)
  439. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  440. return nullptr;
  441. }
  442. const TerrainTile * CGameInfoCallback::getTileUnchecked(int3 tile) const
  443. {
  444. if (isInTheMap(tile))
  445. return &gs->map->getTile(tile);
  446. return nullptr;
  447. }
  448. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  449. {
  450. if(!isVisible(tile))
  451. return EDiggingStatus::UNKNOWN;
  452. for(const auto & object : gs->map->objects)
  453. {
  454. if(object && object->ID == Obj::HOLE && object->pos == tile)
  455. return EDiggingStatus::TILE_OCCUPIED;
  456. }
  457. return getTile(tile)->getDiggingStatus();
  458. }
  459. //TODO: typedef?
  460. std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
  461. {
  462. assert(getPlayerID().has_value());
  463. const auto * team = getPlayerTeam(getPlayerID().value());
  464. size_t width = gs->map->width;
  465. size_t height = gs->map->height;
  466. size_t levels = gs->map->levels();
  467. auto * ptr = new boost::multi_array<TerrainTile *, 3>(boost::extents[levels][width][height]);
  468. int3 tile;
  469. for(tile.z = 0; tile.z < levels; tile.z++)
  470. for(tile.x = 0; tile.x < width; tile.x++)
  471. for(tile.y = 0; tile.y < height; tile.y++)
  472. {
  473. if (team->fogOfWarMap[tile.z][tile.x][tile.y])
  474. (*ptr)[tile.z][tile.x][tile.y] = &gs->map->getTile(tile);
  475. else
  476. (*ptr)[tile.z][tile.x][tile.y] = nullptr;
  477. }
  478. return std::shared_ptr<const boost::multi_array<TerrainTile*, 3>>(ptr);
  479. }
  480. EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  481. {
  482. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  483. if(!t->town->buildings.count(ID))
  484. return EBuildingState::BUILDING_ERROR;
  485. const CBuilding * building = t->town->buildings.at(ID);
  486. if(t->hasBuilt(ID)) //already built
  487. return EBuildingState::ALREADY_PRESENT;
  488. //can we build it?
  489. if(vstd::contains(t->forbiddenBuildings, ID))
  490. return EBuildingState::FORBIDDEN; //forbidden
  491. auto possiblyNotBuiltTest = [&](const BuildingID & id) -> bool
  492. {
  493. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  494. };
  495. std::function<bool(BuildingID id)> allowedTest = [&](const BuildingID & id) -> bool
  496. {
  497. return !vstd::contains(t->forbiddenBuildings, id);
  498. };
  499. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  500. return EBuildingState::FORBIDDEN;
  501. if(ID == BuildingID::CAPITOL)
  502. {
  503. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  504. if(ps)
  505. {
  506. for(const CGTownInstance *town : ps->towns)
  507. {
  508. if(town->hasBuilt(BuildingID::CAPITOL))
  509. {
  510. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  511. }
  512. }
  513. }
  514. }
  515. else if(ID == BuildingID::SHIPYARD)
  516. {
  517. const TerrainTile *tile = getTile(t->bestLocation(), false);
  518. if(!tile || !tile->terType->isWater())
  519. return EBuildingState::NO_WATER; //lack of water
  520. }
  521. auto buildTest = [&](const BuildingID & id) -> bool
  522. {
  523. return t->hasBuilt(id);
  524. };
  525. if (!t->genBuildingRequirements(ID).test(buildTest))
  526. return EBuildingState::PREREQUIRES;
  527. if(t->built >= VLC->settings()->getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  528. return EBuildingState::CANT_BUILD_TODAY; //building limit
  529. //checking resources
  530. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  531. return EBuildingState::NO_RESOURCES; //lack of res
  532. return EBuildingState::ALLOWED;
  533. }
  534. const CMapHeader * CGameInfoCallback::getMapHeader() const
  535. {
  536. return gs->map;
  537. }
  538. bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
  539. {
  540. return !getPlayerID() || getPlayerID()->isSpectator() || gs->getPlayerRelations(*playerId, *getPlayerID()) != PlayerRelations::ENEMIES;
  541. }
  542. EPlayerStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  543. {
  544. const PlayerState *ps = gs->getPlayerState(player, verbose);
  545. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  546. return ps->status;
  547. }
  548. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  549. {
  550. MetaString text;
  551. text.appendLocalString(EMetaText::GENERAL_TXT, 216);
  552. std::string extraText;
  553. if(gs->currentRumor.type == RumorState::TYPE_NONE)
  554. return text.toString();
  555. auto rumor = gs->currentRumor.last[gs->currentRumor.type];
  556. switch(gs->currentRumor.type)
  557. {
  558. case RumorState::TYPE_SPECIAL:
  559. text.replaceLocalString(EMetaText::GENERAL_TXT, rumor.first);
  560. if(rumor.first == RumorState::RUMOR_GRAIL)
  561. text.replaceTextID(TextIdentifier("core", "arraytxt", 158 + rumor.second).get());
  562. else
  563. text.replaceTextID(TextIdentifier("core", "plcolors", rumor.second).get());
  564. break;
  565. case RumorState::TYPE_MAP:
  566. text.replaceRawString(gs->map->rumors[rumor.first].text.toString());
  567. break;
  568. case RumorState::TYPE_RAND:
  569. text.replaceTextID(TextIdentifier("core", "randtvrn", rumor.first).get());
  570. break;
  571. }
  572. return text.toString();
  573. }
  574. PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  575. {
  576. return gs->getPlayerRelations(color1, color2);
  577. }
  578. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  579. {
  580. return !obj || hasAccess(obj->tempOwner);
  581. }
  582. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  583. {
  584. int ret = 0;
  585. const PlayerState *p = gs->getPlayerState(player);
  586. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  587. if(includeGarrisoned)
  588. return static_cast<int>(p->heroes.size());
  589. else
  590. for(const auto & elem : p->heroes)
  591. if(!elem->inTownGarrison)
  592. ret++;
  593. return ret;
  594. }
  595. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  596. {
  597. if(canGetFullInfo(obj))
  598. return true;
  599. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  600. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the object itself at last
  601. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  602. }
  603. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  604. {
  605. return gs->actingPlayers.count(player);
  606. }
  607. CGameInfoCallback::CGameInfoCallback():
  608. gs(nullptr)
  609. {
  610. }
  611. CGameInfoCallback::CGameInfoCallback(CGameState * GS):
  612. gs(GS)
  613. {
  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. auto 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 & possibleHero : heroes)
  659. {
  660. if (includeGarrisoned || !(possibleHero)->inTownGarrison)
  661. index++;
  662. if (possibleHero == hero)
  663. return static_cast<int>(index);
  664. }
  665. return -1;
  666. }
  667. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  668. {
  669. if (!getPlayerID() || gs->map->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(gs->map->obelisksVisited.count(t))
  678. visited = static_cast<double>(gs->map->obelisksVisited[t]);
  679. *outKnownRatio = visited / gs->map->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. const CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  823. {
  824. return gs->getArtSet(loc);
  825. }
  826. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  827. {
  828. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  829. {
  830. const auto * obj = getObj(id, false);
  831. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  832. });
  833. return ids;
  834. }
  835. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntrances(TeleportChannelID id, PlayerColor player) const
  836. {
  837. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  838. }
  839. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  840. {
  841. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  842. }
  843. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  844. {
  845. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntrances(id, player);
  846. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  847. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  848. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  849. {
  850. return ETeleportChannelType::IMPASSABLE;
  851. }
  852. auto intersection = vstd::intersection(entrances, exits);
  853. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  854. return ETeleportChannelType::BIDIRECTIONAL;
  855. else if(intersection.empty())
  856. return ETeleportChannelType::UNIDIRECTIONAL;
  857. else
  858. return ETeleportChannelType::MIXED;
  859. }
  860. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  861. {
  862. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  863. }
  864. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  865. {
  866. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  867. }
  868. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  869. {
  870. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  871. }
  872. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  873. {
  874. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  875. }
  876. VCMI_LIB_NAMESPACE_END