CStack.cpp 10 KB

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