CStack.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 "battle/BattleInfo.h"
  13. #include "spells/CSpellHandler.h"
  14. #include "CRandomGenerator.h"
  15. #include "NetPacks.h"
  16. CStack::CStack(const CStackInstance *Base, PlayerColor O, int I, bool AO, SlotID S)
  17. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  18. counterAttacksPerformed(0),counterAttacksTotalCache(0), cloneID(-1),
  19. firstHPleft(-1), position(), shots(0), casts(0), resurrected(0)
  20. {
  21. assert(base);
  22. type = base->type;
  23. count = baseAmount = base->count;
  24. setNodeType(STACK_BATTLE);
  25. }
  26. CStack::CStack()
  27. {
  28. init();
  29. setNodeType(STACK_BATTLE);
  30. }
  31. CStack::CStack(const CStackBasicDescriptor *stack, PlayerColor O, int I, bool AO, SlotID S)
  32. : base(nullptr), ID(I), owner(O), slot(S), attackerOwned(AO),
  33. counterAttacksPerformed(0), counterAttacksTotalCache(0), cloneID(-1),
  34. firstHPleft(-1), position(), shots(0), casts(0), resurrected(0)
  35. {
  36. type = stack->type;
  37. count = baseAmount = stack->count;
  38. setNodeType(STACK_BATTLE);
  39. }
  40. void CStack::init()
  41. {
  42. base = nullptr;
  43. type = nullptr;
  44. ID = -1;
  45. count = baseAmount = -1;
  46. firstHPleft = -1;
  47. owner = PlayerColor::NEUTRAL;
  48. slot = SlotID(255);
  49. attackerOwned = false;
  50. position = BattleHex();
  51. counterAttacksPerformed = 0;
  52. counterAttacksTotalCache = 0;
  53. cloneID = -1;
  54. shots = 0;
  55. casts = 0;
  56. resurrected = 0;
  57. }
  58. void CStack::postInit()
  59. {
  60. assert(type);
  61. assert(getParentNodes().size());
  62. firstHPleft = MaxHealth();
  63. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  64. counterAttacksPerformed = 0;
  65. counterAttacksTotalCache = 0;
  66. casts = valOfBonuses(Bonus::CASTS);
  67. resurrected = 0;
  68. cloneID = -1;
  69. }
  70. ui32 CStack::level() const
  71. {
  72. if (base)
  73. return base->getLevel(); //creatture or commander
  74. else
  75. return std::max(1, (int)getCreature()->level); //war machine, clone etc
  76. }
  77. si32 CStack::magicResistance() const
  78. {
  79. si32 magicResistance;
  80. if (base) //TODO: make war machines receive aura of magic resistance
  81. {
  82. magicResistance = base->magicResistance();
  83. int auraBonus = 0;
  84. for (const CStack * stack : base->armyObj->battle-> batteAdjacentCreatures(this))
  85. {
  86. if (stack->owner == owner)
  87. {
  88. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  89. }
  90. }
  91. magicResistance += auraBonus;
  92. vstd::amin (magicResistance, 100);
  93. }
  94. else
  95. magicResistance = type->magicResistance();
  96. return magicResistance;
  97. }
  98. bool CStack::willMove(int turn /*= 0*/) const
  99. {
  100. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  101. && !moved(turn)
  102. && canMove(turn);
  103. }
  104. bool CStack::canMove( int turn /*= 0*/ ) const
  105. {
  106. return alive()
  107. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE).And(Selector::turns(turn))); //eg. Ammo Cart or blinded creature
  108. }
  109. bool CStack::moved( int turn /*= 0*/ ) const
  110. {
  111. if(!turn)
  112. return vstd::contains(state, EBattleStackState::MOVED);
  113. else
  114. return false;
  115. }
  116. bool CStack::waited(int turn /*= 0*/) const
  117. {
  118. if(!turn)
  119. return vstd::contains(state, EBattleStackState::WAITING);
  120. else
  121. return false;
  122. }
  123. bool CStack::doubleWide() const
  124. {
  125. return getCreature()->doubleWide;
  126. }
  127. BattleHex CStack::occupiedHex() const
  128. {
  129. return occupiedHex(position);
  130. }
  131. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  132. {
  133. if (doubleWide())
  134. {
  135. if (attackerOwned)
  136. return assumedPos - 1;
  137. else
  138. return assumedPos + 1;
  139. }
  140. else
  141. {
  142. return BattleHex::INVALID;
  143. }
  144. }
  145. std::vector<BattleHex> CStack::getHexes() const
  146. {
  147. return getHexes(position);
  148. }
  149. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  150. {
  151. return getHexes(assumedPos, doubleWide(), attackerOwned);
  152. }
  153. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  154. {
  155. std::vector<BattleHex> hexes;
  156. hexes.push_back(assumedPos);
  157. if (twoHex)
  158. {
  159. if (AttackerOwned)
  160. hexes.push_back(assumedPos - 1);
  161. else
  162. hexes.push_back(assumedPos + 1);
  163. }
  164. return hexes;
  165. }
  166. bool CStack::coversPos(BattleHex pos) const
  167. {
  168. return vstd::contains(getHexes(), pos);
  169. }
  170. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  171. {
  172. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  173. std::vector<BattleHex> hexes;
  174. if (doubleWide())
  175. {
  176. const int WN = GameConstants::BFIELD_WIDTH;
  177. if(attackerOwned)
  178. { //position is equal to front hex
  179. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  180. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  181. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  182. BattleHex::checkAndPush(hex - 2, hexes);
  183. BattleHex::checkAndPush(hex + 1, hexes);
  184. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  185. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  186. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  187. }
  188. else
  189. {
  190. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  191. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  192. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  193. BattleHex::checkAndPush(hex + 2, hexes);
  194. BattleHex::checkAndPush(hex - 1, hexes);
  195. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  196. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  197. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  198. }
  199. return hexes;
  200. }
  201. else
  202. {
  203. return hex.neighbouringTiles();
  204. }
  205. }
  206. std::vector<si32> CStack::activeSpells() const
  207. {
  208. std::vector<si32> ret;
  209. std::stringstream cachingStr;
  210. cachingStr << "!type_" << Bonus::NONE << "source_" << Bonus::SPELL_EFFECT;
  211. CSelector selector = Selector::sourceType(Bonus::SPELL_EFFECT)
  212. .And(CSelector([](const Bonus *b)->bool
  213. {
  214. return b->type != Bonus::NONE;
  215. }));
  216. TBonusListPtr spellEffects = getBonuses(selector, Selector::all, cachingStr.str());
  217. for(const std::shared_ptr<Bonus> it : *spellEffects)
  218. {
  219. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  220. ret.push_back(it->sid);
  221. }
  222. return ret;
  223. }
  224. CStack::~CStack()
  225. {
  226. detachFromAll();
  227. }
  228. const CGHeroInstance * CStack::getMyHero() const
  229. {
  230. if(base)
  231. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  232. else //we are attached directly?
  233. for(const CBonusSystemNode *n : getParentNodes())
  234. if(n->getNodeType() == HERO)
  235. return dynamic_cast<const CGHeroInstance *>(n);
  236. return nullptr;
  237. }
  238. ui32 CStack::totalHealth() const
  239. {
  240. return ((count > 0) ? MaxHealth() * (count-1) : 0) + firstHPleft;//do not hide possible invalid firstHPleft for dead stack
  241. }
  242. std::string CStack::nodeName() const
  243. {
  244. std::ostringstream oss;
  245. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  246. if(type)
  247. oss << type->namePl;
  248. else
  249. oss << "[UNDEFINED TYPE]";
  250. oss << " from slot " << slot;
  251. if(base && base->armyObj)
  252. oss << " of armyobj=" << base->armyObj->id.getNum();
  253. return oss.str();
  254. }
  255. std::pair<int,int> CStack::countKilledByAttack(int damageReceived) const
  256. {
  257. int newRemainingHP = 0;
  258. int killedCount = damageReceived / MaxHealth();
  259. unsigned damageFirst = damageReceived % MaxHealth();
  260. if (damageReceived && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  261. {
  262. killedCount = count;
  263. }
  264. else
  265. {
  266. if( firstHPleft <= damageFirst )
  267. {
  268. killedCount++;
  269. newRemainingHP = firstHPleft + MaxHealth() - damageFirst;
  270. }
  271. else
  272. {
  273. newRemainingHP = firstHPleft - damageFirst;
  274. }
  275. }
  276. if(killedCount == count)
  277. newRemainingHP = 0;
  278. return std::make_pair(killedCount, newRemainingHP);
  279. }
  280. void CStack::prepareAttacked(BattleStackAttacked &bsa, CRandomGenerator & rand, boost::optional<int> customCount /*= boost::none*/) const
  281. {
  282. auto afterAttack = countKilledByAttack(bsa.damageAmount);
  283. bsa.killedAmount = afterAttack.first;
  284. bsa.newHP = afterAttack.second;
  285. if(bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  286. {
  287. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  288. return; // no rebirth I believe
  289. }
  290. const int countToUse = customCount ? *customCount : count;
  291. if(countToUse <= bsa.killedAmount) //stack killed
  292. {
  293. bsa.newAmount = 0;
  294. bsa.flags |= BattleStackAttacked::KILLED;
  295. bsa.killedAmount = countToUse; //we cannot kill more creatures than we have
  296. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  297. if(resurrectFactor > 0 && casts) //there must be casts left
  298. {
  299. int resurrectedStackCount = base->count * resurrectFactor / 100;
  300. // last stack has proportional chance to rebirth
  301. auto diff = base->count * resurrectFactor / 100.0 - resurrectedStackCount;
  302. if (diff > rand.nextDouble(0, 0.99))
  303. {
  304. resurrectedStackCount += 1;
  305. }
  306. if(hasBonusOfType(Bonus::REBIRTH, 1))
  307. {
  308. // resurrect at least one Sacred Phoenix
  309. vstd::amax(resurrectedStackCount, 1);
  310. }
  311. if(resurrectedStackCount > 0)
  312. {
  313. bsa.flags |= BattleStackAttacked::REBIRTH;
  314. bsa.newAmount = resurrectedStackCount; //risky?
  315. bsa.newHP = MaxHealth(); //resore full health
  316. }
  317. }
  318. }
  319. else
  320. {
  321. bsa.newAmount = countToUse - bsa.killedAmount;
  322. }
  323. }
  324. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  325. {
  326. if (!attackerPos.isValid())
  327. {
  328. attackerPos = attacker->position;
  329. }
  330. if (!defenderPos.isValid())
  331. {
  332. defenderPos = defender->position;
  333. }
  334. return
  335. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  336. || (attacker->doubleWide() //back <=> front
  337. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  338. || (defender->doubleWide() //front <=> back
  339. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  340. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  341. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  342. }
  343. bool CStack::ableToRetaliate() const //FIXME: crash after clone is killed
  344. {
  345. return alive()
  346. && (counterAttacksPerformed < counterAttacksTotal() || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  347. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  348. && !hasBonusOfType(Bonus::HYPNOTIZED)
  349. && !hasBonusOfType(Bonus::NO_RETALIATION);
  350. }
  351. ui8 CStack::counterAttacksTotal() const
  352. {
  353. //after dispell bonus should remain during current round
  354. ui8 val = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  355. vstd::amax(counterAttacksTotalCache, val);
  356. return counterAttacksTotalCache;
  357. }
  358. si8 CStack::counterAttacksRemaining() const
  359. {
  360. return counterAttacksTotal() - counterAttacksPerformed;
  361. }
  362. std::string CStack::getName() const
  363. {
  364. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  365. }
  366. bool CStack::isValidTarget(bool allowDead/* = false*/) const
  367. {
  368. return (alive() || (allowDead && isDead())) && position.isValid() && !isTurret();
  369. }
  370. bool CStack::isDead() const
  371. {
  372. return !alive() && !isGhost();
  373. }
  374. bool CStack::isGhost() const
  375. {
  376. return vstd::contains(state,EBattleStackState::GHOST);
  377. }
  378. bool CStack::isTurret() const
  379. {
  380. return type->idNumber == CreatureID::ARROW_TOWERS;
  381. }
  382. bool CStack::canBeHealed() const
  383. {
  384. return firstHPleft < MaxHealth()
  385. && isValidTarget()
  386. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  387. }
  388. void CStack::makeGhost()
  389. {
  390. state.erase(EBattleStackState::ALIVE);
  391. state.insert(EBattleStackState::GHOST_PENDING);
  392. }
  393. bool CStack::alive() const //determines if stack is alive
  394. {
  395. return vstd::contains(state,EBattleStackState::ALIVE);
  396. }
  397. ui32 CStack::calculateHealedHealthPoints(ui32 toHeal, const bool resurrect) const
  398. {
  399. if(!resurrect && !alive())
  400. {
  401. logGlobal->warnStream() <<"Attempt to heal corpse detected.";
  402. return 0;
  403. }
  404. return std::min<ui32>(toHeal, MaxHealth() - firstHPleft + (resurrect ? (baseAmount - count) * MaxHealth() : 0));
  405. }
  406. ui8 CStack::getSpellSchoolLevel(const CSpell * spell, int * outSelectedSchool) const
  407. {
  408. int skill = valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, spell->id));
  409. vstd::abetween(skill, 0, 3);
  410. return skill;
  411. }
  412. ui32 CStack::getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const
  413. {
  414. //stacks does not have sorcery-like bonuses (yet?)
  415. return base;
  416. }
  417. int CStack::getEffectLevel(const CSpell * spell) const
  418. {
  419. return getSpellSchoolLevel(spell);
  420. }
  421. int CStack::getEffectPower(const CSpell * spell) const
  422. {
  423. return valOfBonuses(Bonus::CREATURE_SPELL_POWER) * count / 100;
  424. }
  425. int CStack::getEnchantPower(const CSpell * spell) const
  426. {
  427. int res = valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  428. if(res<=0)
  429. res = 3;//default for creatures
  430. return res;
  431. }
  432. int CStack::getEffectValue(const CSpell * spell) const
  433. {
  434. return valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, spell->id.toEnum()) * count;
  435. }
  436. const PlayerColor CStack::getOwner() const
  437. {
  438. return owner;
  439. }
  440. void CStack::getCasterName(MetaString & text) const
  441. {
  442. //always plural name in case of spell cast.
  443. text.addReplacement(MetaString::CRE_PL_NAMES, type->idNumber.num);
  444. }
  445. void CStack::getCastDescription(const CSpell * spell, const std::vector<const CStack*> & attacked, MetaString & text) const
  446. {
  447. text.addTxt(MetaString::GENERAL_TXT, 565);//The %s casts %s
  448. //todo: use text 566 for single creature
  449. getCasterName(text);
  450. text.addReplacement(MetaString::SPELL_NAME, spell->id.toEnum());
  451. }