CGameInfoCallback.cpp 29 KB

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