CGameInfoCallback.cpp 29 KB

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