AIUtility.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. /*
  2. * AIUtility.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 "AIUtility.h"
  12. #include "AIGateway.h"
  13. #include "Goals/Goals.h"
  14. #include "../../lib/UnlockGuard.h"
  15. #include "../../lib/CConfigHandler.h"
  16. #include "../../lib/entities/artifact/CArtifact.h"
  17. #include "../../lib/mapObjects/MapObjects.h"
  18. #include "../../lib/mapObjects/CQuest.h"
  19. #include "../../lib/mapping/TerrainTile.h"
  20. #include "../../lib/gameState/QuestInfo.h"
  21. #include "../../lib/IGameSettings.h"
  22. #include "../../lib/bonuses/Limiters.h"
  23. #include "../../lib/bonuses/Propagators.h"
  24. #include <vcmi/CreatureService.h>
  25. namespace NK2AI
  26. {
  27. const CGObjectInstance * ObjectIdRef::operator->() const
  28. {
  29. return ccTl->getObj(id, false);
  30. }
  31. ObjectIdRef::operator const CGObjectInstance *() const
  32. {
  33. return ccTl->getObj(id, false);
  34. }
  35. ObjectIdRef::operator bool() const
  36. {
  37. return ccTl->getObj(id, false);
  38. }
  39. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id)
  40. : id(_id)
  41. {
  42. }
  43. ObjectIdRef::ObjectIdRef(const CGObjectInstance * obj)
  44. : id(obj->id)
  45. {
  46. }
  47. bool ObjectIdRef::operator<(const ObjectIdRef & rhs) const
  48. {
  49. return id < rhs.id;
  50. }
  51. HeroPtr::HeroPtr(const CGHeroInstance * input, std::shared_ptr<CPlayerSpecificInfoCallback> cpsic)
  52. : hero(input), cpsic(cpsic)
  53. {
  54. }
  55. bool HeroPtr::operator<(const HeroPtr & rhs) const
  56. {
  57. return idOrNone() < rhs.idOrNone();
  58. }
  59. ObjectInstanceID HeroPtr::idOrNone() const
  60. {
  61. if (hero)
  62. return hero->id;
  63. return ObjectInstanceID::NONE;
  64. }
  65. std::string HeroPtr::nameOrDefault() const
  66. {
  67. if (hero)
  68. return hero->getNameTextID() + "(" + hero->getNameTranslated() + ")";
  69. return "<NO HERO>";
  70. }
  71. // enforces isVerified()
  72. const CGHeroInstance * HeroPtr::get() const
  73. {
  74. assert(isVerified());
  75. return hero;
  76. }
  77. // does not enforce isVerified()
  78. const CGHeroInstance * HeroPtr::getUnverified() const
  79. {
  80. return hero;
  81. }
  82. bool HeroPtr::verify() const
  83. {
  84. // TODO: check if these all assertions every time we get info about hero affect efficiency
  85. // behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  86. if(hero)
  87. {
  88. const auto *obj = cpsic->getObj(hero->id);
  89. //const bool owned = obj && obj->tempOwner == ai->playerID;
  90. if(!obj)
  91. return false;
  92. return true;
  93. //assert(owned);
  94. }
  95. return false;
  96. }
  97. // enforces isVerified()
  98. const CGHeroInstance * HeroPtr::operator->() const
  99. {
  100. assert(isVerified());
  101. return hero;
  102. }
  103. // Should be called before using the hero inside this HeroPtr, that's the point of this
  104. bool HeroPtr::isVerified() const
  105. {
  106. return verify();
  107. }
  108. // enforces isVerified()
  109. const CGHeroInstance * HeroPtr::operator*() const
  110. {
  111. assert(isVerified());
  112. return hero;
  113. }
  114. // enforces isVerified() on input
  115. bool HeroPtr::operator==(const HeroPtr & rhs) const
  116. {
  117. return hero == rhs.get();
  118. }
  119. bool isSafeToVisit(const CGHeroInstance * h, const CCreatureSet * heroArmy, uint64_t dangerStrength, float safeAttackRatio)
  120. {
  121. const ui64 heroStrength = h->getHeroStrength() * heroArmy->getArmyStrength();
  122. if(dangerStrength)
  123. {
  124. return heroStrength > dangerStrength * safeAttackRatio;
  125. }
  126. return true; //there's no danger
  127. }
  128. bool isSafeToVisit(const CGHeroInstance * h, uint64_t dangerStrength, float safeAttackRatio)
  129. {
  130. return isSafeToVisit(h, h, dangerStrength, safeAttackRatio);
  131. }
  132. bool isObjectRemovable(const CGObjectInstance * obj)
  133. {
  134. //FIXME: move logic to object property!
  135. switch (obj->ID)
  136. {
  137. case Obj::MONSTER:
  138. case Obj::RESOURCE:
  139. case Obj::CAMPFIRE:
  140. case Obj::TREASURE_CHEST:
  141. case Obj::ARTIFACT:
  142. case Obj::BORDERGUARD:
  143. case Obj::FLOTSAM:
  144. case Obj::PANDORAS_BOX:
  145. case Obj::OCEAN_BOTTLE:
  146. case Obj::SEA_CHEST:
  147. case Obj::SHIPWRECK_SURVIVOR:
  148. case Obj::SPELL_SCROLL:
  149. return true;
  150. default:
  151. return false;
  152. }
  153. }
  154. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater)
  155. {
  156. // TODO: Such information should be provided by pathfinder
  157. // Tile must be free or with unoccupied boat
  158. if(!t->blocked())
  159. {
  160. return true;
  161. }
  162. else if(!fromWater) // do not try to board when in water sector
  163. {
  164. if(t->visitableObjects.size() == 1 && ccTl->getObjInstance(t->topVisitableObj())->ID == Obj::BOAT)
  165. return true;
  166. }
  167. return false;
  168. }
  169. bool isObjectPassable(const Nullkiller * aiNk, const CGObjectInstance * obj)
  170. {
  171. return isObjectPassable(obj, aiNk->playerID, aiNk->cc->getPlayerRelations(obj->tempOwner, aiNk->playerID));
  172. }
  173. // Pathfinder internal helper
  174. bool isObjectPassable(const CGObjectInstance * obj, PlayerColor playerColor, PlayerRelations objectRelations)
  175. {
  176. if((obj->ID == Obj::GARRISON || obj->ID == Obj::GARRISON2)
  177. && objectRelations != PlayerRelations::ENEMIES)
  178. return true;
  179. if(obj->ID == Obj::BORDER_GATE)
  180. {
  181. auto quest = dynamic_cast<const CGKeys *>(obj);
  182. if(quest->wasMyColorVisited(playerColor))
  183. return true;
  184. }
  185. return false;
  186. }
  187. bool isBlockVisitObj(const int3 & pos)
  188. {
  189. if(auto obj = ccTl->getTopObj(pos))
  190. {
  191. if(obj->isBlockedVisitable()) //we can't stand on that object
  192. return true;
  193. }
  194. return false;
  195. }
  196. creInfo infoFromDC(const dwellingContent & dc)
  197. {
  198. creInfo ci;
  199. ci.count = dc.first;
  200. ci.creID = dc.second.size() ? dc.second.back() : CreatureID(-1); //should never be accessed
  201. if (ci.creID != CreatureID::NONE)
  202. {
  203. ci.level = ci.creID.toCreature()->getLevel(); //this is creature tier, while tryRealize expects dwelling level. Ignore.
  204. }
  205. else
  206. {
  207. ci.level = 0;
  208. }
  209. return ci;
  210. }
  211. bool compareHeroStrength(const CGHeroInstance * h1, const CGHeroInstance * h2)
  212. {
  213. return h1->getTotalStrength() < h2->getTotalStrength();
  214. }
  215. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2)
  216. {
  217. return a1->getArmyStrength() < a2->getArmyStrength();
  218. }
  219. double getArtifactBonusRelevance(const CGHeroInstance * hero, const std::shared_ptr<Bonus> & bonus)
  220. {
  221. if (bonus->propagator && bonus->limiter && bonus->propagator->getPropagatorType() == BonusNodeType::BATTLE_WIDE)
  222. {
  223. // assume that this is battle wide / other side propagator+limiter
  224. // consider it as fully relevant since we don't know about future combat when equipping artifacts
  225. return 1.0;
  226. }
  227. const auto & getArmyRatioAffectedByLimiter = [&]()
  228. {
  229. if (!bonus->limiter)
  230. return 1.0;
  231. uint64_t totalStrength = 0;
  232. uint64_t affectedStrength = 0;
  233. const BonusList stillUndecided;
  234. for (const auto & slot : hero->Slots())
  235. {
  236. const auto allBonuses = slot.second->getAllBonuses(Selector::all);
  237. BonusLimitationContext context = {*bonus, *slot.second, *allBonuses, stillUndecided};
  238. uint64_t unitStrength = slot.second->getPower();
  239. if (bonus->limiter->limit(context) == ILimiter::EDecision::ACCEPT)
  240. affectedStrength += unitStrength;
  241. totalStrength += unitStrength;
  242. }
  243. if (totalStrength == 0)
  244. return 0.0;
  245. return static_cast<double>(affectedStrength) / totalStrength;
  246. };
  247. const auto & getArmyPercentageWithBonus = [&](BonusType type)
  248. {
  249. uint64_t totalStrength = 0;
  250. uint64_t affectedStrength = 0;
  251. for (const auto & slot : hero->Slots())
  252. {
  253. uint64_t unitStrength = slot.second->getPower();
  254. if (slot.second->hasBonusOfType(type))
  255. affectedStrength += unitStrength;
  256. totalStrength += unitStrength;
  257. }
  258. if (totalStrength == 0)
  259. return 0.0;
  260. return static_cast<double>(affectedStrength) / totalStrength;
  261. };
  262. const auto & getSpellSchoolKnownSpellsFactor = [&](SpellSchool school)
  263. {
  264. uint64_t totalWeight = 0;
  265. uint64_t knownWeight = 0;
  266. for (auto spellID : LIBRARY->spellh->getDefaultAllowed())
  267. {
  268. auto spell = spellID.toEntity(LIBRARY);
  269. if (!spell->hasSchool(school))
  270. continue;
  271. uint64_t spellLevel = spell->getLevel();
  272. uint64_t spellWeight = spellLevel * spellLevel;
  273. if (!hero->spellbookContainsSpell(spellID))
  274. knownWeight += spellWeight;
  275. totalWeight += spellWeight;
  276. }
  277. if (totalWeight == 0)
  278. return 0.0;
  279. return static_cast<double>(knownWeight) / totalWeight;
  280. };
  281. const auto & getSpellLevelKnownSpellsFactor = [&](int level)
  282. {
  283. uint64_t totalWeight = 0;
  284. uint64_t knownWeight = 0;
  285. for (auto spellID : LIBRARY->spellh->getDefaultAllowed())
  286. {
  287. auto spell = spellID.toEntity(LIBRARY);
  288. if (spell->getLevel() != level)
  289. continue;
  290. if (!hero->spellbookContainsSpell(spellID))
  291. knownWeight += 1;
  292. totalWeight += 1;
  293. }
  294. if (totalWeight == 0)
  295. return 0.0;
  296. return static_cast<double>(knownWeight) / totalWeight;
  297. };
  298. constexpr double notRelevant = 0.0; // artifact is not useful in current conditions
  299. constexpr double relevant = 1.0;
  300. constexpr double veryRelevant = 2.0; // for very situational artifacts, e.g. skill-specific, or army composition-specific
  301. switch (bonus->type)
  302. {
  303. case BonusType::MOVEMENT:
  304. if (hero->getBoat() && bonus->subtype == BonusCustomSubtype::heroMovementSea)
  305. return veryRelevant;
  306. if (!hero->getBoat() && bonus->subtype == BonusCustomSubtype::heroMovementLand)
  307. return relevant;
  308. return notRelevant;
  309. case BonusType::STACKS_SPEED:
  310. case BonusType::STACK_HEALTH:
  311. return getArmyRatioAffectedByLimiter();
  312. case BonusType::MORALE:
  313. return getArmyRatioAffectedByLimiter() * (1 - getArmyPercentageWithBonus(BonusType::UNDEAD)); // TODO: other unaffected, e.g. Golems
  314. case BonusType::LUCK:
  315. return getArmyRatioAffectedByLimiter(); // Do we have luck?
  316. case BonusType::PRIMARY_SKILL:
  317. if (bonus->subtype == PrimarySkill::ATTACK || bonus->subtype == PrimarySkill::DEFENSE)
  318. return getArmyRatioAffectedByLimiter(); // e.g. Vial of Dragonblood - consider only affected unit
  319. else
  320. return relevant; // spellpower / knowledge - always relevant
  321. case BonusType::WATER_WALKING:
  322. case BonusType::FLYING_MOVEMENT:
  323. return hero->getBoat() ? notRelevant : relevant; // boat can't fly
  324. case BonusType::WHIRLPOOL_PROTECTION:
  325. return hero->getBoat() ? relevant : notRelevant;
  326. case BonusType::UNDEAD_RAISE_PERCENTAGE:
  327. return hero->hasBonusOfType(BonusType::IMPROVED_NECROMANCY) ? veryRelevant : notRelevant;
  328. case BonusType::SPELL_DAMAGE:
  329. case BonusType::SPELL_DURATION:
  330. return hero->hasSpellbook() ? relevant : notRelevant;
  331. case BonusType::PERCENTAGE_DAMAGE_BOOST:
  332. if (bonus->subtype == BonusCustomSubtype::damageTypeRanged)
  333. return veryRelevant * getArmyPercentageWithBonus(BonusType::SHOOTER);
  334. if (bonus->subtype == BonusCustomSubtype::damageTypeMelee)
  335. return veryRelevant * (1 - getArmyPercentageWithBonus(BonusType::SHOOTER));
  336. return 0;
  337. case BonusType::MANA_PERCENTAGE_REGENERATION:
  338. case BonusType::MANA_REGENERATION:
  339. return hero->hasSpellbook() ? relevant : notRelevant;
  340. case BonusType::LEARN_BATTLE_SPELL_CHANCE:
  341. return hero->hasBonusOfType(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT) ? relevant : notRelevant;
  342. case BonusType::NO_DISTANCE_PENALTY:
  343. case BonusType::NO_WALL_PENALTY:
  344. return getArmyPercentageWithBonus(BonusType::SHOOTER) * veryRelevant;
  345. case BonusType::SPELLS_OF_SCHOOL:
  346. if (!hero->hasSpellbook())
  347. return notRelevant;
  348. return 1 - getSpellSchoolKnownSpellsFactor(bonus->subtype.as<SpellSchool>());
  349. case BonusType::SPELLS_OF_LEVEL:
  350. if (!hero->hasSpellbook())
  351. return notRelevant;
  352. return 1 - getSpellLevelKnownSpellsFactor(bonus->subtype.getNum());
  353. // Potential TODO's
  354. // case BonusType::MAGIC_RESISTANCE:
  355. // case BonusType::FREE_SHIP_BOARDING:
  356. // case BonusType::GENERATE_RESOURCE:
  357. // case BonusType::CREATURE_GROWTH:
  358. //
  359. // case BonusType::SPELLS_OF_LEVEL:
  360. // case BonusType::SIGHT_RADIUS:
  361. }
  362. return 1.0;
  363. }
  364. int32_t getArtifactBonusScoreImpl(const std::shared_ptr<Bonus> & bonus)
  365. {
  366. switch (bonus->type)
  367. {
  368. case BonusType::MOVEMENT:
  369. if (bonus->subtype == BonusCustomSubtype::heroMovementLand)
  370. return bonus->val * 20;
  371. if (bonus->subtype == BonusCustomSubtype::heroMovementSea)
  372. return bonus->val * 10;
  373. return 0;
  374. case BonusType::STACKS_SPEED:
  375. return bonus->val * 8000;
  376. case BonusType::MORALE:
  377. return bonus->val * 1500;
  378. case BonusType::LUCK:
  379. return bonus->val * 1000;
  380. case BonusType::PRIMARY_SKILL:
  381. return bonus->val * 1000;
  382. case BonusType::SURRENDER_DISCOUNT:
  383. return 0; // irrelevant in gameplay
  384. case BonusType::WATER_WALKING:
  385. return 5000;
  386. case BonusType::FREE_SHIP_BOARDING:
  387. return 10000;
  388. case BonusType::WHIRLPOOL_PROTECTION:
  389. return 5000;
  390. case BonusType::FLYING_MOVEMENT:
  391. return 20000;
  392. case BonusType::UNDEAD_RAISE_PERCENTAGE:
  393. return bonus->val * 400;
  394. case BonusType::GENERATE_RESOURCE:
  395. return bonus->val * LIBRARY->objh->resVals.at(bonus->subtype.as<GameResID>().getNum()) * 10;
  396. case BonusType::SPELL_DURATION:
  397. return bonus->val * 200;
  398. case BonusType::MAGIC_RESISTANCE:
  399. return bonus->val * 400;
  400. case BonusType::PERCENTAGE_DAMAGE_BOOST:
  401. if (bonus->subtype == BonusCustomSubtype::damageTypeRanged)
  402. return bonus->val * 200;
  403. if (bonus->subtype == BonusCustomSubtype::damageTypeMelee)
  404. return bonus->val * 500;
  405. return 0;
  406. case BonusType::CREATURE_GROWTH:
  407. return (1+bonus->subtype.getNum()) * bonus->val * 400;
  408. case BonusType::MANA_PERCENTAGE_REGENERATION:
  409. return bonus->val * 150;
  410. case BonusType::MANA_REGENERATION:
  411. return bonus->val * 500;
  412. case BonusType::SPELLS_OF_SCHOOL:
  413. return 20000;
  414. case BonusType::SPELLS_OF_LEVEL:
  415. return bonus->subtype.getNum() * 6000;
  416. case BonusType::SPELL_DAMAGE:
  417. return bonus->val * 120;
  418. case BonusType::SIGHT_RADIUS:
  419. return bonus->val * 1000;
  420. case BonusType::LEARN_BATTLE_SPELL_CHANCE:
  421. return 0; // irrelevant in gameplay
  422. case BonusType::STACK_HEALTH:
  423. return bonus->val * 5000;
  424. case BonusType::NO_DISTANCE_PENALTY:
  425. return 10000;
  426. case BonusType::NO_WALL_PENALTY:
  427. return 5000;
  428. }
  429. return 0;
  430. // Additional bonuses to consider from H3 artifacts:
  431. // MIND_IMMUNITY
  432. // BLOCK_MAGIC_ABOVE
  433. // SPELL_IMMUNITY
  434. // NEGATE_ALL_NATURAL_IMMUNITIES
  435. // SPELL_RESISTANCE_AURA
  436. // SPELL
  437. // BATTLE_NO_FLEEING
  438. // BLOCK_ALL_MAGIC
  439. // NONEVIL_ALIGNMENT_MIX
  440. // OPENING_BATTLE_SPELL
  441. // IMPROVED_NECROMANCY
  442. // HP_REGENERATION
  443. // CREATURE_GROWTH_PERCENT
  444. // LEVEL_SPELL_IMMUNITY
  445. // FREE_SHOOTING
  446. // FULL_MANA_REGENERATION
  447. }
  448. int32_t getArtifactBonusScore(const std::shared_ptr<Bonus> & bonus)
  449. {
  450. if (bonus->propagator && bonus->propagator->getPropagatorType() == BonusNodeType::BATTLE_WIDE)
  451. {
  452. if (bonus->limiter)
  453. {
  454. // assume that this is battle wide / other side propagator+limiter -> invert value
  455. return -getArtifactBonusScoreImpl(bonus);
  456. }
  457. else
  458. {
  459. return 0; // TODO? How to consider battle-wide bonuses that affect everyone?
  460. }
  461. }
  462. else
  463. {
  464. return getArtifactBonusScoreImpl(bonus);
  465. }
  466. }
  467. int64_t getPotentialArtifactScore(const CArtifact * type)
  468. {
  469. int64_t totalScore = 0;
  470. for (const auto & bonus : type->getExportedBonusList())
  471. totalScore += getArtifactBonusScore(bonus);
  472. if (type->hasParts())
  473. {
  474. for (const auto & part : type->getConstituents())
  475. {
  476. for (const auto & bonus : part->getExportedBonusList())
  477. totalScore += getArtifactBonusScore(bonus);
  478. }
  479. }
  480. int64_t finalScore = std::max<int64_t>(type->getPrice() / 5, totalScore );
  481. return finalScore;
  482. }
  483. int64_t getArtifactScoreForHero(const CGHeroInstance * hero, const CArtifactInstance * artifact)
  484. {
  485. if (artifact->isScroll())
  486. {
  487. auto spellID = artifact->getScrollSpellID();
  488. auto spell = spellID.toEntity(LIBRARY);
  489. if (hero->getSpellsInSpellbook().count(spellID))
  490. return 0;
  491. else
  492. return spell->getLevel() * 100;
  493. }
  494. const CArtifact * type = artifact->getType();
  495. int64_t totalScore = 0;
  496. if (type->getId() == ArtifactID::SPELLBOOK)
  497. return 0;
  498. for (const auto & bonus : type->getExportedBonusList())
  499. totalScore += getArtifactBonusRelevance(hero, bonus) * getArtifactBonusScore(bonus);
  500. if (type->hasParts())
  501. {
  502. for (const auto & part : type->getConstituents())
  503. {
  504. for (const auto & bonus : part->getExportedBonusList())
  505. totalScore += getArtifactBonusRelevance(hero, bonus) * getArtifactBonusScore(bonus);
  506. }
  507. }
  508. return totalScore;
  509. }
  510. bool isWeeklyRevisitable(const PlayerColor & playerID, const CGObjectInstance * obj)
  511. {
  512. if(!obj)
  513. return false;
  514. //TODO: allow polling of remaining creatures in dwelling
  515. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  516. return rewardable->configuration.getResetDuration() == 7;
  517. if(dynamic_cast<const CGDwelling *>(obj))
  518. return true;
  519. switch(obj->ID)
  520. {
  521. case Obj::HILL_FORT:
  522. return true;
  523. case Obj::BORDER_GATE:
  524. case Obj::BORDERGUARD:
  525. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(playerID); //FIXME: they could be revisited sooner than in a week
  526. }
  527. return false;
  528. }
  529. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  530. {
  531. auto end = std::chrono::high_resolution_clock::now();
  532. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  533. }
  534. int getDuplicatingSlots(const CArmedInstance * army)
  535. {
  536. int duplicatingSlots = 0;
  537. for(const auto & stack : army->Slots())
  538. {
  539. if(stack.second->getCreature() && army->getSlotFor(stack.second->getCreature()) != stack.first)
  540. duplicatingSlots++;
  541. }
  542. return duplicatingSlots;
  543. }
  544. // todo: move to obj manager
  545. bool shouldVisit(const Nullkiller * aiNk, const CGHeroInstance * hero, const CGObjectInstance * obj)
  546. {
  547. auto relations = aiNk->cc->getPlayerRelations(obj->tempOwner, hero->tempOwner);
  548. switch(obj->ID)
  549. {
  550. case Obj::TOWN:
  551. case Obj::HERO: //never visit our heroes at random
  552. return relations == PlayerRelations::ENEMIES; //do not visit our towns at random
  553. case Obj::BORDER_GATE:
  554. {
  555. for(auto q : aiNk->cc->getMyQuests())
  556. {
  557. if(q.obj == obj->id)
  558. {
  559. return false; // do not visit guards or gates when wandering
  560. }
  561. }
  562. return true; //we don't have this quest yet
  563. }
  564. case Obj::BORDERGUARD: //open borderguard if possible
  565. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(aiNk->playerID);
  566. case Obj::SEER_HUT:
  567. {
  568. for(auto q : aiNk->cc->getMyQuests())
  569. {
  570. if(q.obj == obj->id)
  571. {
  572. if(q.getQuest(aiNk->cc.get())->checkQuest(hero))
  573. return true; //we completed the quest
  574. else
  575. return false; //we can't complete this quest
  576. }
  577. }
  578. return true; //we don't have this quest yet
  579. }
  580. case Obj::CREATURE_GENERATOR1:
  581. {
  582. if(relations == PlayerRelations::ENEMIES)
  583. return true; //flag just in case
  584. if(relations == PlayerRelations::ALLIES)
  585. return false;
  586. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  587. auto duplicatingSlotsCount = getDuplicatingSlots(hero);
  588. for(auto level : d->creatures)
  589. {
  590. for(auto c : level.second)
  591. {
  592. if(level.first
  593. && (hero->getSlotFor(CreatureID(c)) != SlotID() || duplicatingSlotsCount > 0)
  594. && aiNk->cc->getResourceAmount().canAfford(c.toCreature()->getFullRecruitCost()))
  595. {
  596. return true;
  597. }
  598. }
  599. }
  600. return false;
  601. }
  602. case Obj::HILL_FORT:
  603. {
  604. for(const auto & slot : hero->Slots())
  605. {
  606. if(slot.second->getType()->hasUpgrades())
  607. return true; //TODO: check price?
  608. }
  609. return false;
  610. }
  611. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  612. case Obj::MONOLITH_ONE_WAY_EXIT:
  613. case Obj::MONOLITH_TWO_WAY:
  614. case Obj::WHIRLPOOL:
  615. return false;
  616. case Obj::SCHOOL_OF_MAGIC:
  617. case Obj::SCHOOL_OF_WAR:
  618. {
  619. if(aiNk->getFreeGold() < 1000)
  620. return false;
  621. break;
  622. }
  623. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  624. if(hero->level < 10)
  625. return false;
  626. break;
  627. case Obj::TREE_OF_KNOWLEDGE:
  628. {
  629. if(aiNk->heroManager->getHeroRoleOrDefaultInefficient(hero) == HeroRole::SCOUT)
  630. return false;
  631. TResources myRes = aiNk->getFreeResources();
  632. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  633. return false;
  634. break;
  635. }
  636. case Obj::MAGIC_WELL:
  637. return hero->mana < hero->manaLimit();
  638. case Obj::PRISON:
  639. return !aiNk->heroManager->heroCapReached();
  640. case Obj::TAVERN:
  641. case Obj::EYE_OF_MAGI:
  642. case Obj::BOAT:
  643. case Obj::SIGN:
  644. return false;
  645. }
  646. if(obj->wasVisited(hero))
  647. return false;
  648. auto rewardable = dynamic_cast<const Rewardable::Interface *>(obj);
  649. if(rewardable && rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT).empty())
  650. {
  651. return false;
  652. }
  653. return true;
  654. }
  655. bool townHasFreeTavern(const CGTownInstance * town)
  656. {
  657. if(!town->hasBuilt(BuildingID::TAVERN)) return false;
  658. if(!town->getVisitingHero()) return true;
  659. bool canMoveVisitingHeroToGarrison = !town->getUpperArmy()->stacksCount();
  660. return canMoveVisitingHeroToGarrison;
  661. }
  662. uint64_t getHeroArmyStrengthWithCommander(const CGHeroInstance * hero, const CCreatureSet * heroArmy, int fortLevel)
  663. {
  664. auto armyStrength = heroArmy->getArmyStrength(fortLevel);
  665. if(hero && hero->getCommander() && hero->getCommander()->alive)
  666. {
  667. armyStrength += 100 * hero->getCommander()->level;
  668. }
  669. return armyStrength;
  670. }
  671. }