CGameInfoCallback.cpp 29 KB

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