AIUtility.cpp 20 KB

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