CGameInfoCallback.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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 "CGameState.h" // PlayerState
  13. #include "CGeneralTextHandler.h"
  14. #include "mapObjects/CObjectHandler.h" // for CGObjectInstance
  15. #include "StartInfo.h" // for StartInfo
  16. #include "battle/BattleInfo.h" // for BattleInfo
  17. #include "NetPacks.h" // for InfoWindow
  18. #include "CModHandler.h"
  19. #include "TerrainHandler.h"
  20. #include "spells/CSpellHandler.h"
  21. #include "mapping/CMap.h"
  22. #include "CPlayerState.h"
  23. VCMI_LIB_NAMESPACE_BEGIN
  24. //TODO make clean
  25. #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)
  26. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return;}} while(0)
  27. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  28. PlayerColor CGameInfoCallback::getOwner(ObjectInstanceID heroID) const
  29. {
  30. const CGObjectInstance *obj = getObj(heroID);
  31. ERROR_RET_VAL_IF(!obj, "No such object!", PlayerColor::CANNOT_DETERMINE);
  32. return obj->tempOwner;
  33. }
  34. int CGameInfoCallback::getResource(PlayerColor Player, Res::ERes which) const
  35. {
  36. const PlayerState *p = getPlayerState(Player);
  37. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  38. ERROR_RET_VAL_IF(p->resources.size() <= which || which < 0, "No such resource!", -1);
  39. return p->resources[which];
  40. }
  41. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  42. {
  43. return &gs->scenarioOps->getIthPlayersSettings(color);
  44. }
  45. bool CGameInfoCallback::isAllowed(int32_t type, int32_t id) const
  46. {
  47. switch(type)
  48. {
  49. case 0:
  50. return gs->map->allowedSpell[id];
  51. case 1:
  52. return gs->map->allowedArtifact[id];
  53. case 2:
  54. return gs->map->allowedAbilities[id];
  55. default:
  56. ERROR_RET_VAL_IF(1, "Wrong type!", false);
  57. }
  58. }
  59. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  60. {
  61. return getPlayerState(color, false);
  62. }
  63. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  64. {
  65. //funtion written from scratch since it's accessed A LOT by AI
  66. if(!color.isValidPlayer())
  67. {
  68. return nullptr;
  69. }
  70. auto player = gs->players.find(color);
  71. if (player != gs->players.end())
  72. {
  73. if (hasAccess(color))
  74. return &player->second;
  75. else
  76. {
  77. if (verbose)
  78. logGlobal->error("Cannot access player %d info!", color);
  79. return nullptr;
  80. }
  81. }
  82. else
  83. {
  84. if (verbose)
  85. logGlobal->error("Cannot find player %d info!", color);
  86. return nullptr;
  87. }
  88. }
  89. const CTown * CGameInfoCallback::getNativeTown(PlayerColor color) const
  90. {
  91. const PlayerSettings *ps = getPlayerSettings(color);
  92. ERROR_RET_VAL_IF(!ps, "There is no such player!", nullptr);
  93. return (*VLC->townh)[ps->castle]->town;
  94. }
  95. const CGObjectInstance * CGameInfoCallback::getObjByQuestIdentifier(int identifier) const
  96. {
  97. if(gs->map->questIdentifierToId.empty())
  98. {
  99. //assume that it is VCMI map and quest identifier equals instance identifier
  100. return getObj(ObjectInstanceID(identifier), true);
  101. }
  102. else
  103. {
  104. ERROR_RET_VAL_IF(!vstd::contains(gs->map->questIdentifierToId, identifier), "There is no object with such quest identifier!", nullptr);
  105. return getObj(gs->map->questIdentifierToId[identifier]);
  106. }
  107. }
  108. /************************************************************************/
  109. /* */
  110. /************************************************************************/
  111. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  112. {
  113. si32 oid = objid.num;
  114. if(oid < 0 || oid >= gs->map->objects.size())
  115. {
  116. if(verbose)
  117. logGlobal->error("Cannot get object with id %d", oid);
  118. return nullptr;
  119. }
  120. const CGObjectInstance *ret = gs->map->objects[oid];
  121. if(!ret)
  122. {
  123. if(verbose)
  124. logGlobal->error("Cannot get object with id %d. Object was removed", oid);
  125. return nullptr;
  126. }
  127. if(!isVisible(ret, player) && ret->tempOwner != player)
  128. {
  129. if(verbose)
  130. logGlobal->error("Cannot get object with id %d. Object is not visible.", oid);
  131. return nullptr;
  132. }
  133. return ret;
  134. }
  135. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  136. {
  137. const CGObjectInstance *obj = getObj(objid, false);
  138. if(obj)
  139. return dynamic_cast<const CGHeroInstance*>(obj);
  140. else
  141. return nullptr;
  142. }
  143. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  144. {
  145. const CGObjectInstance *obj = getObj(objid, false);
  146. if(obj)
  147. return dynamic_cast<const CGTownInstance*>(obj);
  148. else
  149. return nullptr;
  150. }
  151. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  152. {
  153. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  154. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  155. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  156. gs->fillUpgradeInfo(obj, stackPos, out);
  157. //return gs->fillUpgradeInfo(obj->getStack(stackPos));
  158. }
  159. const StartInfo * CGameInfoCallback::getStartInfo(bool beforeRandomization) const
  160. {
  161. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  162. if(beforeRandomization)
  163. return gs->initialOpts;
  164. else
  165. return gs->scenarioOps;
  166. }
  167. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  168. {
  169. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  170. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  171. //if there is a battle
  172. if(gs->curB)
  173. return gs->curB->battleGetSpellCost(sp, caster);
  174. //if there is no battle
  175. return caster->getSpellCost(sp);
  176. }
  177. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  178. {
  179. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  180. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  181. if(hero) //we see hero's spellbook
  182. return sp->calculateDamage(hero);
  183. else
  184. return 0; //mage guild
  185. }
  186. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  187. {
  188. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  189. ERROR_RET_IF(!obj, "No guild object!");
  190. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  191. //TODO: advmap object -> check if they're visited by our hero
  192. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  193. {
  194. int taverns = 0;
  195. for(auto town : gs->players[*player].towns)
  196. {
  197. if(town->hasBuilt(BuildingID::TAVERN))
  198. taverns++;
  199. }
  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].towns.size());
  211. }
  212. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  213. {
  214. ERROR_RET_VAL_IF(!isVisible(town, player), "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 CGHeroInstance * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  221. if(nullptr != selectedHero)
  222. detailed = selectedHero->hasVisions(town, 1);
  223. }
  224. dest.initFromTown(static_cast<const CGTownInstance *>(town), detailed);
  225. }
  226. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  227. dest.initFromArmy(static_cast<const CArmedInstance *>(town), detailed);
  228. else
  229. return false;
  230. return true;
  231. }
  232. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const //FIXME: redundant?
  233. {
  234. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  235. return gs->guardingCreaturePosition(pos);
  236. }
  237. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  238. {
  239. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  240. std::vector<const CGObjectInstance*> ret;
  241. for(auto cr : gs->guardingCreatures(pos))
  242. {
  243. ret.push_back(cr);
  244. }
  245. return ret;
  246. }
  247. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  248. {
  249. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(hero);
  250. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  251. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  252. if(hasAccess(h->tempOwner))
  253. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  254. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  255. {
  256. if(gs->curB && gs->curB->playerHasAccessToHeroInfo(*player, h)) //if it's battle we can get enemy hero full data
  257. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  258. else
  259. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  260. }
  261. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  262. {
  263. const CGHeroInstance * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  264. if(nullptr != selectedHero)
  265. if(selectedHero->hasVisions(hero, 1))
  266. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  267. }
  268. dest.initFromHero(h, infoLevel);
  269. //DISGUISED bonus implementation
  270. if(getPlayerRelations(getLocalPlayer(), hero->tempOwner) == PlayerRelations::ENEMIES)
  271. {
  272. //todo: bonus cashing
  273. int disguiseLevel = h->valOfBonuses(Selector::typeSubtype(Bonus::DISGUISED, 0));
  274. auto doBasicDisguise = [](InfoAboutHero & info)
  275. {
  276. int maxAIValue = 0;
  277. const CCreature * mostStrong = nullptr;
  278. for(auto & elem : info.army)
  279. {
  280. if((int)elem.second.type->AIValue > maxAIValue)
  281. {
  282. maxAIValue = elem.second.type->AIValue;
  283. mostStrong = elem.second.type;
  284. }
  285. }
  286. if(nullptr == mostStrong)//just in case
  287. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  288. else
  289. for(auto & elem : info.army)
  290. {
  291. elem.second.type = mostStrong;
  292. }
  293. };
  294. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  295. {
  296. doBasicDisguise(info);
  297. for(auto & elem : info.army)
  298. elem.second.count = 0;
  299. };
  300. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  301. {
  302. for(auto & elem : info.army)
  303. elem.second.count = 0;
  304. const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle;
  305. int maxAIValue = 0;
  306. const CCreature * mostStrong = nullptr;
  307. for(auto creature : VLC->creh->objects)
  308. {
  309. if((si16)creature->faction == factionIndex && (int)creature->AIValue > maxAIValue)
  310. {
  311. maxAIValue = creature->AIValue;
  312. mostStrong = creature;
  313. }
  314. }
  315. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  316. for(auto & elem : info.army)
  317. elem.second.type = mostStrong;
  318. };
  319. switch (disguiseLevel)
  320. {
  321. case 0:
  322. //no bonus at all - do nothing
  323. break;
  324. case 1:
  325. doBasicDisguise(dest);
  326. break;
  327. case 2:
  328. doAdvancedDisguise(dest);
  329. break;
  330. case 3:
  331. doExpertDisguise(dest);
  332. break;
  333. default:
  334. //invalid value
  335. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  336. break;
  337. }
  338. }
  339. return true;
  340. }
  341. int CGameInfoCallback::getDate(Date::EDateType mode) const
  342. {
  343. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  344. return gs->getDate(mode);
  345. }
  346. bool CGameInfoCallback::isVisible(int3 pos, boost::optional<PlayerColor> Player) const
  347. {
  348. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  349. return gs->isVisible(pos, Player);
  350. }
  351. bool CGameInfoCallback::isVisible(int3 pos) const
  352. {
  353. return isVisible(pos, player);
  354. }
  355. bool CGameInfoCallback::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> Player ) const
  356. {
  357. return gs->isVisible(obj, Player);
  358. }
  359. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  360. {
  361. return isVisible(obj, player);
  362. }
  363. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  364. // {
  365. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  366. // if()
  367. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  368. // if(!armi)
  369. // return nullptr;
  370. // else
  371. // return armi;
  372. // }
  373. std::vector < const CGObjectInstance * > CGameInfoCallback::getBlockingObjs( int3 pos ) const
  374. {
  375. std::vector<const CGObjectInstance *> ret;
  376. const TerrainTile *t = getTile(pos);
  377. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  378. for(const CGObjectInstance * obj : t->blockingObjects)
  379. ret.push_back(obj);
  380. return ret;
  381. }
  382. std::vector <const CGObjectInstance * > CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  383. {
  384. std::vector<const CGObjectInstance *> ret;
  385. const TerrainTile *t = getTile(pos, verbose);
  386. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  387. for(const CGObjectInstance * obj : t->visitableObjects)
  388. {
  389. if(player || obj->ID != Obj::EVENT) //hide events from players
  390. ret.push_back(obj);
  391. }
  392. return ret;
  393. }
  394. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  395. {
  396. return vstd::backOrNull(getVisitableObjs(pos));
  397. }
  398. std::vector < const CGObjectInstance * > CGameInfoCallback::getFlaggableObjects(int3 pos) const
  399. {
  400. std::vector<const CGObjectInstance *> ret;
  401. const TerrainTile *t = getTile(pos);
  402. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  403. for(const CGObjectInstance *obj : t->blockingObjects)
  404. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  405. ret.push_back(obj);
  406. return ret;
  407. }
  408. int3 CGameInfoCallback::getMapSize() const
  409. {
  410. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  411. }
  412. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  413. {
  414. ASSERT_IF_CALLED_WITH_PLAYER
  415. std::vector<const CGHeroInstance *> ret;
  416. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  417. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  418. const CGTownInstance * town = getTown(townOrTavern->id);
  419. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  420. {
  421. range::copy(gs->players[*player].availableHeroes, std::back_inserter(ret));
  422. vstd::erase_if(ret, [](const CGHeroInstance * h) {
  423. return h == nullptr;
  424. });
  425. }
  426. return ret;
  427. }
  428. const TerrainTile * CGameInfoCallback::getTile( int3 tile, bool verbose) const
  429. {
  430. if(isVisible(tile))
  431. return &gs->map->getTile(tile);
  432. if(verbose)
  433. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  434. return nullptr;
  435. }
  436. //TODO: typedef?
  437. std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
  438. {
  439. assert(player.is_initialized());
  440. auto team = getPlayerTeam(player.get());
  441. size_t width = gs->map->width;
  442. size_t height = gs->map->height;
  443. size_t levels = gs->map->levels();
  444. auto ptr = new boost::multi_array<TerrainTile*, 3>(boost::extents[levels][width][height]);
  445. int3 tile;
  446. for(tile.z = 0; tile.z < levels; tile.z++)
  447. for(tile.x = 0; tile.x < width; tile.x++)
  448. for(tile.y = 0; tile.y < height; tile.y++)
  449. {
  450. if ((*team->fogOfWarMap)[tile.z][tile.x][tile.y])
  451. (*ptr)[tile.z][tile.x][tile.y] = &gs->map->getTile(tile);
  452. else
  453. (*ptr)[tile.z][tile.x][tile.y] = nullptr;
  454. }
  455. return std::shared_ptr<const boost::multi_array<TerrainTile*, 3>>(ptr);
  456. }
  457. EBuildingState::EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  458. {
  459. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  460. if(!t->town->buildings.count(ID))
  461. return EBuildingState::BUILDING_ERROR;
  462. const CBuilding * building = t->town->buildings.at(ID);
  463. if(t->hasBuilt(ID)) //already built
  464. return EBuildingState::ALREADY_PRESENT;
  465. //can we build it?
  466. if(vstd::contains(t->forbiddenBuildings, ID))
  467. return EBuildingState::FORBIDDEN; //forbidden
  468. auto possiblyNotBuiltTest = [&](BuildingID id) -> bool
  469. {
  470. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  471. };
  472. std::function<bool(BuildingID id)> allowedTest = [&](BuildingID id) -> bool
  473. {
  474. return !vstd::contains(t->forbiddenBuildings, id);
  475. };
  476. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  477. return EBuildingState::FORBIDDEN;
  478. if(ID == BuildingID::CAPITOL)
  479. {
  480. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  481. if(ps)
  482. {
  483. for(const CGTownInstance *town : ps->towns)
  484. {
  485. if(town->hasBuilt(BuildingID::CAPITOL))
  486. {
  487. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  488. }
  489. }
  490. }
  491. }
  492. else if(ID == BuildingID::SHIPYARD)
  493. {
  494. const TerrainTile *tile = getTile(t->bestLocation(), false);
  495. if(!tile || tile->terType->isLand())
  496. return EBuildingState::NO_WATER; //lack of water
  497. }
  498. auto buildTest = [&](BuildingID id) -> bool
  499. {
  500. return t->hasBuilt(id);
  501. };
  502. if (!t->genBuildingRequirements(ID).test(buildTest))
  503. return EBuildingState::PREREQUIRES;
  504. if(t->builded >= VLC->modh->settings.MAX_BUILDING_PER_TURN)
  505. return EBuildingState::CANT_BUILD_TODAY; //building limit
  506. //checking resources
  507. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  508. return EBuildingState::NO_RESOURCES; //lack of res
  509. return EBuildingState::ALLOWED;
  510. }
  511. const CMapHeader * CGameInfoCallback::getMapHeader() const
  512. {
  513. return gs->map;
  514. }
  515. bool CGameInfoCallback::hasAccess(boost::optional<PlayerColor> playerId) const
  516. {
  517. return !player || player.get().isSpectator() || gs->getPlayerRelations( *playerId, *player ) != PlayerRelations::ENEMIES;
  518. }
  519. EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  520. {
  521. const PlayerState *ps = gs->getPlayerState(player, verbose);
  522. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  523. return ps->status;
  524. }
  525. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  526. {
  527. std::string text = "", extraText = "";
  528. if(gs->rumor.type == RumorState::TYPE_NONE)
  529. return text;
  530. auto rumor = gs->rumor.last[gs->rumor.type];
  531. switch(gs->rumor.type)
  532. {
  533. case RumorState::TYPE_SPECIAL:
  534. if(rumor.first == RumorState::RUMOR_GRAIL)
  535. extraText = VLC->generaltexth->arraytxt[158 + rumor.second];
  536. else
  537. extraText = VLC->generaltexth->capColors[rumor.second];
  538. text = boost::str(boost::format(VLC->generaltexth->allTexts[rumor.first]) % extraText);
  539. break;
  540. case RumorState::TYPE_MAP:
  541. text = gs->map->rumors[rumor.first].text;
  542. break;
  543. case RumorState::TYPE_RAND:
  544. text = VLC->generaltexth->tavernRumors[rumor.first];
  545. break;
  546. }
  547. return text;
  548. }
  549. PlayerRelations::PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  550. {
  551. return gs->getPlayerRelations(color1, color2);
  552. }
  553. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  554. {
  555. return !obj || hasAccess(obj->tempOwner);
  556. }
  557. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  558. {
  559. int ret = 0;
  560. const PlayerState *p = gs->getPlayerState(player);
  561. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  562. if(includeGarrisoned)
  563. return static_cast<int>(p->heroes.size());
  564. else
  565. for(auto & elem : p->heroes)
  566. if(!elem->inTownGarrison)
  567. ret++;
  568. return ret;
  569. }
  570. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  571. {
  572. if(canGetFullInfo(obj))
  573. return true;
  574. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  575. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the obejct itself at last
  576. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  577. }
  578. PlayerColor CGameInfoCallback::getCurrentPlayer() const
  579. {
  580. return gs->currentPlayer;
  581. }
  582. CGameInfoCallback::CGameInfoCallback()
  583. {
  584. }
  585. CGameInfoCallback::CGameInfoCallback(CGameState *GS, boost::optional<PlayerColor> Player)
  586. {
  587. gs = GS;
  588. player = 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. boost::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 (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() && (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(Res::ERes 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.is_initialized()) //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, ShashInt3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  791. {
  792. gs->getTilesInRange(tiles, pos, radious, getLocalPlayer(), -1, distanceFormula);
  793. }
  794. void CGameInfoCallback::calculatePaths(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, [&](ObjectInstanceID id) -> bool
  813. {
  814. 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.size() || !exits.size()) // 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.size())
  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