CGameInfoCallback.cpp 28 KB

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