CStack.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * CStack.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 "CStack.h"
  12. #include <vstd/RNG.h>
  13. #include <vcmi/ServerCallback.h>
  14. #include "CGeneralTextHandler.h"
  15. #include "battle/BattleInfo.h"
  16. #include "spells/CSpellHandler.h"
  17. #include "NetPacks.h"
  18. ///CStack
  19. CStack::CStack(const CStackInstance * Base, PlayerColor O, int I, ui8 Side, SlotID S)
  20. : CBonusSystemNode(STACK_BATTLE),
  21. CUnitState(),
  22. base(Base),
  23. ID(I),
  24. type(Base->type),
  25. baseAmount(base->count),
  26. owner(O),
  27. slot(S),
  28. side(Side),
  29. initialPosition(),
  30. nativeTerrain()
  31. {
  32. health.init(); //???
  33. }
  34. CStack::CStack()
  35. : CBonusSystemNode(STACK_BATTLE),
  36. CUnitState(),
  37. nativeTerrain()
  38. {
  39. base = nullptr;
  40. type = nullptr;
  41. ID = -1;
  42. baseAmount = -1;
  43. owner = PlayerColor::NEUTRAL;
  44. slot = SlotID(255);
  45. side = 1;
  46. initialPosition = BattleHex();
  47. }
  48. CStack::CStack(const CStackBasicDescriptor * stack, PlayerColor O, int I, ui8 Side, SlotID S)
  49. : CBonusSystemNode(STACK_BATTLE),
  50. CUnitState(),
  51. base(nullptr),
  52. ID(I),
  53. type(stack->type),
  54. baseAmount(stack->count),
  55. owner(O),
  56. slot(S),
  57. side(Side),
  58. initialPosition()
  59. {
  60. health.init(); //???
  61. }
  62. const CCreature * CStack::getCreature() const
  63. {
  64. return type;
  65. }
  66. void CStack::localInit(BattleInfo * battleInfo)
  67. {
  68. battle = battleInfo;
  69. assert(type);
  70. exportBonuses();
  71. if(base) //stack originating from "real" stack in garrison -> attach to it
  72. {
  73. attachTo(const_cast<CStackInstance *>(base));
  74. }
  75. else //attach directly to obj to which stack belongs and creature type
  76. {
  77. CArmedInstance * army = battle->battleGetArmyObject(side);
  78. attachTo(army);
  79. attachTo(const_cast<CCreature *>(type));
  80. }
  81. nativeTerrain = type->getNativeTerrain(); //save nativeTerrain in the variable on the battle start to avoid dead lock
  82. CUnitState::localInit(this); //it causes execution of the CStack::isOnNativeTerrain where nativeTerrain will be considered
  83. position = initialPosition;
  84. }
  85. ui32 CStack::level() const
  86. {
  87. if(base)
  88. return base->getLevel(); //creature or commander
  89. else
  90. return std::max(1, (int)getCreature()->level); //war machine, clone etc
  91. }
  92. si32 CStack::magicResistance() const
  93. {
  94. si32 magicResistance = IBonusBearer::magicResistance();
  95. si32 auraBonus = 0;
  96. for(auto one : battle->battleAdjacentUnits(this))
  97. {
  98. if(one->unitOwner() == owner)
  99. vstd::amax(auraBonus, one->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  100. }
  101. magicResistance += auraBonus;
  102. vstd::amin(magicResistance, 100);
  103. return magicResistance;
  104. }
  105. BattleHex::EDir CStack::destShiftDir() const
  106. {
  107. if(doubleWide())
  108. {
  109. if(side == BattleSide::ATTACKER)
  110. return BattleHex::EDir::RIGHT;
  111. else
  112. return BattleHex::EDir::LEFT;
  113. }
  114. else
  115. {
  116. return BattleHex::EDir::NONE;
  117. }
  118. }
  119. std::vector<si32> CStack::activeSpells() const
  120. {
  121. std::vector<si32> ret;
  122. std::stringstream cachingStr;
  123. cachingStr << "!type_" << Bonus::NONE << "source_" << Bonus::SPELL_EFFECT;
  124. CSelector selector = Selector::sourceType()(Bonus::SPELL_EFFECT)
  125. .And(CSelector([](const Bonus * b)->bool
  126. {
  127. return b->type != Bonus::NONE;
  128. }));
  129. TConstBonusListPtr spellEffects = getBonuses(selector, Selector::all, cachingStr.str());
  130. for(const auto & it : *spellEffects)
  131. {
  132. if(!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  133. ret.push_back(it->sid);
  134. }
  135. return ret;
  136. }
  137. CStack::~CStack()
  138. {
  139. detachFromAll();
  140. }
  141. const CGHeroInstance * CStack::getMyHero() const
  142. {
  143. if(base)
  144. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  145. else //we are attached directly?
  146. for(const CBonusSystemNode * n : getParentNodes())
  147. if(n->getNodeType() == HERO)
  148. return dynamic_cast<const CGHeroInstance *>(n);
  149. return nullptr;
  150. }
  151. std::string CStack::nodeName() const
  152. {
  153. std::ostringstream oss;
  154. oss << owner.getStr();
  155. oss << " battle stack [" << ID << "]: " << getCount() << " of ";
  156. if(type)
  157. oss << type->namePl;
  158. else
  159. oss << "[UNDEFINED TYPE]";
  160. oss << " from slot " << slot;
  161. if(base && base->armyObj)
  162. oss << " of armyobj=" << base->armyObj->id.getNum();
  163. return oss.str();
  164. }
  165. void CStack::prepareAttacked(BattleStackAttacked & bsa, vstd::RNG & rand) const
  166. {
  167. auto newState = acquireState();
  168. prepareAttacked(bsa, rand, newState);
  169. }
  170. void CStack::prepareAttacked(BattleStackAttacked & bsa, vstd::RNG & rand, std::shared_ptr<battle::CUnitState> customState)
  171. {
  172. auto initialCount = customState->getCount();
  173. customState->damage(bsa.damageAmount);
  174. bsa.killedAmount = initialCount - customState->getCount();
  175. if(!customState->alive() && customState->isClone())
  176. {
  177. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  178. }
  179. else if(!customState->alive()) //stack killed
  180. {
  181. bsa.flags |= BattleStackAttacked::KILLED;
  182. auto resurrectValue = customState->valOfBonuses(Bonus::REBIRTH);
  183. if(resurrectValue > 0 && customState->canCast()) //there must be casts left
  184. {
  185. double resurrectFactor = resurrectValue / 100.0;
  186. auto baseAmount = customState->unitBaseAmount();
  187. double resurrectedRaw = baseAmount * resurrectFactor;
  188. int32_t resurrectedCount = static_cast<int32_t>(floor(resurrectedRaw));
  189. int32_t resurrectedAdd = static_cast<int32_t>(baseAmount - (resurrectedCount/resurrectFactor));
  190. auto rangeGen = rand.getInt64Range(0, 99);
  191. for(int32_t i = 0; i < resurrectedAdd; i++)
  192. {
  193. if(resurrectValue > rangeGen())
  194. resurrectedCount += 1;
  195. }
  196. if(customState->hasBonusOfType(Bonus::REBIRTH, 1))
  197. {
  198. // resurrect at least one Sacred Phoenix
  199. vstd::amax(resurrectedCount, 1);
  200. }
  201. if(resurrectedCount > 0)
  202. {
  203. customState->casts.use();
  204. bsa.flags |= BattleStackAttacked::REBIRTH;
  205. int64_t toHeal = customState->MaxHealth() * resurrectedCount;
  206. //TODO: add one-battle rebirth?
  207. customState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  208. customState->counterAttacks.use(customState->counterAttacks.available());
  209. }
  210. }
  211. }
  212. customState->save(bsa.newState.data);
  213. bsa.newState.healthDelta = -bsa.damageAmount;
  214. bsa.newState.id = customState->unitId();
  215. bsa.newState.operation = UnitChanges::EOperation::RESET_STATE;
  216. }
  217. std::vector<BattleHex> CStack::meleeAttackHexes(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPos, BattleHex defenderPos)
  218. {
  219. int mask = 0;
  220. std::vector<BattleHex> res;
  221. if (!attackerPos.isValid())
  222. attackerPos = attacker->getPosition();
  223. if (!defenderPos.isValid())
  224. defenderPos = defender->getPosition();
  225. BattleHex otherAttackerPos = attackerPos + (attacker->unitSide() == BattleSide::ATTACKER ? -1 : 1);
  226. BattleHex otherDefenderPos = defenderPos + (defender->unitSide() == BattleSide::ATTACKER ? -1 : 1);
  227. if(BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  228. {
  229. if((mask & 1) == 0)
  230. {
  231. mask |= 1;
  232. res.push_back(defenderPos);
  233. }
  234. }
  235. if (attacker->doubleWide() //back <=> front
  236. && BattleHex::mutualPosition(otherAttackerPos, defenderPos) >= 0)
  237. {
  238. if((mask & 1) == 0)
  239. {
  240. mask |= 1;
  241. res.push_back(defenderPos);
  242. }
  243. }
  244. if (defender->doubleWide()//front <=> back
  245. && BattleHex::mutualPosition(attackerPos, otherDefenderPos) >= 0)
  246. {
  247. if((mask & 2) == 0)
  248. {
  249. mask |= 2;
  250. res.push_back(otherDefenderPos);
  251. }
  252. }
  253. if (defender->doubleWide() && attacker->doubleWide()//back <=> back
  254. && BattleHex::mutualPosition(otherAttackerPos, otherDefenderPos) >= 0)
  255. {
  256. if((mask & 2) == 0)
  257. {
  258. mask |= 2;
  259. res.push_back(otherDefenderPos);
  260. }
  261. }
  262. return res;
  263. }
  264. bool CStack::isMeleeAttackPossible(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPos, BattleHex defenderPos)
  265. {
  266. return !meleeAttackHexes(attacker, defender, attackerPos, defenderPos).empty();
  267. }
  268. std::string CStack::getName() const
  269. {
  270. return (getCount() == 1) ? type->nameSing : type->namePl; //War machines can't use base
  271. }
  272. bool CStack::canBeHealed() const
  273. {
  274. return getFirstHPleft() < (int32_t)MaxHealth()
  275. && isValidTarget()
  276. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  277. }
  278. bool CStack::isOnNativeTerrain() const
  279. {
  280. //this code is called from CreatureTerrainLimiter::limit on battle start
  281. auto res = nativeTerrain == Terrain::ANY_TERRAIN || nativeTerrain == battle->getTerrainType();
  282. return res;
  283. }
  284. bool CStack::isOnTerrain(TTerrainId terrain) const
  285. {
  286. return battle->getTerrainType() == terrain;
  287. }
  288. const CCreature * CStack::unitType() const
  289. {
  290. return type;
  291. }
  292. int32_t CStack::unitBaseAmount() const
  293. {
  294. return baseAmount;
  295. }
  296. bool CStack::unitHasAmmoCart(const battle::Unit * unit) const
  297. {
  298. for(const CStack * st : battle->stacks)
  299. {
  300. if(battle->battleMatchOwner(st, unit, true) && st->getCreature()->idNumber == CreatureID::AMMO_CART)
  301. {
  302. return st->alive();
  303. }
  304. }
  305. //ammo cart works during creature bank battle while not on battlefield
  306. auto ownerHero = battle->battleGetOwnerHero(unit);
  307. if(ownerHero && ownerHero->artifactsWorn.find(ArtifactPosition::MACH2) != ownerHero->artifactsWorn.end())
  308. {
  309. if(battle->battleGetOwnerHero(unit)->artifactsWorn.at(ArtifactPosition::MACH2).artifact->artType->id == ArtifactID::AMMO_CART)
  310. {
  311. return true;
  312. }
  313. }
  314. return false; //will be always false if trying to examine enemy hero in "special battle"
  315. }
  316. PlayerColor CStack::unitEffectiveOwner(const battle::Unit * unit) const
  317. {
  318. return battle->battleGetOwner(unit);
  319. }
  320. uint32_t CStack::unitId() const
  321. {
  322. return ID;
  323. }
  324. ui8 CStack::unitSide() const
  325. {
  326. return side;
  327. }
  328. PlayerColor CStack::unitOwner() const
  329. {
  330. return owner;
  331. }
  332. SlotID CStack::unitSlot() const
  333. {
  334. return slot;
  335. }
  336. std::string CStack::getDescription() const
  337. {
  338. return nodeName();
  339. }
  340. void CStack::spendMana(ServerCallback * server, const int spellCost) const
  341. {
  342. if(spellCost != 1)
  343. logGlobal->warn("Unexpected spell cost %d for creature", spellCost);
  344. BattleSetStackProperty ssp;
  345. ssp.stackID = unitId();
  346. ssp.which = BattleSetStackProperty::CASTS;
  347. ssp.val = -spellCost;
  348. ssp.absolute = false;
  349. server->apply(&ssp);
  350. }