CGameInfoCallback.cpp 30 KB

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