CGameInfoCallback.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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 "gameState/QuestInfo.h"
  17. #include "mapObjects/CGHeroInstance.h"
  18. #include "mapObjects/CGTownInstance.h"
  19. #include "mapObjects/MiscObjects.h"
  20. #include "networkPacks/ArtifactLocation.h"
  21. #include "CGeneralTextHandler.h"
  22. #include "StartInfo.h" // for StartInfo
  23. #include "battle/BattleInfo.h" // for BattleInfo
  24. #include "GameSettings.h"
  25. #include "TerrainHandler.h"
  26. #include "spells/CSpellHandler.h"
  27. #include "mapping/CMap.h"
  28. #include "CPlayerState.h"
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. //TODO make clean
  31. #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)
  32. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return;}} while(0)
  33. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  34. PlayerColor CGameInfoCallback::getOwner(ObjectInstanceID heroID) const
  35. {
  36. const CGObjectInstance *obj = getObj(heroID);
  37. ERROR_RET_VAL_IF(!obj, "No such object!", PlayerColor::CANNOT_DETERMINE);
  38. return obj->tempOwner;
  39. }
  40. int CGameInfoCallback::getResource(PlayerColor Player, GameResID which) const
  41. {
  42. const PlayerState *p = getPlayerState(Player);
  43. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  44. ERROR_RET_VAL_IF(p->resources.size() <= which.getNum() || which.getNum() < 0, "No such resource!", -1);
  45. return p->resources[which];
  46. }
  47. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  48. {
  49. return &gs->scenarioOps->getIthPlayersSettings(color);
  50. }
  51. bool CGameInfoCallback::isAllowed(SpellID id) const
  52. {
  53. return gs->map->allowedSpells.count(id) != 0;
  54. }
  55. bool CGameInfoCallback::isAllowed(ArtifactID id) const
  56. {
  57. return gs->map->allowedArtifact.count(id) != 0;
  58. }
  59. bool CGameInfoCallback::isAllowed(SecondarySkill id) const
  60. {
  61. return gs->map->allowedAbilities.count(id) != 0;
  62. }
  63. std::optional<PlayerColor> CGameInfoCallback::getPlayerID() const
  64. {
  65. return std::nullopt;
  66. }
  67. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  68. {
  69. return getPlayerState(color, false);
  70. }
  71. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  72. {
  73. //funtion written from scratch since it's accessed A LOT by AI
  74. if(!color.isValidPlayer())
  75. {
  76. return nullptr;
  77. }
  78. auto player = gs->players.find(color);
  79. if (player != gs->players.end())
  80. {
  81. if (hasAccess(color))
  82. return &player->second;
  83. else
  84. {
  85. if (verbose)
  86. logGlobal->error("Cannot access player %d info!", color);
  87. return nullptr;
  88. }
  89. }
  90. else
  91. {
  92. if (verbose)
  93. logGlobal->error("Cannot find player %d info!", color);
  94. return nullptr;
  95. }
  96. }
  97. TurnTimerInfo CGameInfoCallback::getPlayerTurnTime(PlayerColor color) const
  98. {
  99. if(!color.isValidPlayer())
  100. {
  101. return TurnTimerInfo{};
  102. }
  103. auto player = gs->players.find(color);
  104. if(player != gs->players.end())
  105. {
  106. return player->second.turnTimer;
  107. }
  108. return TurnTimerInfo{};
  109. }
  110. const CGObjectInstance * CGameInfoCallback::getObjByQuestIdentifier(ObjectInstanceID identifier) const
  111. {
  112. if(gs->map->questIdentifierToId.empty())
  113. {
  114. //assume that it is VCMI map and quest identifier equals instance identifier
  115. return getObj(identifier, true);
  116. }
  117. else
  118. {
  119. ERROR_RET_VAL_IF(!vstd::contains(gs->map->questIdentifierToId, identifier.getNum()), "There is no object with such quest identifier!", nullptr);
  120. return getObj(gs->map->questIdentifierToId[identifier.getNum()]);
  121. }
  122. }
  123. /************************************************************************/
  124. /* */
  125. /************************************************************************/
  126. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  127. {
  128. si32 oid = objid.num;
  129. if(oid < 0 || oid >= gs->map->objects.size())
  130. {
  131. if(verbose)
  132. logGlobal->error("Cannot get object with id %d", oid);
  133. return nullptr;
  134. }
  135. const CGObjectInstance *ret = gs->map->objects[oid];
  136. if(!ret)
  137. {
  138. if(verbose)
  139. logGlobal->error("Cannot get object with id %d. Object was removed", oid);
  140. return nullptr;
  141. }
  142. if(!isVisible(ret, getPlayerID()) && ret->tempOwner != getPlayerID())
  143. {
  144. if(verbose)
  145. logGlobal->error("Cannot get object with id %d. Object is not visible.", oid);
  146. return nullptr;
  147. }
  148. return ret;
  149. }
  150. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  151. {
  152. const CGObjectInstance *obj = getObj(objid, false);
  153. if(obj)
  154. return dynamic_cast<const CGHeroInstance*>(obj);
  155. else
  156. return nullptr;
  157. }
  158. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  159. {
  160. const CGObjectInstance *obj = getObj(objid, false);
  161. if(obj)
  162. return dynamic_cast<const CGTownInstance*>(obj);
  163. else
  164. return nullptr;
  165. }
  166. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  167. {
  168. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  169. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  170. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  171. gs->fillUpgradeInfo(obj, stackPos, out);
  172. //return gs->fillUpgradeInfo(obj->getStack(stackPos));
  173. }
  174. const StartInfo * CGameInfoCallback::getStartInfo(bool beforeRandomization) const
  175. {
  176. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  177. if(beforeRandomization)
  178. return gs->initialOpts;
  179. else
  180. return gs->scenarioOps;
  181. }
  182. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  183. {
  184. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  185. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  186. //if there is a battle
  187. auto casterBattle = gs->getBattle(caster->getOwner());
  188. if(casterBattle)
  189. return casterBattle->battleGetSpellCost(sp, caster);
  190. //if there is no battle
  191. return caster->getSpellCost(sp);
  192. }
  193. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  194. {
  195. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  196. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  197. if(hero) //we see hero's spellbook
  198. return sp->calculateDamage(hero);
  199. else
  200. return 0; //mage guild
  201. }
  202. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  203. {
  204. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  205. ERROR_RET_IF(!obj, "No guild object!");
  206. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  207. //TODO: advmap object -> check if they're visited by our hero
  208. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  209. {
  210. int taverns = 0;
  211. for(auto town : gs->players[*getPlayerID()].towns)
  212. {
  213. if(town->hasBuilt(BuildingID::TAVERN))
  214. taverns++;
  215. }
  216. gs->obtainPlayersStats(thi, taverns);
  217. }
  218. else if(obj->ID == Obj::DEN_OF_THIEVES)
  219. {
  220. gs->obtainPlayersStats(thi, 20);
  221. }
  222. }
  223. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  224. {
  225. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  226. return static_cast<int>(gs->players[Player].towns.size());
  227. }
  228. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  229. {
  230. ERROR_RET_VAL_IF(!isVisible(town, getPlayerID()), "Town is not visible!", false); //it's not a town or it's not visible for layer
  231. bool detailed = hasAccess(town->tempOwner);
  232. if(town->ID == Obj::TOWN)
  233. {
  234. if(!detailed && nullptr != selectedObject)
  235. {
  236. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  237. if(nullptr != selectedHero)
  238. detailed = selectedHero->hasVisions(town, BonusCustomSubtype::visionsTowns);
  239. }
  240. dest.initFromTown(dynamic_cast<const CGTownInstance *>(town), detailed);
  241. }
  242. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  243. dest.initFromArmy(dynamic_cast<const CArmedInstance *>(town), detailed);
  244. else
  245. return false;
  246. return true;
  247. }
  248. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const //FIXME: redundant?
  249. {
  250. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  251. return gs->guardingCreaturePosition(pos);
  252. }
  253. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  254. {
  255. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  256. std::vector<const CGObjectInstance*> ret;
  257. for(auto * cr : gs->guardingCreatures(pos))
  258. {
  259. ret.push_back(cr);
  260. }
  261. return ret;
  262. }
  263. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  264. {
  265. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  266. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  267. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  268. if(hasAccess(h->tempOwner))
  269. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  270. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  271. {
  272. auto ourBattle = gs->getBattle(*getPlayerID());
  273. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  274. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  275. else
  276. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  277. }
  278. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  279. {
  280. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  281. if(nullptr != selectedHero)
  282. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  283. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  284. }
  285. dest.initFromHero(h, infoLevel);
  286. //DISGUISED bonus implementation
  287. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  288. {
  289. //todo: bonus cashing
  290. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  291. auto doBasicDisguise = [](InfoAboutHero & info)
  292. {
  293. int maxAIValue = 0;
  294. const CCreature * mostStrong = nullptr;
  295. for(auto & elem : info.army)
  296. {
  297. if(static_cast<int>(elem.second.type->getAIValue()) > maxAIValue)
  298. {
  299. maxAIValue = elem.second.type->getAIValue();
  300. mostStrong = elem.second.type;
  301. }
  302. }
  303. if(nullptr == mostStrong)//just in case
  304. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  305. else
  306. for(auto & elem : info.army)
  307. {
  308. elem.second.type = mostStrong;
  309. }
  310. };
  311. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  312. {
  313. doBasicDisguise(info);
  314. for(auto & elem : info.army)
  315. elem.second.count = 0;
  316. };
  317. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  318. {
  319. for(auto & elem : info.army)
  320. elem.second.count = 0;
  321. const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle;
  322. int maxAIValue = 0;
  323. const CCreature * mostStrong = nullptr;
  324. for(auto creature : VLC->creh->objects)
  325. {
  326. if(creature->getFaction() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  327. {
  328. maxAIValue = creature->getAIValue();
  329. mostStrong = creature.get();
  330. }
  331. }
  332. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  333. for(auto & elem : info.army)
  334. elem.second.type = mostStrong;
  335. };
  336. switch (disguiseLevel)
  337. {
  338. case 0:
  339. //no bonus at all - do nothing
  340. break;
  341. case 1:
  342. doBasicDisguise(dest);
  343. break;
  344. case 2:
  345. doAdvancedDisguise(dest);
  346. break;
  347. case 3:
  348. doExpertDisguise(dest);
  349. break;
  350. default:
  351. //invalid value
  352. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  353. break;
  354. }
  355. }
  356. return true;
  357. }
  358. int CGameInfoCallback::getDate(Date mode) const
  359. {
  360. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  361. return gs->getDate(mode);
  362. }
  363. bool CGameInfoCallback::isVisible(int3 pos, const std::optional<PlayerColor> & Player) const
  364. {
  365. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  366. return gs->isVisible(pos, Player);
  367. }
  368. bool CGameInfoCallback::isVisible(int3 pos) const
  369. {
  370. return isVisible(pos, getPlayerID());
  371. }
  372. bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const
  373. {
  374. return gs->isVisible(obj, Player);
  375. }
  376. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  377. {
  378. return isVisible(obj, getPlayerID());
  379. }
  380. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  381. // {
  382. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  383. // if()
  384. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  385. // if(!armi)
  386. // return nullptr;
  387. // else
  388. // return armi;
  389. // }
  390. std::vector < const CGObjectInstance * > CGameInfoCallback::getBlockingObjs( int3 pos ) const
  391. {
  392. std::vector<const CGObjectInstance *> ret;
  393. const TerrainTile *t = getTile(pos);
  394. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  395. for(const CGObjectInstance * obj : t->blockingObjects)
  396. ret.push_back(obj);
  397. return ret;
  398. }
  399. std::vector <const CGObjectInstance * > CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  400. {
  401. std::vector<const CGObjectInstance *> ret;
  402. const TerrainTile *t = getTile(pos, verbose);
  403. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  404. for(const CGObjectInstance * obj : t->visitableObjects)
  405. {
  406. if(getPlayerID() || obj->ID != Obj::EVENT) //hide events from players
  407. ret.push_back(obj);
  408. }
  409. return ret;
  410. }
  411. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  412. {
  413. return vstd::backOrNull(getVisitableObjs(pos));
  414. }
  415. std::vector < const CGObjectInstance * > CGameInfoCallback::getFlaggableObjects(int3 pos) const
  416. {
  417. std::vector<const CGObjectInstance *> ret;
  418. const TerrainTile *t = getTile(pos);
  419. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  420. for(const CGObjectInstance *obj : t->blockingObjects)
  421. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  422. ret.push_back(obj);
  423. return ret;
  424. }
  425. int3 CGameInfoCallback::getMapSize() const
  426. {
  427. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  428. }
  429. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  430. {
  431. ASSERT_IF_CALLED_WITH_PLAYER
  432. std::vector<const CGHeroInstance *> ret;
  433. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  434. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  435. const CGTownInstance * town = getTown(townOrTavern->id);
  436. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  437. return gs->heroesPool->getHeroesFor(*getPlayerID());
  438. return ret;
  439. }
  440. const TerrainTile * CGameInfoCallback::getTile( int3 tile, bool verbose) const
  441. {
  442. if(isVisible(tile))
  443. return &gs->map->getTile(tile);
  444. if(verbose)
  445. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  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->builded >= 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->rumor.type == RumorState::TYPE_NONE)
  554. return text.toString();
  555. auto rumor = gs->rumor.last[gs->rumor.type];
  556. switch(gs->rumor.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 obejct 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 & 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() || 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. CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  823. {
  824. auto hero = const_cast<CGHeroInstance*>(getHero(loc.artHolder));
  825. if(loc.creature.has_value())
  826. {
  827. if(loc.creature.value() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  828. return hero->commander;
  829. else
  830. return hero->getStackPtr(loc.creature.value());
  831. }
  832. else
  833. {
  834. return hero;
  835. }
  836. }
  837. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  838. {
  839. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  840. {
  841. const auto * obj = getObj(id, false);
  842. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  843. });
  844. return ids;
  845. }
  846. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntraces(TeleportChannelID id, PlayerColor player) const
  847. {
  848. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  849. }
  850. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  851. {
  852. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  853. }
  854. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  855. {
  856. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntraces(id, player);
  857. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  858. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  859. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  860. {
  861. return ETeleportChannelType::IMPASSABLE;
  862. }
  863. auto intersection = vstd::intersection(entrances, exits);
  864. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  865. return ETeleportChannelType::BIDIRECTIONAL;
  866. else if(intersection.empty())
  867. return ETeleportChannelType::UNIDIRECTIONAL;
  868. else
  869. return ETeleportChannelType::MIXED;
  870. }
  871. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  872. {
  873. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  874. }
  875. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  876. {
  877. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  878. }
  879. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  880. {
  881. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  882. }
  883. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  884. {
  885. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  886. }
  887. VCMI_LIB_NAMESPACE_END