Actors.cpp 12 KB

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