CStack.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. doubleWideCached = battle::CUnitState::doubleWide();
  33. }
  34. CStack::CStack():
  35. CBonusSystemNode(STACK_BATTLE),
  36. owner(PlayerColor::NEUTRAL),
  37. slot(SlotID(255)),
  38. initialPosition(BattleHex())
  39. {
  40. }
  41. CStack::CStack(const CStackBasicDescriptor * stack, const PlayerColor & O, int I, BattleSide Side, const SlotID & S):
  42. CBonusSystemNode(STACK_BATTLE),
  43. ID(I),
  44. typeID(stack->getId()),
  45. baseAmount(stack->count),
  46. owner(O),
  47. slot(S),
  48. side(Side)
  49. {
  50. health.init(); //???
  51. doubleWideCached = battle::CUnitState::doubleWide();
  52. }
  53. void CStack::localInit(BattleInfo * battleInfo)
  54. {
  55. battle = battleInfo;
  56. assert(typeID.hasValue());
  57. exportBonuses();
  58. if(base) //stack originating from "real" stack in garrison -> attach to it
  59. {
  60. attachTo(const_cast<CStackInstance&>(*base));
  61. }
  62. else //attach directly to obj to which stack belongs and creature type
  63. {
  64. CArmedInstance * army = battle->battleGetArmyObject(side);
  65. assert(army);
  66. attachTo(*army);
  67. attachToSource(*typeID.toCreature());
  68. }
  69. CUnitState::localInit(this); //it causes execution of the CStack::isOnNativeTerrain where nativeTerrain will be considered
  70. position = initialPosition;
  71. }
  72. ui32 CStack::level() const
  73. {
  74. if(base)
  75. return base->getLevel(); //creature or commander
  76. else
  77. return std::max(1, static_cast<int>(unitType()->getLevel())); //war machine, clone etc
  78. }
  79. si32 CStack::magicResistance() const
  80. {
  81. auto magicResistance = AFactionMember::magicResistance();
  82. si32 auraBonus = 0;
  83. for(const auto * one : battle->battleAdjacentUnits(this))
  84. {
  85. if(one->unitOwner() == owner)
  86. vstd::amax(auraBonus, one->valOfBonuses(BonusType::SPELL_RESISTANCE_AURA)); //max value
  87. }
  88. vstd::abetween(auraBonus, 0, 100);
  89. vstd::abetween(magicResistance, 0, 100);
  90. float castChance = (100 - magicResistance) * (100 - auraBonus)/100.0;
  91. return static_cast<si32>(100 - castChance);
  92. }
  93. BattleHex::EDir CStack::destShiftDir() const
  94. {
  95. if(doubleWide())
  96. {
  97. if(side == BattleSide::ATTACKER)
  98. return BattleHex::EDir::RIGHT;
  99. else
  100. return BattleHex::EDir::LEFT;
  101. }
  102. else
  103. {
  104. return BattleHex::EDir::NONE;
  105. }
  106. }
  107. std::vector<SpellID> CStack::activeSpells() const
  108. {
  109. std::vector<SpellID> ret;
  110. std::stringstream cachingStr;
  111. cachingStr << "!type_" << vstd::to_underlying(BonusType::NONE) << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT);
  112. CSelector selector = Selector::sourceType()(BonusSource::SPELL_EFFECT)
  113. .And(CSelector([](const Bonus * b)->bool
  114. {
  115. return b->type != BonusType::NONE && b->sid.as<SpellID>().toSpell() && !b->sid.as<SpellID>().toSpell()->isAdventure();
  116. }));
  117. TConstBonusListPtr spellEffects = getBonuses(selector, Selector::all, cachingStr.str());
  118. for(const auto & it : *spellEffects)
  119. {
  120. if(!vstd::contains(ret, it->sid.as<SpellID>())) //do not duplicate spells with multiple effects
  121. ret.push_back(it->sid.as<SpellID>());
  122. }
  123. return ret;
  124. }
  125. CStack::~CStack()
  126. {
  127. detachFromAll();
  128. }
  129. const CGHeroInstance * CStack::getMyHero() const
  130. {
  131. if(base)
  132. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  133. else //we are attached directly?
  134. for(const CBonusSystemNode * n : getParentNodes())
  135. if(n->getNodeType() == HERO)
  136. return dynamic_cast<const CGHeroInstance *>(n);
  137. return nullptr;
  138. }
  139. std::string CStack::nodeName() const
  140. {
  141. std::ostringstream oss;
  142. oss << owner.toString();
  143. oss << " battle stack [" << ID << "]: " << getCount() << " of ";
  144. if(typeID.hasValue())
  145. oss << typeID.toEntity(LIBRARY)->getJsonKey();
  146. else
  147. oss << "[UNDEFINED TYPE]";
  148. oss << " from slot " << slot;
  149. if(base && base->armyObj)
  150. oss << " of armyobj=" << base->armyObj->id.getNum();
  151. return oss.str();
  152. }
  153. void CStack::prepareAttacked(BattleStackAttacked & bsa, vstd::RNG & rand) const
  154. {
  155. auto newState = acquireState();
  156. prepareAttacked(bsa, rand, newState);
  157. }
  158. void CStack::prepareAttacked(BattleStackAttacked & bsa, vstd::RNG & rand, const std::shared_ptr<battle::CUnitState> & customState)
  159. {
  160. auto initialCount = customState->getCount();
  161. // compute damage and update bsa.damageAmount
  162. customState->damage(bsa.damageAmount);
  163. bsa.killedAmount = initialCount - customState->getCount();
  164. if(!customState->alive() && customState->isClone())
  165. {
  166. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  167. }
  168. else if(!customState->alive()) //stack killed
  169. {
  170. bsa.flags |= BattleStackAttacked::KILLED;
  171. auto resurrectValue = customState->valOfBonuses(BonusType::REBIRTH);
  172. if(resurrectValue > 0 && customState->canCast()) //there must be casts left
  173. {
  174. double resurrectFactor = resurrectValue / 100.0;
  175. auto baseAmount = customState->unitBaseAmount();
  176. double resurrectedRaw = baseAmount * resurrectFactor;
  177. auto resurrectedCount = static_cast<int32_t>(floor(resurrectedRaw));
  178. auto resurrectedAdd = static_cast<int32_t>(baseAmount - (resurrectedCount / resurrectFactor));
  179. for(int32_t i = 0; i < resurrectedAdd; i++)
  180. {
  181. if(resurrectValue > rand.nextInt(0, 99))
  182. resurrectedCount += 1;
  183. }
  184. if(customState->hasBonusOfType(BonusType::REBIRTH, BonusCustomSubtype::rebirthSpecial))
  185. {
  186. // resurrect at least one Sacred Phoenix
  187. vstd::amax(resurrectedCount, 1);
  188. }
  189. if(resurrectedCount > 0)
  190. {
  191. customState->casts.use();
  192. bsa.flags |= BattleStackAttacked::REBIRTH;
  193. int64_t toHeal = customState->getMaxHealth() * resurrectedCount;
  194. //TODO: add one-battle rebirth?
  195. customState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  196. customState->counterAttacks.use(customState->counterAttacks.available());
  197. }
  198. }
  199. }
  200. customState->save(bsa.newState.data);
  201. bsa.newState.healthDelta = -bsa.damageAmount;
  202. bsa.newState.id = customState->unitId();
  203. bsa.newState.operation = UnitChanges::EOperation::RESET_STATE;
  204. }
  205. BattleHexArray CStack::meleeAttackHexes(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPos, BattleHex defenderPos)
  206. {
  207. int mask = 0;
  208. BattleHexArray res;
  209. if (!attackerPos.isValid())
  210. attackerPos = attacker->getPosition();
  211. if (!defenderPos.isValid())
  212. defenderPos = defender->getPosition();
  213. BattleHex otherAttackerPos = attackerPos.toInt() + (attacker->unitSide() == BattleSide::ATTACKER ? -1 : 1);
  214. BattleHex otherDefenderPos = defenderPos.toInt() + (defender->unitSide() == BattleSide::ATTACKER ? -1 : 1);
  215. if(BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  216. {
  217. if((mask & 1) == 0)
  218. {
  219. mask |= 1;
  220. res.insert(defenderPos);
  221. }
  222. }
  223. if (attacker->doubleWide() //back <=> front
  224. && BattleHex::mutualPosition(otherAttackerPos, defenderPos) >= 0)
  225. {
  226. if((mask & 1) == 0)
  227. {
  228. mask |= 1;
  229. res.insert(defenderPos);
  230. }
  231. }
  232. if (defender->doubleWide()//front <=> back
  233. && BattleHex::mutualPosition(attackerPos, otherDefenderPos) >= 0)
  234. {
  235. if((mask & 2) == 0)
  236. {
  237. mask |= 2;
  238. res.insert(otherDefenderPos);
  239. }
  240. }
  241. if (defender->doubleWide() && attacker->doubleWide()//back <=> back
  242. && BattleHex::mutualPosition(otherAttackerPos, otherDefenderPos) >= 0)
  243. {
  244. if((mask & 2) == 0)
  245. {
  246. mask |= 2;
  247. res.insert(otherDefenderPos);
  248. }
  249. }
  250. return res;
  251. }
  252. bool CStack::isMeleeAttackPossible(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPos, BattleHex defenderPos)
  253. {
  254. if(defender->isInvincible())
  255. return false;
  256. return !meleeAttackHexes(attacker, defender, attackerPos, defenderPos).empty();
  257. }
  258. std::string CStack::getName() const
  259. {
  260. return (getCount() == 1) ? typeID.toEntity(LIBRARY)->getNameSingularTranslated() : typeID.toEntity(LIBRARY)->getNamePluralTranslated(); //War machines can't use base
  261. }
  262. bool CStack::canBeHealed() const
  263. {
  264. return getFirstHPleft() < static_cast<int32_t>(getMaxHealth()) && isValidTarget() && !hasBonusOfType(BonusType::SIEGE_WEAPON);
  265. }
  266. bool CStack::isOnNativeTerrain() const
  267. {
  268. auto nativeTerrain = getNativeTerrain();
  269. return nativeTerrain == ETerrainId::ANY_TERRAIN || getCurrentTerrain() == nativeTerrain;
  270. }
  271. TerrainId CStack::getCurrentTerrain() const
  272. {
  273. return battle->getTerrainType();
  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. void CStack::postDeserialize(const CArmedInstance * army, const SlotID & extSlot)
  344. {
  345. if(extSlot == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  346. {
  347. const auto * hero = dynamic_cast<const CGHeroInstance *>(army);
  348. assert(hero);
  349. base = hero->commander;
  350. }
  351. else if(slot == SlotID::SUMMONED_SLOT_PLACEHOLDER || slot == SlotID::ARROW_TOWERS_SLOT || slot == SlotID::WAR_MACHINES_SLOT)
  352. {
  353. //no external slot possible, so no base stack
  354. base = nullptr;
  355. }
  356. else if(!army || extSlot == SlotID() || !army->hasStackAtSlot(extSlot))
  357. {
  358. base = nullptr;
  359. logGlobal->warn("%s doesn't have a base stack!", typeID.toEntity(LIBRARY)->getNameSingularTranslated());
  360. }
  361. else
  362. {
  363. base = &army->getStack(extSlot);
  364. }
  365. doubleWideCached = battle::CUnitState::doubleWide();
  366. }
  367. VCMI_LIB_NAMESPACE_END