Actors.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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/mapping/CMap.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "Actions/BuyArmyAction.h"
  18. CCreatureSet emptyArmy;
  19. bool HeroExchangeArmy::needsLastStack() const
  20. {
  21. return true;
  22. }
  23. std::shared_ptr<SpecialAction> HeroExchangeArmy::getActorAction() const
  24. {
  25. std::shared_ptr<SpecialAction> result;
  26. if(requireBuyArmy)
  27. {
  28. result.reset(new AIPathfinding::BuyArmyAction());
  29. }
  30. return result;
  31. }
  32. ChainActor::ChainActor(const CGHeroInstance * hero, HeroRole heroRole, uint64_t chainMask)
  33. :hero(hero), heroRole(heroRole), isMovable(true), chainMask(chainMask), creatureSet(hero),
  34. baseActor(this), carrierParent(nullptr), otherParent(nullptr), actorExchangeCount(1), armyCost(), actorAction()
  35. {
  36. initialPosition = hero->visitablePos();
  37. layer = hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND;
  38. initialMovement = hero->movement;
  39. initialTurn = 0;
  40. armyValue = hero->getArmyStrength();
  41. heroFightingStrength = hero->getFightingStrength();
  42. tiCache.reset(new TurnInfo(hero));
  43. }
  44. ChainActor::ChainActor(const ChainActor * carrier, const ChainActor * other, const CCreatureSet * heroArmy)
  45. :hero(carrier->hero), tiCache(carrier->tiCache), 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 = heroArmy->getArmyStrength();
  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 AI_TRACE_LEVEL > 0
  63. if(!hero)
  64. throw std::logic_error("Asking movement points for static actor");
  65. #endif
  66. return hero->maxMovePointsCached(layer, tiCache.get());
  67. }
  68. std::string ChainActor::toString() const
  69. {
  70. return hero->name;
  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. tiCache = base->tiCache;
  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. namespace vstd
  144. {
  145. template <class M, class Key, class F>
  146. typename M::mapped_type & getOrCompute(M &m, Key const& k, F f)
  147. {
  148. typedef typename M::mapped_type V;
  149. std::pair<typename M::iterator, bool> r = m.insert(typename M::value_type(k, V()));
  150. V &v = r.first->second;
  151. if(r.second)
  152. f(v);
  153. return v;
  154. }
  155. }
  156. ExchangeResult HeroActor::tryExchangeNoLock(const ChainActor * specialActor, const ChainActor * other) const
  157. {
  158. const ChainActor * otherBase = other->baseActor;
  159. ExchangeResult result = exchangeMap->tryExchangeNoLock(otherBase);
  160. if(!result.actor || !result.lockAcquired) return result;
  161. if(specialActor == this)
  162. return result;
  163. int index = vstd::find_pos_if(specialActors, [specialActor](const ChainActor & actor) -> bool
  164. {
  165. return &actor == specialActor;
  166. });
  167. result.actor = &(dynamic_cast<HeroActor *>(result.actor)->specialActors[index]);
  168. return result;
  169. }
  170. HeroExchangeMap::HeroExchangeMap(const HeroActor * actor, const Nullkiller * ai)
  171. :actor(actor), ai(ai), sync()
  172. {
  173. }
  174. HeroExchangeMap::~HeroExchangeMap()
  175. {
  176. for(auto & exchange : exchangeMap)
  177. {
  178. if(!exchange.second) continue;
  179. delete exchange.second->creatureSet;
  180. }
  181. for(auto & exchange : exchangeMap)
  182. {
  183. if(!exchange.second) continue;
  184. delete exchange.second;
  185. }
  186. exchangeMap.clear();
  187. }
  188. ExchangeResult HeroExchangeMap::tryExchangeNoLock(const ChainActor * other)
  189. {
  190. ExchangeResult result;
  191. {
  192. boost::shared_lock<boost::shared_mutex> lock(sync, boost::try_to_lock);
  193. if(!lock.owns_lock())
  194. {
  195. result.lockAcquired = false;
  196. return result;
  197. }
  198. auto position = exchangeMap.find(other);
  199. if(position != exchangeMap.end())
  200. {
  201. result.actor = position->second;
  202. return result;
  203. }
  204. }
  205. {
  206. boost::unique_lock<boost::shared_mutex> uniqueLock(sync, boost::try_to_lock);
  207. if(!uniqueLock.owns_lock())
  208. {
  209. result.lockAcquired = false;
  210. return result;
  211. }
  212. auto inserted = exchangeMap.insert(std::pair<const ChainActor *, HeroActor *>(other, nullptr));
  213. if(!inserted.second)
  214. {
  215. result.actor = inserted.first->second;
  216. return result; // already inserted
  217. }
  218. auto differentMasks = (actor->chainMask & other->chainMask) == 0;
  219. if(!differentMasks) return result;
  220. TResources resources = ai->cb->getResourceAmount();
  221. if(!resources.canAfford(actor->armyCost + other->armyCost))
  222. {
  223. #if PATHFINDER_TRACE_LEVEL >= 2
  224. logAi->trace(
  225. "Can not afford exchange because of total cost %s but we have %s",
  226. (actor->armyCost + other->armyCost).toString(),
  227. resources.toString());
  228. #endif
  229. return result;
  230. }
  231. if(other->isMovable && other->armyValue <= actor->armyValue / 10 && other->armyValue < MIN_ARMY_STRENGTH_FOR_CHAIN)
  232. return result;
  233. TResources availableResources = resources - actor->armyCost - other->armyCost;
  234. HeroExchangeArmy * upgradedInitialArmy = tryUpgrade(actor->creatureSet, other->getActorObject(), availableResources);
  235. HeroExchangeArmy * newArmy;
  236. if(other->creatureSet->Slots().size())
  237. {
  238. if(upgradedInitialArmy)
  239. {
  240. newArmy = pickBestCreatures(upgradedInitialArmy, other->creatureSet);
  241. newArmy->armyCost = upgradedInitialArmy->armyCost;
  242. newArmy->requireBuyArmy = upgradedInitialArmy->requireBuyArmy;
  243. delete upgradedInitialArmy;
  244. }
  245. else
  246. {
  247. newArmy = pickBestCreatures(actor->creatureSet, other->creatureSet);
  248. }
  249. }
  250. else
  251. {
  252. newArmy = upgradedInitialArmy;
  253. }
  254. if(!newArmy) return result;
  255. auto reinforcement = newArmy->getArmyStrength() - actor->creatureSet->getArmyStrength();
  256. #if PATHFINDER_TRACE_LEVEL >= 2
  257. logAi->trace(
  258. "Exchange %s->%s reinforcement: %d, %f%%",
  259. actor->toString(),
  260. other->toString(),
  261. reinforcement,
  262. 100.0f * reinforcement / actor->armyValue);
  263. #endif
  264. if(reinforcement <= actor->armyValue / 10 && reinforcement < MIN_ARMY_STRENGTH_FOR_CHAIN)
  265. {
  266. delete newArmy;
  267. return result;
  268. }
  269. HeroActor * exchanged = new HeroActor(actor, other, newArmy, ai);
  270. exchanged->armyCost += newArmy->armyCost;
  271. result.actor = exchanged;
  272. exchangeMap[other] = exchanged;
  273. return result;
  274. }
  275. }
  276. HeroExchangeArmy * HeroExchangeMap::tryUpgrade(
  277. const CCreatureSet * army,
  278. const CGObjectInstance * upgrader,
  279. TResources resources) const
  280. {
  281. HeroExchangeArmy * target = new HeroExchangeArmy();
  282. auto upgradeInfo = ai->armyManager->calculateCreaturesUpgrade(army, upgrader, resources);
  283. if(upgradeInfo.upgradeValue)
  284. {
  285. for(auto & slotInfo : upgradeInfo.resultingArmy)
  286. {
  287. auto targetSlot = target->getFreeSlot();
  288. target->addToSlot(targetSlot, slotInfo.creature->idNumber, TQuantity(slotInfo.count));
  289. }
  290. resources -= upgradeInfo.upgradeCost;
  291. target->armyCost += upgradeInfo.upgradeCost;
  292. }
  293. else
  294. {
  295. for(auto slot : army->Slots())
  296. {
  297. auto targetSlot = target->getSlotFor(slot.second->getCreatureID());
  298. target->addToSlot(targetSlot, slot.second->getCreatureID(), slot.second->count);
  299. }
  300. }
  301. if(upgrader->ID == Obj::TOWN)
  302. {
  303. auto buyArmy = ai->armyManager->getArmyAvailableToBuy(target, ai->cb->getTown(upgrader->id), resources);
  304. for(auto creatureToBuy : buyArmy)
  305. {
  306. auto targetSlot = target->getSlotFor(creatureToBuy.cre);
  307. target->addToSlot(targetSlot, creatureToBuy.creID, creatureToBuy.count);
  308. target->armyCost += creatureToBuy.cre->cost * creatureToBuy.count;
  309. target->requireBuyArmy = true;
  310. }
  311. }
  312. if(target->getArmyStrength() <= army->getArmyStrength())
  313. {
  314. delete target;
  315. return nullptr;
  316. }
  317. return target;
  318. }
  319. HeroExchangeArmy * HeroExchangeMap::pickBestCreatures(const CCreatureSet * army1, const CCreatureSet * army2) const
  320. {
  321. HeroExchangeArmy * target = new HeroExchangeArmy();
  322. auto bestArmy = ai->armyManager->getBestArmy(actor->hero, army1, army2);
  323. for(auto & slotInfo : bestArmy)
  324. {
  325. auto targetSlot = target->getFreeSlot();
  326. target->addToSlot(targetSlot, slotInfo.creature->idNumber, TQuantity(slotInfo.count));
  327. }
  328. return target;
  329. }
  330. HillFortActor::HillFortActor(const CGObjectInstance * hillFort, uint64_t chainMask)
  331. :ObjectActor(hillFort, &emptyArmy, chainMask, 0)
  332. {
  333. }
  334. DwellingActor::DwellingActor(const CGDwelling * dwelling, uint64_t chainMask, bool waitForGrowth, int dayOfWeek)
  335. : ObjectActor(
  336. dwelling,
  337. getDwellingCreatures(dwelling, waitForGrowth),
  338. chainMask,
  339. getInitialTurn(waitForGrowth, dayOfWeek)),
  340. dwelling(dwelling)
  341. {
  342. for(auto & slot : creatureSet->Slots())
  343. {
  344. armyCost += slot.second->getCreatureID().toCreature()->cost * slot.second->count;
  345. }
  346. }
  347. DwellingActor::~DwellingActor()
  348. {
  349. delete creatureSet;
  350. }
  351. int DwellingActor::getInitialTurn(bool waitForGrowth, int dayOfWeek)
  352. {
  353. if(!waitForGrowth)
  354. return 0;
  355. return 8 - dayOfWeek;
  356. }
  357. std::string DwellingActor::toString() const
  358. {
  359. return dwelling->typeName + dwelling->visitablePos().toString();
  360. }
  361. CCreatureSet * DwellingActor::getDwellingCreatures(const CGDwelling * dwelling, bool waitForGrowth)
  362. {
  363. CCreatureSet * dwellingCreatures = new CCreatureSet();
  364. for(auto & creatureInfo : dwelling->creatures)
  365. {
  366. if(!creatureInfo.second.size())
  367. continue;
  368. auto creature = creatureInfo.second.back().toCreature();
  369. dwellingCreatures->addToSlot(
  370. dwellingCreatures->getSlotFor(creature),
  371. creature->idNumber,
  372. TQuantity(creatureInfo.first));
  373. }
  374. return dwellingCreatures;
  375. }
  376. TownGarrisonActor::TownGarrisonActor(const CGTownInstance * town, uint64_t chainMask)
  377. :ObjectActor(town, town->getUpperArmy(), chainMask, 0), town(town)
  378. {
  379. }
  380. std::string TownGarrisonActor::toString() const
  381. {
  382. return town->name;
  383. }