CGameInfoCallback.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  437. {
  438. if(!isVisible(tile))
  439. return EDiggingStatus::UNKNOWN;
  440. for(const auto & object : gs->map->objects)
  441. {
  442. if(object && object->ID == Obj::HOLE && object->pos == tile)
  443. return EDiggingStatus::TILE_OCCUPIED;
  444. }
  445. return getTile(tile)->getDiggingStatus();
  446. }
  447. //TODO: typedef?
  448. std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
  449. {
  450. assert(player.is_initialized());
  451. auto team = getPlayerTeam(player.get());
  452. size_t width = gs->map->width;
  453. size_t height = gs->map->height;
  454. size_t levels = gs->map->levels();
  455. auto ptr = new boost::multi_array<TerrainTile*, 3>(boost::extents[levels][width][height]);
  456. int3 tile;
  457. for(tile.z = 0; tile.z < levels; tile.z++)
  458. for(tile.x = 0; tile.x < width; tile.x++)
  459. for(tile.y = 0; tile.y < height; tile.y++)
  460. {
  461. if ((*team->fogOfWarMap)[tile.z][tile.x][tile.y])
  462. (*ptr)[tile.z][tile.x][tile.y] = &gs->map->getTile(tile);
  463. else
  464. (*ptr)[tile.z][tile.x][tile.y] = nullptr;
  465. }
  466. return std::shared_ptr<const boost::multi_array<TerrainTile*, 3>>(ptr);
  467. }
  468. EBuildingState::EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  469. {
  470. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  471. if(!t->town->buildings.count(ID))
  472. return EBuildingState::BUILDING_ERROR;
  473. const CBuilding * building = t->town->buildings.at(ID);
  474. if(t->hasBuilt(ID)) //already built
  475. return EBuildingState::ALREADY_PRESENT;
  476. //can we build it?
  477. if(vstd::contains(t->forbiddenBuildings, ID))
  478. return EBuildingState::FORBIDDEN; //forbidden
  479. auto possiblyNotBuiltTest = [&](BuildingID id) -> bool
  480. {
  481. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  482. };
  483. std::function<bool(BuildingID id)> allowedTest = [&](BuildingID id) -> bool
  484. {
  485. return !vstd::contains(t->forbiddenBuildings, id);
  486. };
  487. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  488. return EBuildingState::FORBIDDEN;
  489. if(ID == BuildingID::CAPITOL)
  490. {
  491. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  492. if(ps)
  493. {
  494. for(const CGTownInstance *town : ps->towns)
  495. {
  496. if(town->hasBuilt(BuildingID::CAPITOL))
  497. {
  498. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  499. }
  500. }
  501. }
  502. }
  503. else if(ID == BuildingID::SHIPYARD)
  504. {
  505. const TerrainTile *tile = getTile(t->bestLocation(), false);
  506. if(!tile || tile->terType->isLand())
  507. return EBuildingState::NO_WATER; //lack of water
  508. }
  509. auto buildTest = [&](BuildingID id) -> bool
  510. {
  511. return t->hasBuilt(id);
  512. };
  513. if (!t->genBuildingRequirements(ID).test(buildTest))
  514. return EBuildingState::PREREQUIRES;
  515. if(t->builded >= VLC->modh->settings.MAX_BUILDING_PER_TURN)
  516. return EBuildingState::CANT_BUILD_TODAY; //building limit
  517. //checking resources
  518. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  519. return EBuildingState::NO_RESOURCES; //lack of res
  520. return EBuildingState::ALLOWED;
  521. }
  522. const CMapHeader * CGameInfoCallback::getMapHeader() const
  523. {
  524. return gs->map;
  525. }
  526. bool CGameInfoCallback::hasAccess(boost::optional<PlayerColor> playerId) const
  527. {
  528. return !player || player.get().isSpectator() || gs->getPlayerRelations( *playerId, *player ) != PlayerRelations::ENEMIES;
  529. }
  530. EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  531. {
  532. const PlayerState *ps = gs->getPlayerState(player, verbose);
  533. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  534. return ps->status;
  535. }
  536. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  537. {
  538. std::string text = "", extraText = "";
  539. if(gs->rumor.type == RumorState::TYPE_NONE)
  540. return text;
  541. auto rumor = gs->rumor.last[gs->rumor.type];
  542. switch(gs->rumor.type)
  543. {
  544. case RumorState::TYPE_SPECIAL:
  545. if(rumor.first == RumorState::RUMOR_GRAIL)
  546. extraText = VLC->generaltexth->arraytxt[158 + rumor.second];
  547. else
  548. extraText = VLC->generaltexth->capColors[rumor.second];
  549. text = boost::str(boost::format(VLC->generaltexth->allTexts[rumor.first]) % extraText);
  550. break;
  551. case RumorState::TYPE_MAP:
  552. text = gs->map->rumors[rumor.first].text;
  553. break;
  554. case RumorState::TYPE_RAND:
  555. text = VLC->generaltexth->tavernRumors[rumor.first];
  556. break;
  557. }
  558. return text;
  559. }
  560. PlayerRelations::PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  561. {
  562. return gs->getPlayerRelations(color1, color2);
  563. }
  564. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  565. {
  566. return !obj || hasAccess(obj->tempOwner);
  567. }
  568. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  569. {
  570. int ret = 0;
  571. const PlayerState *p = gs->getPlayerState(player);
  572. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  573. if(includeGarrisoned)
  574. return static_cast<int>(p->heroes.size());
  575. else
  576. for(auto & elem : p->heroes)
  577. if(!elem->inTownGarrison)
  578. ret++;
  579. return ret;
  580. }
  581. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  582. {
  583. if(canGetFullInfo(obj))
  584. return true;
  585. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  586. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the obejct itself at last
  587. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  588. }
  589. PlayerColor CGameInfoCallback::getCurrentPlayer() const
  590. {
  591. return gs->currentPlayer;
  592. }
  593. CGameInfoCallback::CGameInfoCallback()
  594. {
  595. }
  596. CGameInfoCallback::CGameInfoCallback(CGameState *GS, boost::optional<PlayerColor> Player)
  597. {
  598. gs = GS;
  599. player = Player;
  600. }
  601. std::shared_ptr<const boost::multi_array<ui8, 3>> CPlayerSpecificInfoCallback::getVisibilityMap() const
  602. {
  603. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  604. return gs->getPlayerTeam(*player)->fogOfWarMap;
  605. }
  606. int CPlayerSpecificInfoCallback::howManyTowns() const
  607. {
  608. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  609. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  610. return CGameInfoCallback::howManyTowns(*player);
  611. }
  612. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  613. {
  614. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  615. std::vector < const CGTownInstance *> ret = std::vector < const CGTownInstance *>();
  616. for(const auto & i : gs->players)
  617. {
  618. for(const auto & town : i.second.towns)
  619. {
  620. if(i.first == player || (!onlyOur && isVisible(town, player)))
  621. {
  622. ret.push_back(town);
  623. }
  624. }
  625. } // for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  626. return ret;
  627. }
  628. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo(bool onlyOur) const
  629. {
  630. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  631. std::vector < const CGHeroInstance *> ret;
  632. for(auto hero : gs->map->heroesOnMap)
  633. {
  634. // !player || // - why would we even get access to hero not owned by any player?
  635. if((hero->tempOwner == *player) ||
  636. (isVisible(hero->visitablePos(), player) && !onlyOur) )
  637. {
  638. ret.push_back(hero);
  639. }
  640. }
  641. return ret;
  642. }
  643. boost::optional<PlayerColor> CPlayerSpecificInfoCallback::getMyColor() const
  644. {
  645. return player;
  646. }
  647. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  648. {
  649. if (hero->inTownGarrison && !includeGarrisoned)
  650. return -1;
  651. size_t index = 0;
  652. auto & heroes = gs->players[*player].heroes;
  653. for (auto & heroe : heroes)
  654. {
  655. if (includeGarrisoned || !(heroe)->inTownGarrison)
  656. index++;
  657. if (heroe == hero)
  658. return static_cast<int>(index);
  659. }
  660. return -1;
  661. }
  662. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  663. {
  664. if (!player || CGObelisk::obeliskCount == 0)
  665. {
  666. *outKnownRatio = 0.0;
  667. }
  668. else
  669. {
  670. TeamID t = gs->getPlayerTeam(*player)->id;
  671. double visited = 0.0;
  672. if(CGObelisk::visited.count(t))
  673. visited = static_cast<double>(CGObelisk::visited[t]);
  674. *outKnownRatio = visited / CGObelisk::obeliskCount;
  675. }
  676. return gs->map->grailPos;
  677. }
  678. std::vector < const CGObjectInstance * > CPlayerSpecificInfoCallback::getMyObjects() const
  679. {
  680. std::vector < const CGObjectInstance * > ret;
  681. for(const CGObjectInstance * obj : gs->map->objects)
  682. {
  683. if(obj && obj->tempOwner == player)
  684. ret.push_back(obj);
  685. }
  686. return ret;
  687. }
  688. std::vector < const CGDwelling * > CPlayerSpecificInfoCallback::getMyDwellings() const
  689. {
  690. ASSERT_IF_CALLED_WITH_PLAYER
  691. std::vector < const CGDwelling * > ret;
  692. for(CGDwelling * dw : gs->getPlayerState(*player)->dwellings)
  693. {
  694. ret.push_back(dw);
  695. }
  696. return ret;
  697. }
  698. std::vector <QuestInfo> CPlayerSpecificInfoCallback::getMyQuests() const
  699. {
  700. std::vector <QuestInfo> ret;
  701. for (auto quest : gs->getPlayerState(*player)->quests)
  702. {
  703. ret.push_back (quest);
  704. }
  705. return ret;
  706. }
  707. int CPlayerSpecificInfoCallback::howManyHeroes(bool includeGarrisoned) const
  708. {
  709. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  710. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  711. return getHeroCount(*player,includeGarrisoned);
  712. }
  713. const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId, bool includeGarrisoned) const
  714. {
  715. ASSERT_IF_CALLED_WITH_PLAYER
  716. const PlayerState *p = getPlayerState(*player);
  717. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  718. if (!includeGarrisoned)
  719. {
  720. for(ui32 i = 0; i < p->heroes.size() && (int)i<=serialId; i++)
  721. if(p->heroes[i]->inTownGarrison)
  722. serialId++;
  723. }
  724. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->heroes.size(), "No player info", nullptr);
  725. return p->heroes[serialId];
  726. }
  727. const CGTownInstance* CPlayerSpecificInfoCallback::getTownBySerial(int serialId) const
  728. {
  729. ASSERT_IF_CALLED_WITH_PLAYER
  730. const PlayerState *p = getPlayerState(*player);
  731. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  732. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->towns.size(), "No player info", nullptr);
  733. return p->towns[serialId];
  734. }
  735. int CPlayerSpecificInfoCallback::getResourceAmount(Res::ERes type) const
  736. {
  737. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  738. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  739. return getResource(*player, type);
  740. }
  741. TResources CPlayerSpecificInfoCallback::getResourceAmount() const
  742. {
  743. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  744. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", TResources());
  745. return gs->players[*player].resources;
  746. }
  747. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  748. {
  749. //rewritten by hand, AI calls this function a lot
  750. auto team = gs->teams.find(teamID);
  751. if (team != gs->teams.end())
  752. {
  753. const TeamState *ret = &team->second;
  754. if (!player.is_initialized()) //neutral (or invalid) player
  755. return ret;
  756. else
  757. {
  758. if (vstd::contains(ret->players, *player)) //specific player
  759. return ret;
  760. else
  761. {
  762. logGlobal->error("Illegal attempt to access team data!");
  763. return nullptr;
  764. }
  765. }
  766. }
  767. else
  768. {
  769. logGlobal->error("Cannot find info for team %d", teamID);
  770. return nullptr;
  771. }
  772. }
  773. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  774. {
  775. auto player = gs->players.find(color);
  776. if (player != gs->players.end())
  777. {
  778. return getTeam (player->second.team);
  779. }
  780. else
  781. {
  782. return nullptr;
  783. }
  784. }
  785. const CGHeroInstance * CGameInfoCallback::getHeroWithSubid( int subid ) const
  786. {
  787. if(subid<0)
  788. return nullptr;
  789. if(subid>= gs->map->allHeroes.size())
  790. return nullptr;
  791. return gs->map->allHeroes.at(subid).get();
  792. }
  793. PlayerColor CGameInfoCallback::getLocalPlayer() const
  794. {
  795. return getCurrentPlayer();
  796. }
  797. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  798. {
  799. return gs->map->isInTheMap(pos);
  800. }
  801. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3, ShashInt3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  802. {
  803. gs->getTilesInRange(tiles, pos, radious, getLocalPlayer(), -1, distanceFormula);
  804. }
  805. void CGameInfoCallback::calculatePaths(std::shared_ptr<PathfinderConfig> config)
  806. {
  807. gs->calculatePaths(config);
  808. }
  809. void CGameInfoCallback::calculatePaths( const CGHeroInstance *hero, CPathsInfo &out)
  810. {
  811. gs->calculatePaths(hero, out);
  812. }
  813. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  814. {
  815. return gs->map->artInstances[aid.num];
  816. }
  817. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  818. {
  819. return gs->map->objects[oid.num];
  820. }
  821. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  822. {
  823. vstd::erase_if(ids, [&](ObjectInstanceID id) -> bool
  824. {
  825. auto obj = getObj(id, false);
  826. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  827. });
  828. return ids;
  829. }
  830. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntraces(TeleportChannelID id, PlayerColor player) const
  831. {
  832. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  833. }
  834. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  835. {
  836. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  837. }
  838. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  839. {
  840. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntraces(id, player);
  841. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  842. if((!entrances.size() || !exits.size()) // impassable if exits or entrances list are empty
  843. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  844. {
  845. return ETeleportChannelType::IMPASSABLE;
  846. }
  847. auto intersection = vstd::intersection(entrances, exits);
  848. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  849. return ETeleportChannelType::BIDIRECTIONAL;
  850. else if(!intersection.size())
  851. return ETeleportChannelType::UNIDIRECTIONAL;
  852. else
  853. return ETeleportChannelType::MIXED;
  854. }
  855. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  856. {
  857. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  858. }
  859. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  860. {
  861. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  862. }
  863. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  864. {
  865. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  866. }
  867. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  868. {
  869. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  870. }
  871. VCMI_LIB_NAMESPACE_END