CStack.cpp 10 KB

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