CStack.cpp 10 KB

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