Actors.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. * AINodeStorage.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 "Actors.h"
  12. #include "../AIGateway.h"
  13. #include "../Engine/Nullkiller.h"
  14. #include "../../../CCallback.h"
  15. #include "../../../lib/mapObjects/MapObjects.h"
  16. #include "../../../lib/mapping/CMapDefines.h"
  17. #include "../../../lib/pathfinder/TurnInfo.h"
  18. #include "Actions/BuyArmyAction.h"
  19. using namespace NKAI;
  20. const CCreatureSet emptyArmy;
  21. bool HeroExchangeArmy::needsLastStack() const
  22. {
  23. return true;
  24. }
  25. std::shared_ptr<SpecialAction> HeroExchangeArmy::getActorAction() const
  26. {
  27. std::shared_ptr<SpecialAction> result;
  28. if(requireBuyArmy)
  29. {
  30. result.reset(new AIPathfinding::BuyArmyAction());
  31. }
  32. return result;
  33. }
  34. ChainActor::ChainActor(const CGHeroInstance * hero, HeroRole heroRole, uint64_t chainMask)
  35. :hero(hero), heroRole(heroRole), isMovable(true), chainMask(chainMask), creatureSet(hero),
  36. baseActor(this), carrierParent(nullptr), otherParent(nullptr), actorExchangeCount(1), armyCost(), actorAction()
  37. {
  38. initialPosition = hero->visitablePos();
  39. layer = hero->boat ? hero->boat->layer : EPathfindingLayer::LAND;
  40. initialMovement = hero->movementPointsRemaining();
  41. initialTurn = 0;
  42. armyValue = getHeroArmyStrengthWithCommander(hero, hero);
  43. heroFightingStrength = hero->getHeroStrength();
  44. }
  45. ChainActor::ChainActor(const ChainActor * carrier, const ChainActor * other, const CCreatureSet * heroArmy)
  46. :hero(carrier->hero), heroRole(carrier->heroRole), isMovable(true), creatureSet(heroArmy), chainMask(carrier->chainMask | other->chainMask),
  47. baseActor(this), carrierParent(carrier), otherParent(other), heroFightingStrength(carrier->heroFightingStrength),
  48. actorExchangeCount(carrier->actorExchangeCount + other->actorExchangeCount), armyCost(carrier->armyCost + other->armyCost), actorAction()
  49. {
  50. armyValue = getHeroArmyStrengthWithCommander(hero, heroArmy);
  51. }
  52. ChainActor::ChainActor(const CGObjectInstance * obj, const CCreatureSet * creatureSet, uint64_t chainMask, int initialTurn)
  53. :hero(nullptr), heroRole(HeroRole::MAIN), isMovable(false), creatureSet(creatureSet), chainMask(chainMask),
  54. baseActor(this), carrierParent(nullptr), otherParent(nullptr), initialTurn(initialTurn), initialMovement(0),
  55. heroFightingStrength(0), actorExchangeCount(1), armyCost(), actorAction()
  56. {
  57. initialPosition = obj->visitablePos();
  58. layer = EPathfindingLayer::LAND;
  59. armyValue = creatureSet->getArmyStrength();
  60. }
  61. int ChainActor::maxMovePoints(CGPathNode::ELayer layer)
  62. {
  63. #if NKAI_TRACE_LEVEL > 0
  64. if(!hero)
  65. throw std::logic_error("Asking movement points for static actor");
  66. #endif
  67. return hero->movementPointsLimit(layer);
  68. }
  69. std::string ChainActor::toString() const
  70. {
  71. return hero->getNameTranslated();
  72. }
  73. ObjectActor::ObjectActor(const CGObjectInstance * obj, const CCreatureSet * army, uint64_t chainMask, int initialTurn)
  74. :ChainActor(obj, army, chainMask, initialTurn), object(obj)
  75. {
  76. }
  77. const CGObjectInstance * ObjectActor::getActorObject() const
  78. {
  79. return object;
  80. }
  81. std::string ObjectActor::toString() const
  82. {
  83. return object->getObjectName() + " at " + object->visitablePos().toString();
  84. }
  85. HeroActor::HeroActor(const CGHeroInstance * hero, HeroRole heroRole, uint64_t chainMask, const Nullkiller * ai)
  86. :ChainActor(hero, heroRole, chainMask)
  87. {
  88. exchangeMap.reset(new HeroExchangeMap(this, ai));
  89. setupSpecialActors();
  90. }
  91. HeroActor::HeroActor(
  92. const ChainActor * carrier,
  93. const ChainActor * other,
  94. const HeroExchangeArmy * army,
  95. const Nullkiller * ai)
  96. :ChainActor(carrier, other, army)
  97. {
  98. exchangeMap.reset(new HeroExchangeMap(this, ai));
  99. armyCost += army->armyCost;
  100. actorAction = army->getActorAction();
  101. setupSpecialActors();
  102. }
  103. void ChainActor::setBaseActor(HeroActor * base)
  104. {
  105. baseActor = base;
  106. hero = base->hero;
  107. heroRole = base->heroRole;
  108. layer = base->layer;
  109. initialMovement = base->initialMovement;
  110. initialTurn = base->initialTurn;
  111. armyValue = base->armyValue;
  112. chainMask = base->chainMask;
  113. creatureSet = base->creatureSet;
  114. isMovable = base->isMovable;
  115. heroFightingStrength = base->heroFightingStrength;
  116. armyCost = base->armyCost;
  117. actorAction = base->actorAction;
  118. actorExchangeCount = base->actorExchangeCount;
  119. }
  120. void HeroActor::setupSpecialActors()
  121. {
  122. auto allActors = std::vector<ChainActor *>{this};
  123. for(ChainActor & specialActor : specialActors)
  124. {
  125. specialActor.setBaseActor(this);
  126. allActors.push_back(&specialActor);
  127. }
  128. for(int i = 0; i <= SPECIAL_ACTORS_COUNT; i++)
  129. {
  130. ChainActor * actor = allActors[i];
  131. actor->allowBattle = (i & 1) > 0;
  132. actor->allowSpellCast = (i & 2) > 0;
  133. actor->allowUseResources = (i & 4) > 0;
  134. actor->battleActor = allActors[i | 1];
  135. actor->castActor = allActors[i | 2];
  136. actor->resourceActor = allActors[i | 4];
  137. }
  138. }
  139. ExchangeResult ChainActor::tryExchangeNoLock(const ChainActor * specialActor, const ChainActor * other) const
  140. {
  141. if(!isMovable) return ExchangeResult();
  142. return baseActor->tryExchangeNoLock(specialActor, other);
  143. }
  144. ExchangeResult HeroActor::tryExchangeNoLock(const ChainActor * specialActor, const ChainActor * other) const
  145. {
  146. const ChainActor * otherBase = other->baseActor;
  147. ExchangeResult result = exchangeMap->tryExchangeNoLock(otherBase);
  148. if(!result.actor || !result.lockAcquired) return result;
  149. if(specialActor == this)
  150. return result;
  151. int index = vstd::find_pos_if(specialActors, [specialActor](const ChainActor & actor) -> bool
  152. {
  153. return &actor == specialActor;
  154. });
  155. result.actor = &(dynamic_cast<HeroActor *>(result.actor)->specialActors.at(index));
  156. return result;
  157. }
  158. HeroExchangeMap::HeroExchangeMap(const HeroActor * actor, const Nullkiller * ai)
  159. :actor(actor), ai(ai), sync()
  160. {
  161. }
  162. HeroExchangeMap::~HeroExchangeMap()
  163. {
  164. for(auto & exchange : exchangeMap)
  165. {
  166. if(!exchange.second) continue;
  167. delete exchange.second->creatureSet;
  168. }
  169. for(auto & exchange : exchangeMap)
  170. {
  171. if(!exchange.second) continue;
  172. delete exchange.second;
  173. }
  174. exchangeMap.clear();
  175. }
  176. ExchangeResult HeroExchangeMap::tryExchangeNoLock(const ChainActor * other)
  177. {
  178. ExchangeResult result;
  179. {
  180. std::shared_lock lock(sync, std::try_to_lock);
  181. if(!lock.owns_lock())
  182. {
  183. result.lockAcquired = false;
  184. return result;
  185. }
  186. auto position = exchangeMap.find(other);
  187. if(position != exchangeMap.end())
  188. {
  189. result.actor = position->second;
  190. return result;
  191. }
  192. }
  193. {
  194. std::unique_lock uniqueLock(sync, std::try_to_lock);
  195. if(!uniqueLock.owns_lock())
  196. {
  197. result.lockAcquired = false;
  198. return result;
  199. }
  200. auto inserted = exchangeMap.insert(std::pair<const ChainActor *, HeroActor *>(other, nullptr));
  201. if(!inserted.second)
  202. {
  203. result.actor = inserted.first->second;
  204. return result; // already inserted
  205. }
  206. auto differentMasks = (actor->chainMask & other->chainMask) == 0;
  207. if(!differentMasks) return result;
  208. if(actor->allowSpellCast || other->allowSpellCast)
  209. return result;
  210. TResources resources = ai->cb->getResourceAmount();
  211. if(!resources.canAfford(actor->armyCost + other->armyCost))
  212. {
  213. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  214. logAi->trace(
  215. "Can not afford exchange because of total cost %s but we have %s",
  216. (actor->armyCost + other->armyCost).toString(),
  217. resources.toString());
  218. #endif
  219. return result;
  220. }
  221. if(other->isMovable && other->armyValue <= actor->armyValue / 10 && other->armyValue < MIN_ARMY_STRENGTH_FOR_CHAIN)
  222. return result;
  223. TResources availableResources = resources - actor->armyCost - other->armyCost;
  224. HeroExchangeArmy * upgradedInitialArmy = tryUpgrade(actor->creatureSet, other->getActorObject(), availableResources);
  225. HeroExchangeArmy * newArmy;
  226. if(other->creatureSet->Slots().size())
  227. {
  228. if(upgradedInitialArmy)
  229. {
  230. newArmy = pickBestCreatures(upgradedInitialArmy, other->creatureSet);
  231. newArmy->armyCost = upgradedInitialArmy->armyCost;
  232. newArmy->requireBuyArmy = upgradedInitialArmy->requireBuyArmy;
  233. delete upgradedInitialArmy;
  234. }
  235. else
  236. {
  237. newArmy = pickBestCreatures(actor->creatureSet, other->creatureSet);
  238. }
  239. }
  240. else
  241. {
  242. newArmy = upgradedInitialArmy;
  243. }
  244. if(!newArmy) return result;
  245. auto newArmyStrength = newArmy->getArmyStrength();
  246. auto oldArmyStrength = actor->creatureSet->getArmyStrength();
  247. if(newArmyStrength <= oldArmyStrength) return result;
  248. auto reinforcement = newArmyStrength - oldArmyStrength;
  249. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  250. logAi->trace(
  251. "Exchange %s->%s reinforcement: %d, %f%%",
  252. actor->toString(),
  253. other->toString(),
  254. reinforcement,
  255. 100.0f * reinforcement / actor->armyValue);
  256. #endif
  257. if(reinforcement <= actor->armyValue / 10 && reinforcement < MIN_ARMY_STRENGTH_FOR_CHAIN)
  258. {
  259. delete newArmy;
  260. return result;
  261. }
  262. auto * exchanged = new HeroActor(actor, other, newArmy, ai);
  263. exchanged->armyCost += newArmy->armyCost;
  264. result.actor = exchanged;
  265. exchangeMap[other] = exchanged;
  266. return result;
  267. }
  268. }
  269. HeroExchangeArmy * HeroExchangeMap::tryUpgrade(
  270. const CCreatureSet * army,
  271. const CGObjectInstance * upgrader,
  272. TResources resources) const
  273. {
  274. auto * target = new HeroExchangeArmy();
  275. auto upgradeInfo = ai->armyManager->calculateCreaturesUpgrade(army, upgrader, resources);
  276. if(upgradeInfo.upgradeValue)
  277. {
  278. for(auto & slotInfo : upgradeInfo.resultingArmy)
  279. {
  280. auto targetSlot = target->getFreeSlot();
  281. target->addToSlot(targetSlot, slotInfo.creature->getId(), TQuantity(slotInfo.count));
  282. }
  283. resources -= upgradeInfo.upgradeCost;
  284. target->armyCost += upgradeInfo.upgradeCost;
  285. }
  286. else
  287. {
  288. for(const auto & slot : army->Slots())
  289. {
  290. const auto & targetSlot = target->getSlotFor(slot.second->getCreatureID());
  291. target->addToSlot(targetSlot, slot.second->getCreatureID(), slot.second->count);
  292. }
  293. }
  294. if(upgrader->ID == Obj::TOWN)
  295. {
  296. auto buyArmy = ai->armyManager->getArmyAvailableToBuy(target, ai->cb->getTown(upgrader->id), resources);
  297. for(auto & creatureToBuy : buyArmy)
  298. {
  299. auto targetSlot = target->getSlotFor(creatureToBuy.creID.toCreature());
  300. if (targetSlot.validSlot())
  301. {
  302. target->addToSlot(targetSlot, creatureToBuy.creID, creatureToBuy.count);
  303. target->armyCost += creatureToBuy.creID.toCreature()->getFullRecruitCost() * creatureToBuy.count;
  304. target->requireBuyArmy = true;
  305. }
  306. }
  307. }
  308. if(target->getArmyStrength() <= army->getArmyStrength())
  309. {
  310. delete target;
  311. return nullptr;
  312. }
  313. return target;
  314. }
  315. HeroExchangeArmy * HeroExchangeMap::pickBestCreatures(const CCreatureSet * army1, const CCreatureSet * army2) const
  316. {
  317. auto * target = new HeroExchangeArmy();
  318. auto bestArmy = ai->armyManager->getBestArmy(actor->hero, army1, army2, ai->cb->getTile(actor->hero->visitablePos())->getTerrainID());
  319. for(auto & slotInfo : bestArmy)
  320. {
  321. auto targetSlot = target->getFreeSlot();
  322. target->addToSlot(targetSlot, slotInfo.creature->getId(), TQuantity(slotInfo.count));
  323. }
  324. return target;
  325. }
  326. HillFortActor::HillFortActor(const CGObjectInstance * hillFort, uint64_t chainMask)
  327. :ObjectActor(hillFort, &emptyArmy, chainMask, 0)
  328. {
  329. }
  330. DwellingActor::DwellingActor(const CGDwelling * dwelling, uint64_t chainMask, bool waitForGrowth, int dayOfWeek)
  331. : ObjectActor(
  332. dwelling,
  333. getDwellingCreatures(dwelling, waitForGrowth),
  334. chainMask,
  335. getInitialTurn(waitForGrowth, dayOfWeek)),
  336. dwelling(dwelling)
  337. {
  338. for(auto & slot : creatureSet->Slots())
  339. {
  340. armyCost += slot.second->getCreatureID().toCreature()->getFullRecruitCost() * slot.second->count;
  341. }
  342. }
  343. DwellingActor::~DwellingActor()
  344. {
  345. delete creatureSet;
  346. }
  347. int DwellingActor::getInitialTurn(bool waitForGrowth, int dayOfWeek)
  348. {
  349. if(!waitForGrowth)
  350. return 0;
  351. return 8 - dayOfWeek;
  352. }
  353. std::string DwellingActor::toString() const
  354. {
  355. return dwelling->getTypeName() + dwelling->visitablePos().toString();
  356. }
  357. CCreatureSet * DwellingActor::getDwellingCreatures(const CGDwelling * dwelling, bool waitForGrowth)
  358. {
  359. auto * dwellingCreatures = new CCreatureSet();
  360. for(auto & creatureInfo : dwelling->creatures)
  361. {
  362. if(!creatureInfo.second.size())
  363. continue;
  364. auto creature = creatureInfo.second.back().toCreature();
  365. dwellingCreatures->addToSlot(
  366. dwellingCreatures->getSlotFor(creature),
  367. creature->getId(),
  368. TQuantity(creatureInfo.first));
  369. }
  370. return dwellingCreatures;
  371. }
  372. TownGarrisonActor::TownGarrisonActor(const CGTownInstance * town, uint64_t chainMask)
  373. :ObjectActor(town, town->getUpperArmy(), chainMask, 0), town(town)
  374. {
  375. }
  376. std::string TownGarrisonActor::toString() const
  377. {
  378. return town->getNameTranslated();
  379. }