BattleState.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  1. #include "StdInc.h"
  2. #include "BattleState.h"
  3. #include <numeric>
  4. #include <boost/random/linear_congruential.hpp>
  5. #include "VCMI_Lib.h"
  6. #include "CObjectHandler.h"
  7. #include "CHeroHandler.h"
  8. #include "CCreatureHandler.h"
  9. #include "CSpellHandler.h"
  10. #include "CTownHandler.h"
  11. #include "NetPacks.h"
  12. #include "JsonNode.h"
  13. #include "Filesystem/CResourceLoader.h"
  14. /*
  15. * BattleState.h, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. extern boost::rand48 ran;
  24. const CStack * BattleInfo::getNextStack() const
  25. {
  26. std::vector<const CStack *> hlp;
  27. battleGetStackQueue(hlp, 1, -1);
  28. if(hlp.size())
  29. return hlp[0];
  30. else
  31. return NULL;
  32. }
  33. BattleHex BattleInfo::getClosestTile(bool attackerOwned, BattleHex initialPos, std::set<BattleHex> & possibilities) const
  34. {
  35. std::vector<BattleHex> sortedTiles (possibilities.begin(), possibilities.end()); //set can't be sorted properly :(
  36. BattleHex initialHex = BattleHex(initialPos);
  37. auto compareDistance = [initialHex](const BattleHex left, const BattleHex right) -> bool
  38. {
  39. return initialHex.getDistance (initialHex, left) < initialHex.getDistance (initialHex, right);
  40. };
  41. boost::sort (sortedTiles, compareDistance); //closest tiles at front
  42. int closestDistance = initialHex.getDistance(initialPos, sortedTiles.front()); //sometimes closest tiles can be many hexes away
  43. auto notClosest = [closestDistance, initialPos](const BattleHex here) -> bool
  44. {
  45. return closestDistance < here.getDistance (initialPos, here);
  46. };
  47. vstd::erase_if(sortedTiles, notClosest); //only closest tiles are interesting
  48. auto compareHorizontal = [attackerOwned, initialPos](const BattleHex left, const BattleHex right) -> bool
  49. {
  50. if(left.getX() != right.getX())
  51. {
  52. if (attackerOwned)
  53. return left.getX() > right.getX(); //find furthest right
  54. else
  55. return left.getX() < right.getX(); //find furthest left
  56. }
  57. else
  58. {
  59. //Prefer tiles in the same row.
  60. return std::abs(left.getY() - initialPos.getY()) < std::abs(right.getY() - initialPos.getY());
  61. }
  62. };
  63. boost::sort (sortedTiles, compareHorizontal);
  64. return sortedTiles.front();
  65. }
  66. int BattleInfo::getAvaliableHex(TCreature creID, bool attackerOwned, int initialPos) const
  67. {
  68. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  69. //bool flying = VLC->creh->creatures[creID]->isFlying();
  70. int pos;
  71. if (initialPos > -1)
  72. pos = initialPos;
  73. else //summon elementals depending on player side
  74. {
  75. if (attackerOwned)
  76. pos = 0; //top left
  77. else
  78. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  79. }
  80. auto accessibility = getAccesibility();
  81. std::set<BattleHex> occupyable;
  82. for(int i = 0; i < accessibility.size(); i++)
  83. if(accessibility.accessible(i, twoHex, attackerOwned))
  84. occupyable.insert(i);
  85. if (!occupyable.size())
  86. {
  87. return BattleHex::INVALID; //all tiles are covered
  88. }
  89. return getClosestTile(attackerOwned, pos, occupyable);
  90. }
  91. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack *stack)
  92. {
  93. auto reachability = getReachability(stack);
  94. if(reachability.predecessors[dest] == -1) //cannot reach destination
  95. {
  96. return std::make_pair(std::vector<BattleHex>(), 0);
  97. }
  98. //making the Path
  99. std::vector<BattleHex> path;
  100. BattleHex curElem = dest;
  101. while(curElem != start)
  102. {
  103. path.push_back(curElem);
  104. curElem = reachability.predecessors[curElem];
  105. }
  106. return std::make_pair(path, reachability.distances[dest]);
  107. }
  108. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  109. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg )
  110. {
  111. TDmgRange range = calculateDmgRange(attacker, defender, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  112. if(range.first != range.second)
  113. {
  114. int valuesToAverage[10];
  115. int howManyToAv = std::min<ui32>(10, attacker->count);
  116. for (int g=0; g<howManyToAv; ++g)
  117. {
  118. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  119. }
  120. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  121. }
  122. else
  123. return range.first;
  124. }
  125. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  126. {
  127. for(ui32 i=0; i<stacks.size();i++)//setting casualties
  128. {
  129. const CStack * const st = stacks[i];
  130. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  131. vstd::amax(killed, 0);
  132. if(killed)
  133. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  134. }
  135. }
  136. std::set<const CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, BattleHex destinationTile)
  137. {
  138. std::set<const CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  139. const ui8 attackerSide = sides[1] == attackerOwner;
  140. const auto attackedHexes = s->rangeInHexes(destinationTile, skillLevel, attackerSide);
  141. const bool onlyAlive = s->id != Spells::RESURRECTION && s->id != Spells::ANIMATE_DEAD; //when casting resurrection or animate dead we should be allow to select dead stack
  142. //fixme: what about other rising spells (Sacrifice) ?
  143. if(s->id == Spells::DEATH_RIPPLE || s->id == Spells::DESTROY_UNDEAD || s->id == Spells::ARMAGEDDON)
  144. {
  145. for(int it=0; it<stacks.size(); ++it)
  146. {
  147. if((s->id == Spells::DEATH_RIPPLE && !stacks[it]->getCreature()->isUndead()) //death ripple
  148. || (s->id == Spells::DESTROY_UNDEAD && stacks[it]->getCreature()->isUndead()) //destroy undead
  149. || (s->id == Spells::ARMAGEDDON) //Armageddon
  150. )
  151. {
  152. if(stacks[it]->isValidTarget())
  153. attackedCres.insert(stacks[it]);
  154. }
  155. }
  156. }
  157. else if (s->id == Spells::CHAIN_LIGHTNING)
  158. {
  159. std::set<BattleHex> possibleHexes;
  160. BOOST_FOREACH (auto stack, stacks)
  161. {
  162. if (stack->isValidTarget())
  163. {
  164. BOOST_FOREACH (auto hex, stack->getHexes())
  165. {
  166. possibleHexes.insert (hex);
  167. }
  168. }
  169. }
  170. BattleHex lightningHex = destinationTile;
  171. for (int i = 0; i < 5; ++i) //TODO: depends on spell school level
  172. {
  173. auto stack = battleGetStackByPos (lightningHex, true);
  174. if (!stack)
  175. break;
  176. attackedCres.insert (stack);
  177. BOOST_FOREACH (auto hex, stack->getHexes())
  178. {
  179. possibleHexes.erase (hex); //can't hit same place twice
  180. }
  181. lightningHex = getClosestTile (attackerOwner, destinationTile, possibleHexes);
  182. }
  183. }
  184. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  185. {
  186. BOOST_FOREACH(BattleHex hex, attackedHexes)
  187. {
  188. if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
  189. {
  190. if (s->id == 76) //Death Cloud //TODO: fireball and fire immunity
  191. {
  192. if (st->isLiving() || st->coversPos(destinationTile)) //directly hit or alive
  193. {
  194. attackedCres.insert(st);
  195. }
  196. }
  197. else
  198. attackedCres.insert(st);
  199. }
  200. }
  201. }
  202. else if(s->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  203. {
  204. if(skillLevel < 3) /*not expert */
  205. {
  206. const CStack * st = battleGetStackByPos(destinationTile, onlyAlive);
  207. if(st)
  208. attackedCres.insert(st);
  209. }
  210. else
  211. {
  212. for(int it=0; it<stacks.size(); ++it)
  213. {
  214. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  215. if((!s->isNegative() && stacks[it]->owner == attackerOwner)
  216. ||(!s->isPositive() && stacks[it]->owner != attackerOwner )
  217. )
  218. {
  219. if(stacks[it]->isValidTarget(!onlyAlive))
  220. attackedCres.insert(stacks[it]);
  221. }
  222. }
  223. } //if(caster->getSpellSchoolLevel(s) < 3)
  224. }
  225. else if(s->getTargetType() == CSpell::CREATURE)
  226. {
  227. if(const CStack * st = battleGetStackByPos(destinationTile, onlyAlive))
  228. attackedCres.insert(st);
  229. }
  230. else //custom range from attackedHexes
  231. {
  232. BOOST_FOREACH(BattleHex hex, attackedHexes)
  233. {
  234. if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
  235. attackedCres.insert(st);
  236. }
  237. }
  238. return attackedCres;
  239. }
  240. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower)
  241. {
  242. if(!caster)
  243. {
  244. if (!usedSpellPower)
  245. return 3; //default duration of all creature spells
  246. else
  247. return usedSpellPower; //use creature spell power
  248. }
  249. switch(spell->id)
  250. {
  251. case Spells::FRENZY:
  252. return 1;
  253. default: //other spells
  254. return caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  255. }
  256. }
  257. CStack * BattleInfo::generateNewStack(const CStackInstance &base, bool attackerOwned, int slot, BattleHex position) const
  258. {
  259. int stackID = getIdForNewStack();
  260. int owner = attackerOwned ? sides[0] : sides[1];
  261. assert((owner >= GameConstants::PLAYER_LIMIT) ||
  262. (base.armyObj && base.armyObj->tempOwner == owner));
  263. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  264. ret->position = getAvaliableHex (base.getCreatureID(), attackerOwned, position); //TODO: what if no free tile on battlefield was found?
  265. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  266. return ret;
  267. }
  268. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, int slot, BattleHex position) const
  269. {
  270. int stackID = getIdForNewStack();
  271. int owner = attackerOwned ? sides[0] : sides[1];
  272. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  273. ret->position = position;
  274. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  275. return ret;
  276. }
  277. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  278. {
  279. ui32 ret = baseDamage;
  280. //applying sorcery secondary skill
  281. if(caster)
  282. {
  283. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::SORCERY)) / 100.0;
  284. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0;
  285. if(sp->air)
  286. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  287. else if(sp->fire) //only one type of bonus for Magic Arrow
  288. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  289. else if(sp->water)
  290. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  291. else if(sp->earth)
  292. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  293. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  294. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  295. }
  296. return ret;
  297. }
  298. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  299. {
  300. ui32 ret = 0; //value to return
  301. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  302. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  303. //check if spell really does damage - if not, return 0
  304. if(VLC->spellh->damageSpells.find(sp->id) == VLC->spellh->damageSpells.end())
  305. return 0;
  306. ret = usedSpellPower * sp->power;
  307. ret += sp->powers[spellSchoolLevel];
  308. //affected creature-specific part
  309. if(affectedCreature)
  310. {
  311. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  312. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  313. {
  314. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  315. ret /= 100;
  316. }
  317. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  318. {
  319. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  320. ret /= 100;
  321. }
  322. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  323. {
  324. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  325. ret /= 100;
  326. }
  327. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  328. {
  329. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  330. ret /= 100;
  331. }
  332. //general spell dmg reduction
  333. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  334. {
  335. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  336. ret /= 100;
  337. }
  338. //dmg increasing
  339. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  340. {
  341. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  342. ret /= 100;
  343. }
  344. }
  345. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  346. return ret;
  347. }
  348. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack, const CStack * sacrificedStack) const
  349. {
  350. bool resurrect = resurrects(spell->id);
  351. int healedHealth;
  352. if (spell->id == Spells::SACRIFICE && sacrificedStack)
  353. healedHealth = (caster->getPrimSkillLevel(2) + sacrificedStack->MaxHealth() + spell->powers[caster->getSpellSchoolLevel(spell)]) * sacrificedStack->count;
  354. else
  355. healedHealth = caster->getPrimSkillLevel(2) * spell->power + spell->powers[caster->getSpellSchoolLevel(spell)];
  356. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  357. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  358. }
  359. ui32 BattleInfo::calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const
  360. {
  361. bool resurrect = resurrects(spell->id);
  362. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  363. }
  364. ui32 BattleInfo::calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const
  365. {
  366. bool resurrect = resurrects(spell->id);
  367. int healedHealth = usedSpellPower * spell->power + spell->powers[spellSchoolLevel];
  368. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  369. }
  370. bool BattleInfo::resurrects(TSpell spellid) const
  371. {
  372. return vstd::contains(VLC->spellh->risingSpells, spellid);
  373. }
  374. const CStack * BattleInfo::battleGetStack(BattleHex pos, bool onlyAlive)
  375. {
  376. CStack * stack = NULL;
  377. for(ui32 g=0; g<stacks.size(); ++g)
  378. {
  379. if(stacks[g]->position == pos
  380. || (stacks[g]->doubleWide()
  381. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  382. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  383. ) )
  384. {
  385. if (stacks[g]->alive())
  386. return stacks[g]; //we prefer living stacks - there cna be only one stack on te tile, so return it imediately
  387. else if (!onlyAlive)
  388. stack = stacks[g]; //dead stacks are only accessible when there's no alive stack on this tile
  389. }
  390. }
  391. return stack;
  392. }
  393. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  394. {
  395. return heroes[!stack->attackerOwned];
  396. }
  397. void BattleInfo::localInit()
  398. {
  399. belligerents[0]->battle = belligerents[1]->battle = this;
  400. BOOST_FOREACH(CArmedInstance *b, belligerents)
  401. b->attachTo(this);
  402. BOOST_FOREACH(CStack *s, stacks)
  403. localInitStack(s);
  404. exportBonuses();
  405. }
  406. void BattleInfo::localInitStack(CStack * s)
  407. {
  408. s->exportBonuses();
  409. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  410. {
  411. s->attachTo(const_cast<CStackInstance*>(s->base));
  412. }
  413. else //attach directly to obj to which stack belongs and creature type
  414. {
  415. CArmedInstance *army = belligerents[!s->attackerOwned];
  416. s->attachTo(army);
  417. assert(s->type);
  418. s->attachTo(const_cast<CCreature*>(s->type));
  419. }
  420. s->postInit();
  421. }
  422. namespace CGH
  423. {
  424. using namespace std;
  425. static void readBattlePositions(const JsonNode &node, vector< vector<int> > & dest)
  426. {
  427. BOOST_FOREACH(const JsonNode &level, node.Vector())
  428. {
  429. std::vector<int> pom;
  430. BOOST_FOREACH(const JsonNode &value, level.Vector())
  431. {
  432. pom.push_back(value.Float());
  433. }
  434. dest.push_back(pom);
  435. }
  436. }
  437. }
  438. //RNG that works like H3 one
  439. struct RandGen
  440. {
  441. int seed;
  442. void srand(int s)
  443. {
  444. seed = s;
  445. }
  446. void srand(int3 pos)
  447. {
  448. srand(110291 * pos.x + 167801 * pos.y + 81569);
  449. }
  450. int rand()
  451. {
  452. seed = 214013 * seed + 2531011;
  453. return (seed >> 16) & 0x7FFF;
  454. }
  455. int rand(int min, int max)
  456. {
  457. if(min == max)
  458. return min;
  459. if(min > max)
  460. return min;
  461. return min + rand() % (max - min + 1);
  462. }
  463. };
  464. struct RangeGenerator
  465. {
  466. class ExhaustedPossibilities : public std::exception
  467. {
  468. };
  469. RangeGenerator(int _min, int _max, boost::function<int()> _myRand)
  470. {
  471. myRand = _myRand;
  472. min = _min;
  473. remainingCount = _max - _min + 1;
  474. remaining.resize(remainingCount, true);
  475. }
  476. int generateNumber()
  477. {
  478. if(!remainingCount)
  479. throw ExhaustedPossibilities();
  480. if(remainingCount == 1)
  481. return 0;
  482. return myRand() % remainingCount;
  483. }
  484. //get number fulfilling predicate. Never gives the same number twice.
  485. int getSuchNumber(boost::function<bool(int)> goodNumberPred = 0)
  486. {
  487. int ret = -1;
  488. do
  489. {
  490. int n = generateNumber();
  491. int i = 0;
  492. for(;;i++)
  493. {
  494. assert(i < (int)remaining.size());
  495. if(!remaining[i])
  496. continue;
  497. if(!n)
  498. break;
  499. n--;
  500. }
  501. remainingCount--;
  502. remaining[i] = false;
  503. ret = i + min;
  504. } while(goodNumberPred && !goodNumberPred(ret));
  505. return ret;
  506. }
  507. int min, remainingCount;
  508. std::vector<bool> remaining;
  509. boost::function<int()> myRand;
  510. };
  511. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  512. {
  513. CMP_stack cmpst;
  514. BattleInfo *curB = new BattleInfo;
  515. curB->castSpells[0] = curB->castSpells[1] = 0;
  516. curB->sides[0] = armies[0]->tempOwner;
  517. curB->sides[1] = armies[1]->tempOwner;
  518. if(curB->sides[1] == 254)
  519. curB->sides[1] = 255;
  520. std::vector<CStack*> & stacks = (curB->stacks);
  521. curB->tile = tile;
  522. curB->battlefieldType = battlefieldType;
  523. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  524. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  525. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  526. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  527. curB->round = -2;
  528. curB->activeStack = -1;
  529. curB->enchanterCounter[0] = curB->enchanterCounter[1] = 0; //ready to cast
  530. if(town)
  531. {
  532. curB->town = town;
  533. curB->siege = town->fortLevel();
  534. curB->terrainType = VLC->townh->factions[town->town->typeID].nativeTerrain;
  535. }
  536. else
  537. {
  538. curB->town = NULL;
  539. curB->siege = 0;
  540. curB->terrainType = terrain;
  541. }
  542. //setting up siege obstacles
  543. if (town && town->hasFort())
  544. {
  545. for (int b = 0; b < ARRAY_COUNT (curB->si.wallState); ++b)
  546. {
  547. curB->si.wallState[b] = 1;
  548. }
  549. }
  550. //randomize obstacles
  551. if (town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  552. {
  553. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  554. RandGen r;
  555. auto ourRand = [&]{ return r.rand(); };
  556. r.srand(tile);
  557. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  558. int tilesToBlock = r.rand(5,12);
  559. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  560. std::vector<BattleHex> blockedTiles;
  561. auto appropriateAbsoluteObstacle = [&](int id)
  562. {
  563. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  564. };
  565. auto appropriateUsualObstacle = [&](int id) -> bool
  566. {
  567. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  568. };
  569. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  570. {
  571. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  572. try
  573. {
  574. auto obstPtr = make_shared<CObstacleInstance>();
  575. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  576. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  577. obstPtr->uniqueID = curB->obstacles.size();
  578. curB->obstacles.push_back(obstPtr);
  579. BOOST_FOREACH(BattleHex blocked, obstPtr->getBlockedTiles())
  580. blockedTiles.push_back(blocked);
  581. tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  582. }
  583. catch(RangeGenerator::ExhaustedPossibilities &)
  584. {
  585. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  586. }
  587. }
  588. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  589. try
  590. {
  591. while(tilesToBlock > 0)
  592. {
  593. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  594. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  595. auto validPosition = [&](BattleHex pos) -> bool
  596. {
  597. if(obi.height >= pos.getY())
  598. return false;
  599. if(pos.getX() == 0)
  600. return false;
  601. if(pos.getX() + obi.width > 15)
  602. return false;
  603. if(vstd::contains(blockedTiles, pos))
  604. return false;
  605. BOOST_FOREACH(BattleHex blocked, obi.getBlocked(pos))
  606. {
  607. if(vstd::contains(blockedTiles, blocked))
  608. return false;
  609. int x = blocked.getX();
  610. if(x <= 2 || x >= 14)
  611. return false;
  612. }
  613. return true;
  614. };
  615. RangeGenerator posgenerator(18, 168, ourRand);
  616. auto obstPtr = make_shared<CObstacleInstance>();
  617. obstPtr->ID = obid;
  618. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  619. obstPtr->uniqueID = curB->obstacles.size();
  620. curB->obstacles.push_back(obstPtr);
  621. BOOST_FOREACH(BattleHex blocked, obstPtr->getBlockedTiles())
  622. blockedTiles.push_back(blocked);
  623. tilesToBlock -= obi.blockedTiles.size();
  624. }
  625. }
  626. catch(RangeGenerator::ExhaustedPossibilities &)
  627. {
  628. }
  629. }
  630. //reading battleStartpos - add creatures AFTER random obstacles are generated
  631. //TODO: parse once to some structure
  632. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  633. std::vector <int> commanderField, commanderBank;
  634. const JsonNode config(ResourceID("config/battleStartpos.json"));
  635. const JsonVector &positions = config["battle_positions"].Vector();
  636. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  637. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  638. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  639. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  640. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  641. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  642. BOOST_FOREACH (auto position, config["commanderPositions"]["field"].Vector())
  643. {
  644. commanderField.push_back (position.Float());
  645. }
  646. BOOST_FOREACH (auto position, config["commanderPositions"]["creBank"].Vector())
  647. {
  648. commanderBank.push_back (position.Float());
  649. }
  650. //adding war machines
  651. if(!creatureBank)
  652. {
  653. //Checks if hero has artifact and create appropriate stack
  654. auto handleWarMachine= [&](int side, int artslot, int cretype, int hex)
  655. {
  656. if(heroes[side] && heroes[side]->getArt(artslot))
  657. stacks.push_back(curB->generateNewStack(CStackBasicDescriptor(cretype, 1), true, 255, hex));
  658. };
  659. handleWarMachine(0, 13, 146, 52); //ballista
  660. handleWarMachine(0, 14, 148, 18); //ammo cart
  661. handleWarMachine(0, 15, 147, 154);//first aid tent
  662. if(town && town->hasFort())
  663. handleWarMachine(0, 16, 145, 120);//catapult
  664. if(!town) //defending hero shouldn't receive ballista (bug #551)
  665. handleWarMachine(1, 13, 146, 66); //ballista
  666. handleWarMachine(1, 14, 148, 32); //ammo cart
  667. handleWarMachine(1, 15, 147, 168); //first aid tent
  668. }
  669. //war machines added
  670. //battleStartpos read
  671. for(int side = 0; side < 2; side++)
  672. {
  673. int formationNo = armies[side]->stacksCount() - 1;
  674. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  675. int k = 0; //stack serial
  676. for(TSlots::const_iterator i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  677. {
  678. std::vector<int> *formationVector = nullptr;
  679. if(creatureBank)
  680. formationVector = &creBankFormations[side][formationNo];
  681. else if(armies[side]->formation)
  682. formationVector = &tightFormations[side][formationNo];
  683. else
  684. formationVector = &looseFormations[side][formationNo];
  685. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  686. if(creatureBank && i->second->type->isDoubleWide())
  687. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  688. CStack * stack = curB->generateNewStack(*i->second, !side, i->first, pos);
  689. stacks.push_back(stack);
  690. }
  691. }
  692. //adding commanders
  693. for (int i = 0; i < 2; ++i)
  694. {
  695. if (heroes[i] && heroes[i]->commander)
  696. {
  697. CStack * stack = curB->generateNewStack (*heroes[i]->commander, !i, -2, //TODO: use COMMANDER_SLOT_PLACEHOLDER
  698. creatureBank ? commanderBank[i] : commanderField[i]);
  699. stacks.push_back(stack);
  700. }
  701. }
  702. if (curB->siege == 2 || curB->siege == 3)
  703. {
  704. // keep tower
  705. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -2);
  706. stacks.push_back(stack);
  707. if (curB->siege == 3)
  708. {
  709. // lower tower + upper tower
  710. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -4);
  711. stacks.push_back(stack);
  712. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -3);
  713. stacks.push_back(stack);
  714. }
  715. //moat
  716. auto moat = make_shared<MoatObstacle>();
  717. moat->ID = curB->town->subID;
  718. moat->obstacleType = CObstacleInstance::MOAT;
  719. moat->uniqueID = curB->obstacles.size();
  720. curB->obstacles.push_back(moat);
  721. }
  722. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  723. //spell level limiting bonus
  724. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  725. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  726. //giving terrain overalay premies
  727. int bonusSubtype = -1;
  728. switch(battlefieldType)
  729. {
  730. case 9: //magic plains
  731. {
  732. bonusSubtype = 0;
  733. }
  734. case 14: //fiery fields
  735. {
  736. if(bonusSubtype == -1) bonusSubtype = 1;
  737. }
  738. case 15: //rock lands
  739. {
  740. if(bonusSubtype == -1) bonusSubtype = 8;
  741. }
  742. case 16: //magic clouds
  743. {
  744. if(bonusSubtype == -1) bonusSubtype = 2;
  745. }
  746. case 17: //lucid pools
  747. {
  748. if(bonusSubtype == -1) bonusSubtype = 4;
  749. }
  750. { //common part for cases 9, 14, 15, 16, 17
  751. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  752. break;
  753. }
  754. case 18: //holy ground
  755. {
  756. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  757. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  758. break;
  759. }
  760. case 19: //clover field
  761. { //+2 luck bonus for neutral creatures
  762. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureFactionLimiter>(-1)));
  763. break;
  764. }
  765. case 20: //evil fog
  766. {
  767. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  768. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  769. break;
  770. }
  771. case 22: //cursed ground
  772. {
  773. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  774. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  775. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, GameConstants::SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  776. b->valType = Bonus::INDEPENDENT_MAX;
  777. curB->addNewBonus(b);
  778. break;
  779. }
  780. }
  781. //overlay premies given
  782. //native terrain bonuses
  783. auto nativeTerrain = make_shared<CreatureNativeTerrainLimiter>(curB->terrainType);
  784. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  785. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  786. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  787. //////////////////////////////////////////////////////////////////////////
  788. //tactics
  789. bool isTacticsAllowed = !creatureBank; //no tactics in crebanks
  790. int tacticLvls[2] = {0};
  791. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  792. {
  793. if(heroes[i])
  794. tacticLvls[i] += heroes[i]->getSecSkillLevel(CGHeroInstance::TACTICS);
  795. }
  796. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  797. if(tacticsSkillDiff && isTacticsAllowed)
  798. {
  799. curB->tacticsSide = tacticsSkillDiff < 0;
  800. curB->tacticDistance = std::abs(tacticsSkillDiff)*2 + 1;
  801. }
  802. else
  803. curB->tacticDistance = 0;
  804. // workaround — bonuses affecting only enemy
  805. for(int i = 0; i < 2; i++)
  806. {
  807. TNodes nodes;
  808. curB->belligerents[i]->getRedAncestors(nodes);
  809. BOOST_FOREACH(CBonusSystemNode *n, nodes)
  810. {
  811. BOOST_FOREACH(Bonus *b, n->getExportedBonusList())
  812. {
  813. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  814. {
  815. Bonus *bCopy = new Bonus(*b);
  816. bCopy->effectRange = Bonus::NO_LIMIT;
  817. bCopy->propagator.reset();
  818. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i]));
  819. curB->addNewBonus(bCopy);
  820. }
  821. }
  822. }
  823. }
  824. return curB;
  825. }
  826. const CGHeroInstance * BattleInfo::getHero( int player ) const
  827. {
  828. assert(sides[0] == player || sides[1] == player);
  829. if(heroes[0] && heroes[0]->getOwner() == player)
  830. return heroes[0];
  831. return heroes[1];
  832. }
  833. std::vector<ui32> BattleInfo::calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<const CStack*> affectedCreatures, int casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const
  834. {
  835. std::vector<ui32> ret;
  836. for(auto it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  837. {
  838. if(battleIsImmune(caster, sp, mode, (*it)->position) != ESpellCastProblem::OK)
  839. {
  840. ret.push_back((*it)->ID);
  841. continue;
  842. }
  843. //non-negative spells on friendly stacks should always succeed, unless immune
  844. if(!sp->isNegative() && (*it)->owner == casterSideOwner)
  845. continue;
  846. /*
  847. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  848. if((*it)->owner == casterSideOwner)
  849. bonusHero = caster;
  850. else
  851. bonusHero = hero2;*/
  852. int prob = (*it)->magicResistance(); //probability of resistance in %
  853. if(prob > 100) prob = 100;
  854. if(rand()%100 < prob) //immunity from resistance
  855. ret.push_back((*it)->ID);
  856. }
  857. if(sp->id == 60) //hypnotize
  858. {
  859. for(auto it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  860. {
  861. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  862. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  863. >
  864. usedSpellPower * 25 + sp->powers[spellLevel]
  865. )
  866. {
  867. ret.push_back((*it)->ID);
  868. }
  869. }
  870. }
  871. return ret;
  872. }
  873. int BattleInfo::theOtherPlayer(int player) const
  874. {
  875. return sides[!whatSide(player)];
  876. }
  877. ui8 BattleInfo::whatSide(int player) const
  878. {
  879. for(int i = 0; i < ARRAY_COUNT(sides); i++)
  880. if(sides[i] == player)
  881. return i;
  882. tlog1 << "BattleInfo::whatSide: Player " << player << " is not in battle!\n";
  883. return -1;
  884. }
  885. int BattleInfo::getIdForNewStack() const
  886. {
  887. if(stacks.size())
  888. {
  889. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  890. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  891. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  892. return highestIDStack->ID + 1;
  893. }
  894. return 0;
  895. }
  896. shared_ptr<CObstacleInstance> BattleInfo::getObstacleOnTile(BattleHex tile) const
  897. {
  898. BOOST_FOREACH(auto &obs, obstacles)
  899. if(vstd::contains(obs->getAffectedTiles(), tile))
  900. return obs;
  901. return shared_ptr<CObstacleInstance>();
  902. }
  903. int BattleInfo::battlefieldTypeToBI(int bfieldType)
  904. {
  905. static const std::map<int, int> theMap = boost::assign::map_list_of(19, BattlefieldBI::CLOVER_FIELD)
  906. (22, BattlefieldBI::CURSED_GROUND)(20, BattlefieldBI::EVIL_FOG)(21, BattlefieldBI::NONE)
  907. (14, BattlefieldBI::FIERY_FIELDS)(18, BattlefieldBI::HOLY_GROUND)(17, BattlefieldBI::LUCID_POOLS)
  908. (16, BattlefieldBI::MAGIC_CLOUDS)(9, BattlefieldBI::MAGIC_PLAINS)(15, BattlefieldBI::ROCKLANDS)
  909. (1, BattlefieldBI::COASTAL);
  910. auto itr = theMap.find(bfieldType);
  911. if(itr != theMap.end())
  912. return itr->second;
  913. return BattlefieldBI::NONE;
  914. }
  915. CStack * BattleInfo::getStack(int stackID, bool onlyAlive /*= true*/)
  916. {
  917. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  918. }
  919. CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive /*= true*/)
  920. {
  921. return const_cast<CStack *>(battleGetStackByPos(tileID, onlyAlive));
  922. }
  923. BattleInfo::BattleInfo()
  924. {
  925. setBattle(this);
  926. setNodeType(BATTLE);
  927. }
  928. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  929. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  930. counterAttacks(1)
  931. {
  932. assert(base);
  933. type = base->type;
  934. count = baseAmount = base->count;
  935. setNodeType(STACK_BATTLE);
  936. }
  937. CStack::CStack()
  938. {
  939. init();
  940. setNodeType(STACK_BATTLE);
  941. }
  942. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  943. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  944. {
  945. type = stack->type;
  946. count = baseAmount = stack->count;
  947. setNodeType(STACK_BATTLE);
  948. }
  949. void CStack::init()
  950. {
  951. base = NULL;
  952. type = NULL;
  953. ID = -1;
  954. count = baseAmount = -1;
  955. firstHPleft = -1;
  956. owner = 255;
  957. slot = 255;
  958. attackerOwned = false;
  959. position = BattleHex();
  960. counterAttacks = -1;
  961. }
  962. void CStack::postInit()
  963. {
  964. assert(type);
  965. assert(getParentNodes().size());
  966. firstHPleft = MaxHealth();
  967. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  968. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  969. casts = valOfBonuses(Bonus::CASTS);
  970. }
  971. ui32 CStack::Speed( int turn /*= 0*/ , bool useBind /* = false*/) const
  972. {
  973. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  974. return 0;
  975. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  976. int percentBonus = 0;
  977. BOOST_FOREACH(const Bonus *b, getBonusList())
  978. {
  979. if(b->type == Bonus::STACKS_SPEED)
  980. {
  981. percentBonus += b->additionalInfo;
  982. }
  983. }
  984. speed = ((100 + percentBonus) * speed)/100;
  985. //bind effect check - doesn't influence stack initiative
  986. if (useBind && getEffect (Spells::BIND))
  987. {
  988. return 0;
  989. }
  990. return speed;
  991. }
  992. si32 CStack::magicResistance() const
  993. {
  994. si32 magicResistance;
  995. if (base) //TODO: make war machines receive aura of magic resistance
  996. {
  997. magicResistance = base->magicResistance();
  998. int auraBonus = 0;
  999. BOOST_FOREACH (const CStack * stack, base->armyObj->battle-> batteAdjacentCreatures(this))
  1000. {
  1001. if (stack->owner == owner)
  1002. {
  1003. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  1004. }
  1005. }
  1006. magicResistance += auraBonus;
  1007. vstd::amin (magicResistance, 100);
  1008. }
  1009. else
  1010. magicResistance = type->magicResistance();
  1011. return magicResistance;
  1012. }
  1013. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  1014. {
  1015. si32 power = VLC->spellh->spells[sse.sid]->powers[sse.val];
  1016. switch(sse.sid)
  1017. {
  1018. case 27: //shield
  1019. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1020. sf.back().sid = sse.sid;
  1021. break;
  1022. case 28: //air shield
  1023. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1024. sf.back().sid = sse.sid;
  1025. break;
  1026. case 29: //fire shield
  1027. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  1028. sf.back().sid = sse.sid;
  1029. break;
  1030. case 30: //protection from air
  1031. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1032. sf.back().sid = sse.sid;
  1033. break;
  1034. case 31: //protection from fire
  1035. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1036. sf.back().sid = sse.sid;
  1037. break;
  1038. case 32: //protection from water
  1039. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  1040. sf.back().sid = sse.sid;
  1041. break;
  1042. case 33: //protection from earth
  1043. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  1044. sf.back().sid = sse.sid;
  1045. break;
  1046. case 34: //anti-magic
  1047. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, GameConstants::SPELL_LEVELS, power - 1, sse.turnsRemain));
  1048. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1049. sf.back().sid = sse.sid;
  1050. break;
  1051. case 36: //magic mirror
  1052. sf.push_back(featureGenerator(Bonus::MAGIC_MIRROR, -1, power, sse.turnsRemain));
  1053. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1054. sf.back().sid = sse.sid;
  1055. case 41: //bless
  1056. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  1057. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1058. sf.back().sid = sse.sid;
  1059. break;
  1060. case 42: //curse
  1061. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  1062. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1063. sf.back().sid = sse.sid;
  1064. break;
  1065. case 43: //bloodlust
  1066. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  1067. sf.back().sid = sse.sid;
  1068. break;
  1069. case 44: //precision
  1070. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  1071. sf.back().sid = sse.sid;
  1072. break;
  1073. case 45: //weakness
  1074. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  1075. sf.back().sid = sse.sid;
  1076. break;
  1077. case 46: //stone skin
  1078. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1079. sf.back().sid = sse.sid;
  1080. break;
  1081. case 47: //disrupting ray
  1082. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  1083. sf.back().sid = sse.sid;
  1084. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1085. break;
  1086. case 48: //prayer
  1087. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1088. sf.back().sid = sse.sid;
  1089. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1090. sf.back().sid = sse.sid;
  1091. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1092. sf.back().sid = sse.sid;
  1093. break;
  1094. case 49: //mirth
  1095. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  1096. sf.back().sid = sse.sid;
  1097. break;
  1098. case 50: //sorrow
  1099. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  1100. sf.back().sid = sse.sid;
  1101. break;
  1102. case 51: //fortune
  1103. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  1104. sf.back().sid = sse.sid;
  1105. break;
  1106. case 52: //misfortune
  1107. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  1108. sf.back().sid = sse.sid;
  1109. break;
  1110. case 53: //haste
  1111. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1112. sf.back().sid = sse.sid;
  1113. break;
  1114. case 54: //slow
  1115. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1116. sf.back().sid = sse.sid;
  1117. break;
  1118. case 55: //slayer
  1119. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  1120. sf.back().sid = sse.sid;
  1121. break;
  1122. case 56: //frenzy
  1123. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  1124. sf.back().sid = sse.sid;
  1125. break;
  1126. case 58: //counterstrike
  1127. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  1128. sf.back().sid = sse.sid;
  1129. break;
  1130. case 59: //bersek
  1131. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  1132. sf.back().sid = sse.sid;
  1133. break;
  1134. case 60: //hypnotize
  1135. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  1136. sf.back().sid = sse.sid;
  1137. break;
  1138. case 61: //forgetfulness
  1139. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  1140. sf.back().sid = sse.sid;
  1141. break;
  1142. case Spells::BLIND: //blind
  1143. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1144. sf.back().sid = sse.sid;
  1145. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1146. sf.back().sid = sse.sid;
  1147. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  1148. sf.back().sid = sse.sid;
  1149. break;
  1150. case Spells::STONE_GAZE: //Stone Gaze
  1151. case Spells::PARALYZE: //Paralyze
  1152. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1153. sf.back().sid = sse.sid;
  1154. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  1155. sf.back().sid = sse.sid;
  1156. break;
  1157. case 71: //Poison
  1158. sf.push_back(featureGeneratorVT(Bonus::POISON, 0, 30, sse.turnsRemain, Bonus::INDEPENDENT_MAX)); //max hp penalty from this source
  1159. sf.back().sid = sse.sid;
  1160. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -10, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1161. sf.back().sid = sse.sid;
  1162. break;
  1163. case 72: //Bind
  1164. sf.push_back(featureGenerator(Bonus::BIND_EFFECT, 0, 0, 1)); //marker
  1165. sf.back().duration = Bonus::PERMANENT;
  1166. sf.back().sid = sse.sid;
  1167. break;
  1168. case 73: //Disease
  1169. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -2 , sse.turnsRemain));
  1170. sf.back().sid = sse.sid;
  1171. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -2 , sse.turnsRemain));
  1172. sf.back().sid = sse.sid;
  1173. break;
  1174. case 75: //Age
  1175. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -50, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1176. sf.back().sid = sse.sid;
  1177. break;
  1178. case 80: //Acid Breath
  1179. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -sse.turnsRemain, 1));
  1180. sf.back().sid = sse.sid;
  1181. sf.back().duration = Bonus::PERMANENT;
  1182. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1183. break;
  1184. }
  1185. }
  1186. bool CStack::willMove(int turn /*= 0*/) const
  1187. {
  1188. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  1189. && !moved(turn)
  1190. && canMove(turn);
  1191. }
  1192. bool CStack::canMove( int turn /*= 0*/ ) const
  1193. {
  1194. return alive()
  1195. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  1196. }
  1197. bool CStack::moved( int turn /*= 0*/ ) const
  1198. {
  1199. if(!turn)
  1200. return vstd::contains(state, EBattleStackState::MOVED);
  1201. else
  1202. return false;
  1203. }
  1204. bool CStack::waited(int turn /*= 0*/) const
  1205. {
  1206. if(!turn)
  1207. return vstd::contains(state, EBattleStackState::WAITING);
  1208. else
  1209. return false;
  1210. }
  1211. bool CStack::doubleWide() const
  1212. {
  1213. return getCreature()->doubleWide;
  1214. }
  1215. BattleHex CStack::occupiedHex() const
  1216. {
  1217. return occupiedHex(position);
  1218. }
  1219. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  1220. {
  1221. if (doubleWide())
  1222. {
  1223. if (attackerOwned)
  1224. return assumedPos - 1;
  1225. else
  1226. return assumedPos + 1;
  1227. }
  1228. else
  1229. {
  1230. return BattleHex::INVALID;
  1231. }
  1232. }
  1233. std::vector<BattleHex> CStack::getHexes() const
  1234. {
  1235. return getHexes(position);
  1236. }
  1237. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  1238. {
  1239. return getHexes(assumedPos, doubleWide(), attackerOwned);
  1240. }
  1241. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  1242. {
  1243. std::vector<BattleHex> hexes;
  1244. hexes.push_back(assumedPos);
  1245. if (twoHex)
  1246. {
  1247. if (AttackerOwned)
  1248. hexes.push_back(assumedPos - 1);
  1249. else
  1250. hexes.push_back(assumedPos + 1);
  1251. }
  1252. return hexes;
  1253. }
  1254. bool CStack::coversPos(BattleHex pos) const
  1255. {
  1256. return vstd::contains(getHexes(), pos);
  1257. }
  1258. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  1259. {
  1260. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  1261. std::vector<BattleHex> hexes;
  1262. if (doubleWide())
  1263. {
  1264. const int WN = GameConstants::BFIELD_WIDTH;
  1265. if(attackerOwned)
  1266. { //position is equal to front hex
  1267. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  1268. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  1269. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  1270. BattleHex::checkAndPush(hex - 2, hexes);
  1271. BattleHex::checkAndPush(hex + 1, hexes);
  1272. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  1273. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1274. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1275. }
  1276. else
  1277. {
  1278. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  1279. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  1280. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  1281. BattleHex::checkAndPush(hex + 2, hexes);
  1282. BattleHex::checkAndPush(hex - 1, hexes);
  1283. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1284. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1285. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  1286. }
  1287. return hexes;
  1288. }
  1289. else
  1290. {
  1291. return hex.neighbouringTiles();
  1292. }
  1293. }
  1294. std::vector<si32> CStack::activeSpells() const
  1295. {
  1296. std::vector<si32> ret;
  1297. TBonusListPtr spellEffects = getSpellBonuses();
  1298. BOOST_FOREACH(const Bonus *it, *spellEffects)
  1299. {
  1300. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  1301. ret.push_back(it->sid);
  1302. }
  1303. return ret;
  1304. }
  1305. CStack::~CStack()
  1306. {
  1307. detachFromAll();
  1308. }
  1309. const CGHeroInstance * CStack::getMyHero() const
  1310. {
  1311. if(base)
  1312. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  1313. else //we are attached directly?
  1314. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  1315. if(n->getNodeType() == HERO)
  1316. return dynamic_cast<const CGHeroInstance *>(n);
  1317. return NULL;
  1318. }
  1319. std::string CStack::nodeName() const
  1320. {
  1321. std::ostringstream oss;
  1322. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  1323. if(type)
  1324. oss << type->namePl;
  1325. else
  1326. oss << "[UNDEFINED TYPE]";
  1327. oss << " from slot " << (int)slot;
  1328. if(base && base->armyObj)
  1329. oss << " of armyobj=" << base->armyObj->id;
  1330. return oss.str();
  1331. }
  1332. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  1333. {
  1334. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  1335. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  1336. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  1337. {
  1338. bsa.killedAmount = count;
  1339. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  1340. return; // no rebirth I believe
  1341. }
  1342. if( firstHPleft <= damageFirst )
  1343. {
  1344. bsa.killedAmount++;
  1345. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  1346. }
  1347. else
  1348. {
  1349. bsa.newHP = firstHPleft - damageFirst;
  1350. }
  1351. if(count <= bsa.killedAmount) //stack killed
  1352. {
  1353. bsa.newAmount = 0;
  1354. bsa.flags |= BattleStackAttacked::KILLED;
  1355. bsa.killedAmount = count; //we cannot kill more creatures than we have
  1356. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  1357. if (resurrectFactor > 0 && casts) //there must be casts left
  1358. {
  1359. int resurrectedCount = base->count * resurrectFactor / 100;
  1360. if (resurrectedCount)
  1361. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  1362. else //only one unit
  1363. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  1364. if (hasBonusOfType(Bonus::REBIRTH, 1))
  1365. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  1366. if (resurrectedCount)
  1367. {
  1368. bsa.flags |= BattleStackAttacked::REBIRTH;
  1369. bsa.newAmount = resurrectedCount; //risky?
  1370. bsa.newHP = MaxHealth(); //resore full health
  1371. }
  1372. }
  1373. }
  1374. else
  1375. {
  1376. bsa.newAmount = count - bsa.killedAmount;
  1377. }
  1378. }
  1379. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  1380. {
  1381. if (!attackerPos.isValid())
  1382. {
  1383. attackerPos = attacker->position;
  1384. }
  1385. if (!defenderPos.isValid())
  1386. {
  1387. defenderPos = defender->position;
  1388. }
  1389. return
  1390. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  1391. || (attacker->doubleWide() //back <=> front
  1392. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  1393. || (defender->doubleWide() //front <=> back
  1394. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  1395. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  1396. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  1397. }
  1398. bool CStack::ableToRetaliate() const
  1399. {
  1400. return alive()
  1401. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  1402. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  1403. && !hasBonusOfType(Bonus::HYPNOTIZED)
  1404. && !hasBonusOfType(Bonus::NO_RETALIATION);
  1405. }
  1406. std::string CStack::getName() const
  1407. {
  1408. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  1409. }
  1410. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  1411. {
  1412. return (alive() || allowDead) && position.isValid();
  1413. }
  1414. bool CStack::canBeHealed() const
  1415. {
  1416. return firstHPleft < MaxHealth()
  1417. && isValidTarget()
  1418. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1419. }
  1420. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1421. {
  1422. switch(phase)
  1423. {
  1424. case 0: //catapult moves after turrets
  1425. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1426. case 1: //fastest first, upper slot first
  1427. {
  1428. int as = a->Speed(turn), bs = b->Speed(turn);
  1429. if(as != bs)
  1430. return as > bs;
  1431. else
  1432. return a->slot < b->slot;
  1433. }
  1434. case 2: //fastest last, upper slot first
  1435. //TODO: should be replaced with order of receiving morale!
  1436. case 3: //fastest last, upper slot first
  1437. {
  1438. int as = a->Speed(turn), bs = b->Speed(turn);
  1439. if(as != bs)
  1440. return as < bs;
  1441. else
  1442. return a->slot < b->slot;
  1443. }
  1444. default:
  1445. assert(0);
  1446. return false;
  1447. }
  1448. }
  1449. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1450. {
  1451. phase = Phase;
  1452. turn = Turn;
  1453. }