CGameInfoCallback.cpp 29 KB

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