BattleState.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  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. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  1014. {
  1015. BOOST_FOREACH(Bonus *it, getBonusList())
  1016. {
  1017. if(it->source == Bonus::SPELL_EFFECT && it->sid == id)
  1018. {
  1019. if(!turn || it->turnsRemain > turn)
  1020. return &(*it);
  1021. }
  1022. }
  1023. return NULL;
  1024. }
  1025. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  1026. {
  1027. si32 power = VLC->spellh->spells[sse.sid]->powers[sse.val];
  1028. switch(sse.sid)
  1029. {
  1030. case 27: //shield
  1031. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1032. sf.back().sid = sse.sid;
  1033. break;
  1034. case 28: //air shield
  1035. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1036. sf.back().sid = sse.sid;
  1037. break;
  1038. case 29: //fire shield
  1039. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  1040. sf.back().sid = sse.sid;
  1041. break;
  1042. case 30: //protection from air
  1043. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1044. sf.back().sid = sse.sid;
  1045. break;
  1046. case 31: //protection from fire
  1047. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1048. sf.back().sid = sse.sid;
  1049. break;
  1050. case 32: //protection from water
  1051. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  1052. sf.back().sid = sse.sid;
  1053. break;
  1054. case 33: //protection from earth
  1055. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  1056. sf.back().sid = sse.sid;
  1057. break;
  1058. case 34: //anti-magic
  1059. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, GameConstants::SPELL_LEVELS, power - 1, sse.turnsRemain));
  1060. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1061. sf.back().sid = sse.sid;
  1062. break;
  1063. case 36: //magic mirror
  1064. sf.push_back(featureGenerator(Bonus::MAGIC_MIRROR, -1, power, sse.turnsRemain));
  1065. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1066. sf.back().sid = sse.sid;
  1067. case 41: //bless
  1068. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  1069. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1070. sf.back().sid = sse.sid;
  1071. break;
  1072. case 42: //curse
  1073. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  1074. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1075. sf.back().sid = sse.sid;
  1076. break;
  1077. case 43: //bloodlust
  1078. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  1079. sf.back().sid = sse.sid;
  1080. break;
  1081. case 44: //precision
  1082. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  1083. sf.back().sid = sse.sid;
  1084. break;
  1085. case 45: //weakness
  1086. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  1087. sf.back().sid = sse.sid;
  1088. break;
  1089. case 46: //stone skin
  1090. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1091. sf.back().sid = sse.sid;
  1092. break;
  1093. case 47: //disrupting ray
  1094. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  1095. sf.back().sid = sse.sid;
  1096. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1097. break;
  1098. case 48: //prayer
  1099. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1100. sf.back().sid = sse.sid;
  1101. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1102. sf.back().sid = sse.sid;
  1103. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1104. sf.back().sid = sse.sid;
  1105. break;
  1106. case 49: //mirth
  1107. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  1108. sf.back().sid = sse.sid;
  1109. break;
  1110. case 50: //sorrow
  1111. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  1112. sf.back().sid = sse.sid;
  1113. break;
  1114. case 51: //fortune
  1115. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  1116. sf.back().sid = sse.sid;
  1117. break;
  1118. case 52: //misfortune
  1119. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  1120. sf.back().sid = sse.sid;
  1121. break;
  1122. case 53: //haste
  1123. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1124. sf.back().sid = sse.sid;
  1125. break;
  1126. case 54: //slow
  1127. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1128. sf.back().sid = sse.sid;
  1129. break;
  1130. case 55: //slayer
  1131. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  1132. sf.back().sid = sse.sid;
  1133. break;
  1134. case 56: //frenzy
  1135. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  1136. sf.back().sid = sse.sid;
  1137. break;
  1138. case 58: //counterstrike
  1139. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  1140. sf.back().sid = sse.sid;
  1141. break;
  1142. case 59: //bersek
  1143. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  1144. sf.back().sid = sse.sid;
  1145. break;
  1146. case 60: //hypnotize
  1147. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  1148. sf.back().sid = sse.sid;
  1149. break;
  1150. case 61: //forgetfulness
  1151. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  1152. sf.back().sid = sse.sid;
  1153. break;
  1154. case Spells::BLIND: //blind
  1155. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1156. sf.back().sid = sse.sid;
  1157. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1158. sf.back().sid = sse.sid;
  1159. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  1160. sf.back().sid = sse.sid;
  1161. break;
  1162. case Spells::STONE_GAZE: //Stone Gaze
  1163. case Spells::PARALYZE: //Paralyze
  1164. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1165. sf.back().sid = sse.sid;
  1166. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  1167. sf.back().sid = sse.sid;
  1168. break;
  1169. case 71: //Poison
  1170. sf.push_back(featureGeneratorVT(Bonus::POISON, 0, 30, sse.turnsRemain, Bonus::INDEPENDENT_MAX)); //max hp penalty from this source
  1171. sf.back().sid = sse.sid;
  1172. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -10, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1173. sf.back().sid = sse.sid;
  1174. break;
  1175. case 72: //Bind
  1176. sf.push_back(featureGenerator(Bonus::BIND_EFFECT, 0, 0, 1)); //marker
  1177. sf.back().duration = Bonus::PERMANENT;
  1178. sf.back().sid = sse.sid;
  1179. break;
  1180. case 73: //Disease
  1181. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -2 , sse.turnsRemain));
  1182. sf.back().sid = sse.sid;
  1183. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -2 , sse.turnsRemain));
  1184. sf.back().sid = sse.sid;
  1185. break;
  1186. case 75: //Age
  1187. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -50, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1188. sf.back().sid = sse.sid;
  1189. break;
  1190. case 80: //Acid Breath
  1191. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -sse.turnsRemain, 1));
  1192. sf.back().sid = sse.sid;
  1193. sf.back().duration = Bonus::PERMANENT;
  1194. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1195. break;
  1196. }
  1197. }
  1198. ui8 CStack::howManyEffectsSet(ui16 id) const
  1199. {
  1200. ui8 ret = 0;
  1201. BOOST_FOREACH(const Bonus *it, getBonusList())
  1202. if(it->source == Bonus::SPELL_EFFECT && it->sid == id) //effect found
  1203. {
  1204. ++ret;
  1205. }
  1206. return ret;
  1207. }
  1208. bool CStack::willMove(int turn /*= 0*/) const
  1209. {
  1210. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  1211. && !moved(turn)
  1212. && canMove(turn);
  1213. }
  1214. bool CStack::canMove( int turn /*= 0*/ ) const
  1215. {
  1216. return alive()
  1217. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  1218. }
  1219. bool CStack::moved( int turn /*= 0*/ ) const
  1220. {
  1221. if(!turn)
  1222. return vstd::contains(state, EBattleStackState::MOVED);
  1223. else
  1224. return false;
  1225. }
  1226. bool CStack::doubleWide() const
  1227. {
  1228. return getCreature()->doubleWide;
  1229. }
  1230. BattleHex CStack::occupiedHex() const
  1231. {
  1232. return occupiedHex(position);
  1233. }
  1234. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  1235. {
  1236. if (doubleWide())
  1237. {
  1238. if (attackerOwned)
  1239. return assumedPos - 1;
  1240. else
  1241. return assumedPos + 1;
  1242. }
  1243. else
  1244. {
  1245. return BattleHex::INVALID;
  1246. }
  1247. }
  1248. std::vector<BattleHex> CStack::getHexes() const
  1249. {
  1250. return getHexes(position);
  1251. }
  1252. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  1253. {
  1254. return getHexes(assumedPos, doubleWide(), attackerOwned);
  1255. }
  1256. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  1257. {
  1258. std::vector<BattleHex> hexes;
  1259. hexes.push_back(assumedPos);
  1260. if (twoHex)
  1261. {
  1262. if (AttackerOwned)
  1263. hexes.push_back(assumedPos - 1);
  1264. else
  1265. hexes.push_back(assumedPos + 1);
  1266. }
  1267. return hexes;
  1268. }
  1269. bool CStack::coversPos(BattleHex pos) const
  1270. {
  1271. return vstd::contains(getHexes(), pos);
  1272. }
  1273. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  1274. {
  1275. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  1276. std::vector<BattleHex> hexes;
  1277. if (doubleWide())
  1278. {
  1279. const int WN = GameConstants::BFIELD_WIDTH;
  1280. if(attackerOwned)
  1281. { //position is equal to front hex
  1282. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+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 - 2, hexes);
  1286. BattleHex::checkAndPush(hex + 1, hexes);
  1287. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  1288. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1289. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1290. }
  1291. else
  1292. {
  1293. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  1294. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  1295. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  1296. BattleHex::checkAndPush(hex + 2, hexes);
  1297. BattleHex::checkAndPush(hex - 1, hexes);
  1298. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1299. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1300. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  1301. }
  1302. return hexes;
  1303. }
  1304. else
  1305. {
  1306. return hex.neighbouringTiles();
  1307. }
  1308. }
  1309. std::vector<si32> CStack::activeSpells() const
  1310. {
  1311. std::vector<si32> ret;
  1312. TBonusListPtr spellEffects = getSpellBonuses();
  1313. BOOST_FOREACH(const Bonus *it, *spellEffects)
  1314. {
  1315. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  1316. ret.push_back(it->sid);
  1317. }
  1318. return ret;
  1319. }
  1320. CStack::~CStack()
  1321. {
  1322. detachFromAll();
  1323. }
  1324. const CGHeroInstance * CStack::getMyHero() const
  1325. {
  1326. if(base)
  1327. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  1328. else //we are attached directly?
  1329. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  1330. if(n->getNodeType() == HERO)
  1331. return dynamic_cast<const CGHeroInstance *>(n);
  1332. return NULL;
  1333. }
  1334. std::string CStack::nodeName() const
  1335. {
  1336. std::ostringstream oss;
  1337. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  1338. if(type)
  1339. oss << type->namePl;
  1340. else
  1341. oss << "[UNDEFINED TYPE]";
  1342. oss << " from slot " << (int)slot;
  1343. if(base && base->armyObj)
  1344. oss << " of armyobj=" << base->armyObj->id;
  1345. return oss.str();
  1346. }
  1347. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  1348. {
  1349. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  1350. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  1351. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  1352. {
  1353. bsa.killedAmount = count;
  1354. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  1355. return; // no rebirth I believe
  1356. }
  1357. if( firstHPleft <= damageFirst )
  1358. {
  1359. bsa.killedAmount++;
  1360. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  1361. }
  1362. else
  1363. {
  1364. bsa.newHP = firstHPleft - damageFirst;
  1365. }
  1366. if(count <= bsa.killedAmount) //stack killed
  1367. {
  1368. bsa.newAmount = 0;
  1369. bsa.flags |= BattleStackAttacked::KILLED;
  1370. bsa.killedAmount = count; //we cannot kill more creatures than we have
  1371. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  1372. if (resurrectFactor > 0 && casts) //there must be casts left
  1373. {
  1374. int resurrectedCount = base->count * resurrectFactor / 100;
  1375. if (resurrectedCount)
  1376. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  1377. else //only one unit
  1378. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  1379. if (hasBonusOfType(Bonus::REBIRTH, 1))
  1380. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  1381. if (resurrectedCount)
  1382. {
  1383. bsa.flags |= BattleStackAttacked::REBIRTH;
  1384. bsa.newAmount = resurrectedCount; //risky?
  1385. bsa.newHP = MaxHealth(); //resore full health
  1386. }
  1387. }
  1388. }
  1389. else
  1390. {
  1391. bsa.newAmount = count - bsa.killedAmount;
  1392. }
  1393. }
  1394. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  1395. {
  1396. if (!attackerPos.isValid())
  1397. {
  1398. attackerPos = attacker->position;
  1399. }
  1400. if (!defenderPos.isValid())
  1401. {
  1402. defenderPos = defender->position;
  1403. }
  1404. return
  1405. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  1406. || (attacker->doubleWide() //back <=> front
  1407. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  1408. || (defender->doubleWide() //front <=> back
  1409. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  1410. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  1411. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  1412. }
  1413. bool CStack::ableToRetaliate() const
  1414. {
  1415. return alive()
  1416. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  1417. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  1418. && !hasBonusOfType(Bonus::HYPNOTIZED)
  1419. && !hasBonusOfType(Bonus::NO_RETALIATION);
  1420. }
  1421. std::string CStack::getName() const
  1422. {
  1423. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  1424. }
  1425. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  1426. {
  1427. return (alive() || allowDead) && position.isValid();
  1428. }
  1429. bool CStack::canBeHealed() const
  1430. {
  1431. return firstHPleft < MaxHealth()
  1432. && isValidTarget()
  1433. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1434. }
  1435. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1436. {
  1437. switch(phase)
  1438. {
  1439. case 0: //catapult moves after turrets
  1440. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1441. case 1: //fastest first, upper slot first
  1442. {
  1443. int as = a->Speed(turn), bs = b->Speed(turn);
  1444. if(as != bs)
  1445. return as > bs;
  1446. else
  1447. return a->slot < b->slot;
  1448. }
  1449. case 2: //fastest last, upper slot first
  1450. //TODO: should be replaced with order of receiving morale!
  1451. case 3: //fastest last, upper slot first
  1452. {
  1453. int as = a->Speed(turn), bs = b->Speed(turn);
  1454. if(as != bs)
  1455. return as < bs;
  1456. else
  1457. return a->slot < b->slot;
  1458. }
  1459. default:
  1460. assert(0);
  1461. return false;
  1462. }
  1463. }
  1464. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1465. {
  1466. phase = Phase;
  1467. turn = Turn;
  1468. }