BattleState.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. #define VCMI_DLL
  2. #include "BattleState.h"
  3. #include <fstream>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <numeric>
  7. #include <sstream>
  8. #include <boost/foreach.hpp>
  9. #include <boost/assign/list_of.hpp>
  10. #include "VCMI_Lib.h"
  11. #include "CObjectHandler.h"
  12. #include "CHeroHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "CSpellHandler.h"
  15. #include "CTownHandler.h"
  16. #include "NetPacks.h"
  17. /*
  18. * BattleState.h, part of VCMI engine
  19. *
  20. * Authors: listed in file AUTHORS in main folder
  21. *
  22. * License: GNU General Public License v2.0 or later
  23. * Full text of license available in license.txt file, in main folder
  24. *
  25. */
  26. const CStack * BattleInfo::getNextStack() const
  27. {
  28. std::vector<const CStack *> hlp;
  29. getStackQueue(hlp, 1, -1);
  30. if(hlp.size())
  31. return hlp[0];
  32. else
  33. return NULL;
  34. }
  35. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  36. {
  37. const CStack *ret = NULL;
  38. unsigned i, //fastest stack
  39. j; //fastest stack of the other side
  40. for(i = 0; i < st.size(); i++)
  41. if(st[i])
  42. break;
  43. //no stacks left
  44. if(i == st.size())
  45. return NULL;
  46. const CStack *fastest = st[i], *other = NULL;
  47. int bestSpeed = fastest->Speed(turn);
  48. if(fastest->attackerOwned != curside)
  49. {
  50. ret = fastest;
  51. }
  52. else
  53. {
  54. for(j = i + 1; j < st.size(); j++)
  55. {
  56. if(!st[j]) continue;
  57. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  58. break;
  59. }
  60. if(j >= st.size())
  61. {
  62. ret = fastest;
  63. }
  64. else
  65. {
  66. other = st[j];
  67. if(other->Speed(turn) != bestSpeed)
  68. ret = fastest;
  69. else
  70. ret = other;
  71. }
  72. }
  73. assert(ret);
  74. if(ret == fastest)
  75. st[i] = NULL;
  76. else
  77. st[j] = NULL;
  78. curside = ret->attackerOwned;
  79. return ret;
  80. }
  81. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  82. {
  83. for(unsigned int g=0; g<stacks.size(); ++g)
  84. {
  85. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  86. return stacks[g];
  87. }
  88. return NULL;
  89. }
  90. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  91. {
  92. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  93. }
  94. CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive)
  95. {
  96. for(unsigned int g=0; g<stacks.size(); ++g)
  97. {
  98. if(stacks[g]->position == tileID
  99. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  100. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  101. {
  102. if(!onlyAlive || stacks[g]->alive())
  103. {
  104. return stacks[g];
  105. }
  106. }
  107. }
  108. return NULL;
  109. }
  110. const CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive) const
  111. {
  112. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  113. }
  114. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<THex> & occupyable, bool flying, const CStack * stackToOmmit) const
  115. {
  116. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  117. //removing accessibility for side columns of hexes
  118. for(int v = 0; v < BFIELD_SIZE; ++v)
  119. {
  120. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  121. accessibility[v] = false;
  122. }
  123. for(unsigned int g=0; g<stacks.size(); ++g)
  124. {
  125. if(!stacks[g]->alive() || (stackToOmmit && stacks[g]->ID==stackToOmmit->ID) || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  126. continue;
  127. accessibility[stacks[g]->position] = false;
  128. if(stacks[g]->doubleWide()) //if it's a double hex creature
  129. {
  130. if(stacks[g]->attackerOwned)
  131. accessibility[stacks[g]->position-1] = false;
  132. else
  133. accessibility[stacks[g]->position+1] = false;
  134. }
  135. }
  136. //obstacles
  137. for(unsigned int b=0; b<obstacles.size(); ++b)
  138. {
  139. std::vector<THex> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  140. for(unsigned int c=0; c<blocked.size(); ++c)
  141. {
  142. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  143. accessibility[blocked[c]] = false;
  144. }
  145. }
  146. //walls
  147. if(siege > 0)
  148. {
  149. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  150. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  151. {
  152. accessibility[permanentlyLocked[b]] = false;
  153. }
  154. static const std::pair<int, THex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  155. {std::make_pair(2, THex(182)), std::make_pair(3, THex(130)),
  156. std::make_pair(4, THex(62)), std::make_pair(5, THex(29))};
  157. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  158. {
  159. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  160. {
  161. accessibility[lockedIfNotDestroyed[b].second] = false;
  162. }
  163. }
  164. //gate
  165. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  166. {
  167. accessibility[95] = accessibility[96] = false; //block gate's hexes
  168. }
  169. }
  170. //occupyability
  171. if(addOccupiable && twoHex)
  172. {
  173. std::set<THex> rem; //tiles to unlock
  174. for(int h=0; h<BFIELD_HEIGHT; ++h)
  175. {
  176. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  177. {
  178. THex hex(w, h);
  179. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  180. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  181. )
  182. rem.insert(hex);
  183. }
  184. }
  185. occupyable = rem;
  186. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  187. {
  188. accessibility[*it] = true;
  189. }*/
  190. }
  191. }
  192. bool BattleInfo::isAccessible(THex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  193. {
  194. if(flying && !lastPos)
  195. return true;
  196. if(twoHex)
  197. {
  198. //if given hex is accessible and appropriate adjacent one is free too
  199. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  200. }
  201. else
  202. {
  203. return accessibility[hex];
  204. }
  205. }
  206. void BattleInfo::makeBFS(THex start, bool *accessibility, THex *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  207. {
  208. //inits
  209. for(int b=0; b<BFIELD_SIZE; ++b)
  210. predecessor[b] = -1;
  211. for(int g=0; g<BFIELD_SIZE; ++g)
  212. dists[g] = 100000000;
  213. std::queue< std::pair<THex, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  214. hexq.push(std::make_pair(start, true));
  215. dists[hexq.front().first] = 0;
  216. int curNext = -1; //for bfs loop only (helper var)
  217. while(!hexq.empty()) //bfs loop
  218. {
  219. std::pair<THex, bool> curHex = hexq.front();
  220. std::vector<THex> neighbours = curHex.first.neighbouringTiles();
  221. hexq.pop();
  222. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  223. {
  224. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  225. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  226. if( dists[curHex.first]+1 >= dists[curNext] )
  227. continue;
  228. if(accessible && curHex.second)
  229. {
  230. hexq.push(std::make_pair(curNext, true));
  231. dists[curNext] = dists[curHex.first] + 1;
  232. }
  233. else if(fillPredecessors && !(accessible && !curHex.second))
  234. {
  235. hexq.push(std::make_pair(curNext, false));
  236. dists[curNext] = dists[curHex.first] + 1;
  237. }
  238. predecessor[curNext] = curHex.first;
  239. }
  240. }
  241. };
  242. std::vector<THex> BattleInfo::getAccessibility(const CStack * stack, bool addOccupiable) const
  243. {
  244. std::vector<THex> ret;
  245. bool ac[BFIELD_SIZE];
  246. if(stack->position < 0) //turrets
  247. return std::vector<THex>();
  248. std::set<THex> occupyable;
  249. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, addOccupiable, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  250. THex pr[BFIELD_SIZE];
  251. int dist[BFIELD_SIZE];
  252. makeBFS(stack->position, ac, pr, dist, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), false);
  253. if(stack->doubleWide())
  254. {
  255. if(!addOccupiable)
  256. {
  257. std::vector<THex> rem;
  258. for(int b=0; b<BFIELD_SIZE; ++b)
  259. {
  260. //don't take into account most left and most right columns of hexes
  261. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  262. continue;
  263. if( ac[b] && !(stack->attackerOwned ? ac[b-1] : ac[b+1]) )
  264. {
  265. rem.push_back(b);
  266. }
  267. }
  268. for(unsigned int g=0; g<rem.size(); ++g)
  269. {
  270. ac[rem[g]] = false;
  271. }
  272. //removing accessibility for side hexes
  273. for(int v=0; v<BFIELD_SIZE; ++v)
  274. if(stack->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  275. ac[v] = false;
  276. }
  277. }
  278. for (int i=0; i < BFIELD_SIZE ; ++i)
  279. {
  280. bool rangeFits = tacticDistance
  281. ? isInTacticRange(i)
  282. : dist[i] <= stack->Speed();
  283. if( ( !addOccupiable && rangeFits && ac[i] )
  284. || ( addOccupiable && rangeFits && isAccessible(i, ac, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), true) )//we can reach it
  285. || (vstd::contains(occupyable, i) && (!tacticDistance && dist[ i + (stack->attackerOwned ? 1 : -1 ) ] <= stack->Speed() ) && ac[i + (stack->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  286. )
  287. {
  288. ret.push_back(i);
  289. }
  290. }
  291. return ret;
  292. }
  293. bool BattleInfo::isStackBlocked(const CStack * stack) const
  294. {
  295. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  296. return false;
  297. for(unsigned int i=0; i<stacks.size();i++)
  298. {
  299. if( !stacks[i]->alive()
  300. || stacks[i]->owner==stack->owner
  301. )
  302. continue; //we omit dead and allied stacks
  303. if(stacks[i]->doubleWide())
  304. {
  305. if( THex::mutualPosition(stacks[i]->position, stack->position) >= 0
  306. || THex::mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), stack->position) >= 0)
  307. return true;
  308. }
  309. else
  310. {
  311. if( THex::mutualPosition(stacks[i]->position, stack->position) >= 0 )
  312. return true;
  313. }
  314. }
  315. return false;
  316. }
  317. std::pair< std::vector<THex>, int > BattleInfo::getPath(THex start, THex dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  318. {
  319. THex predecessor[BFIELD_SIZE]; //for getting the Path
  320. int dist[BFIELD_SIZE]; //calculated distances
  321. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  322. if(predecessor[dest] == -1) //cannot reach destination
  323. {
  324. return std::make_pair(std::vector<THex>(), 0);
  325. }
  326. //making the Path
  327. std::vector<THex> path;
  328. THex curElem = dest;
  329. while(curElem != start)
  330. {
  331. path.push_back(curElem);
  332. curElem = predecessor[curElem];
  333. }
  334. return std::make_pair(path, dist[dest]);
  335. }
  336. TDmgRange BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount, TQuantity defenderCount, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky ) const
  337. {
  338. float additiveBonus=1.0f, multBonus=1.0f,
  339. minDmg = attacker->getMinDamage() * attackerCount,
  340. maxDmg = attacker->getMaxDamage() * attackerCount;
  341. if(attacker->getCreature()->idNumber == 149) //arrow turret
  342. {
  343. switch(attacker->position)
  344. {
  345. case -2: //keep
  346. minDmg = 15;
  347. maxDmg = 15;
  348. break;
  349. case -3: case -4: //turrets
  350. minDmg = 7.5f;
  351. maxDmg = 7.5f;
  352. break;
  353. }
  354. }
  355. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->getCreature()->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  356. { //minDmg and maxDmg are multiplied by hero attack + 1
  357. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  358. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  359. }
  360. int attackDefenceDifference = 0;
  361. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  362. {
  363. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  364. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  365. }
  366. else
  367. {
  368. attackDefenceDifference = attacker->Attack();
  369. }
  370. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  371. {
  372. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  373. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  374. }
  375. else
  376. {
  377. attackDefenceDifference -= defender->Defense();
  378. }
  379. //calculating total attack/defense skills modifier
  380. if(shooting) //precision handling (etc.)
  381. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  382. else //bloodlust handling (etc.)
  383. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  384. if(attacker->getEffect(55)) //slayer handling
  385. {
  386. std::vector<int> affectedIds;
  387. int spLevel = attacker->getEffect(55)->val;
  388. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  389. {
  390. BOOST_FOREACH(const Bonus *b, VLC->creh->creatures[g]->bonuses)
  391. {
  392. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  393. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  394. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  395. {
  396. affectedIds.push_back(g);
  397. break;
  398. }
  399. }
  400. }
  401. for(unsigned int g=0; g<affectedIds.size(); ++g)
  402. {
  403. if(defender->getCreature()->idNumber == affectedIds[g])
  404. {
  405. attackDefenceDifference += VLC->spellh->spells[55]->powers[attacker->getEffect(55)->val];
  406. break;
  407. }
  408. }
  409. }
  410. //bonus from attack/defense skills
  411. if(attackDefenceDifference < 0) //decreasing dmg
  412. {
  413. float dec = 0.025f * (-attackDefenceDifference);
  414. if(dec > 0.7f)
  415. {
  416. multBonus *= 0.3f; //1.0 - 0.7
  417. }
  418. else
  419. {
  420. multBonus *= 1.0f - dec;
  421. }
  422. }
  423. else //increasing dmg
  424. {
  425. float inc = 0.05f * attackDefenceDifference;
  426. if(inc > 4.0f)
  427. {
  428. additiveBonus += 4.0f;
  429. }
  430. else
  431. {
  432. additiveBonus += inc;
  433. }
  434. }
  435. //applying jousting bonus
  436. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  437. additiveBonus += charge * 0.05f;
  438. //handling secondary abilities and artifacts giving premies to them
  439. if(attackerHero)
  440. {
  441. if(shooting)
  442. {
  443. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARCHERY) / 100.0f;
  444. }
  445. else
  446. {
  447. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::OFFENCE) / 100.0f;
  448. }
  449. }
  450. if(defendingHero)
  451. {
  452. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARMORER))) / 100.0f;
  453. }
  454. //handling hate effect
  455. if( attacker->hasBonusOfType(Bonus::HATE, defender->getCreature()->idNumber) )
  456. additiveBonus += 0.5f;
  457. //luck bonus
  458. if (lucky)
  459. {
  460. additiveBonus += 1.0f;
  461. }
  462. //handling spell effects
  463. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  464. {
  465. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  466. }
  467. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  468. {
  469. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  470. }
  471. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  472. {
  473. multBonus *= 0.8f * float(VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val]); //the second factor is 1 or 0
  474. }
  475. class HLP
  476. {
  477. public:
  478. static bool hasAdvancedAirShield(const CStack * stack)
  479. {
  480. BOOST_FOREACH(const Bonus *it, stack->bonuses)
  481. {
  482. if (it->source == Bonus::SPELL_EFFECT && it->id == 28 && it->val >= 2)
  483. {
  484. return true;
  485. }
  486. }
  487. return false;
  488. }
  489. };
  490. //wall / distance penalty + advanced air shield
  491. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  492. hasDistancePenalty(attacker, defender->position) || hasWallPenalty(attacker, defender->position) ||
  493. HLP::hasAdvancedAirShield(defender) )
  494. )
  495. {
  496. multBonus *= 0.5;
  497. }
  498. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  499. {
  500. multBonus *= 0.5;
  501. }
  502. minDmg *= additiveBonus * multBonus;
  503. maxDmg *= additiveBonus * multBonus;
  504. TDmgRange returnedVal;
  505. if(attacker->getEffect(42)) //curse handling (rest)
  506. {
  507. minDmg -= VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val];
  508. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  509. }
  510. else if(attacker->getEffect(41)) //bless handling
  511. {
  512. maxDmg += VLC->spellh->spells[41]->powers[attacker->getEffect(41)->val];
  513. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  514. }
  515. else
  516. {
  517. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  518. }
  519. //damage cannot be less than 1
  520. amax(returnedVal.first, 1);
  521. amax(returnedVal.second, 1);
  522. return returnedVal;
  523. }
  524. TDmgRange BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky) const
  525. {
  526. return calculateDmgRange(attacker, defender, attacker->count, defender->count, attackerHero, defendingHero, shooting, charge, lucky);
  527. }
  528. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  529. {
  530. TDmgRange range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  531. if(range.first != range.second)
  532. {
  533. int valuesToAverage[10];
  534. int howManyToAv = std::min<ui32>(10, attacker->count);
  535. for (int g=0; g<howManyToAv; ++g)
  536. {
  537. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  538. }
  539. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  540. }
  541. else
  542. return range.first;
  543. }
  544. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  545. {
  546. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  547. {
  548. const CStack * const st = stacks[i];
  549. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  550. amax(killed, 0);
  551. if(killed)
  552. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  553. }
  554. }
  555. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, THex destinationTile )
  556. {
  557. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  558. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  559. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  560. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  561. {
  562. for(int it=0; it<stacks.size(); ++it)
  563. {
  564. if((s->id == 24 && !stacks[it]->getCreature()->isUndead()) //death ripple
  565. || (s->id == 25 && stacks[it]->getCreature()->isUndead()) //destroy undead
  566. || (s->id == 26) //Armageddon
  567. )
  568. {
  569. if(stacks[it]->alive())
  570. attackedCres.insert(stacks[it]);
  571. }
  572. }
  573. }
  574. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  575. {
  576. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  577. {
  578. CStack * st = getStackT(*it, onlyAlive);
  579. if(st)
  580. attackedCres.insert(st);
  581. }
  582. }
  583. else if(VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET_1") != std::string::npos
  584. || VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  585. {
  586. if(skillLevel < 3) /*not expert */
  587. {
  588. CStack * st = getStackT(destinationTile, onlyAlive);
  589. if(st)
  590. attackedCres.insert(st);
  591. }
  592. else
  593. {
  594. for(int it=0; it<stacks.size(); ++it)
  595. {
  596. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  597. if((VLC->spellh->spells[s->id]->positiveness >= 0 && stacks[it]->owner == attackerOwner)
  598. ||(VLC->spellh->spells[s->id]->positiveness <= 0 && stacks[it]->owner != attackerOwner )
  599. )
  600. {
  601. if(!onlyAlive || stacks[it]->alive())
  602. attackedCres.insert(stacks[it]);
  603. }
  604. }
  605. } //if(caster->getSpellSchoolLevel(s) < 3)
  606. }
  607. else if(VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  608. {
  609. CStack * st = getStackT(destinationTile, onlyAlive);
  610. if(st)
  611. attackedCres.insert(st);
  612. }
  613. else //custom range from attackedHexes
  614. {
  615. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  616. {
  617. CStack * st = getStackT(*it, onlyAlive);
  618. if(st)
  619. attackedCres.insert(st);
  620. }
  621. }
  622. return attackedCres;
  623. }
  624. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  625. {
  626. if(!caster) //TODO: something better
  627. return std::max(5, usedSpellPower);
  628. switch(spell->id)
  629. {
  630. case 56: //frenzy
  631. return 1;
  632. default: //other spells
  633. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  634. }
  635. }
  636. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, THex position) const
  637. {
  638. int owner = attackerOwned ? sides[0] : sides[1];
  639. assert(owner >= PLAYER_LIMIT || base.armyObj && base.armyObj->tempOwner == owner);
  640. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  641. ret->position = position;
  642. return ret;
  643. }
  644. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, int stackID, bool attackerOwned, int slot, THex position) const
  645. {
  646. int owner = attackerOwned ? sides[0] : sides[1];
  647. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  648. ret->position = position;
  649. return ret;
  650. }
  651. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  652. {
  653. ui32 ret = caster->getSpellCost(sp);
  654. //checking for friendly stacks reducing cost of the spell and
  655. //enemy stacks increasing it
  656. si32 manaReduction = 0;
  657. si32 manaIncrease = 0;
  658. for(int g=0; g<stacks.size(); ++g)
  659. {
  660. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  661. {
  662. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  663. }
  664. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  665. {
  666. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  667. }
  668. }
  669. return ret + manaReduction + manaIncrease;
  670. }
  671. int BattleInfo::hexToWallPart(THex hex) const
  672. {
  673. if(siege == 0) //there is no battle!
  674. return -1;
  675. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  676. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  677. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  678. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  679. {
  680. if(attackable[g].first == hex)
  681. return attackable[g].second;
  682. }
  683. return -1; //not found!
  684. }
  685. int BattleInfo::lineToWallHex( int line ) const
  686. {
  687. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  688. return lineToHex[line];
  689. }
  690. std::pair<const CStack *, THex> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  691. {
  692. bool ac[BFIELD_SIZE];
  693. std::set<THex> occupyable;
  694. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest);
  695. THex predecessor[BFIELD_SIZE];
  696. int dist[BFIELD_SIZE];
  697. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  698. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  699. for(int g=0; g<BFIELD_SIZE; ++g)
  700. {
  701. const CStack * atG = getStackT(g);
  702. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  703. continue;
  704. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  705. {
  706. if(predecessor[g] == -1) //TODO: is it really the best solution?
  707. continue;
  708. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  709. }
  710. }
  711. if(stackPairs.size() > 0)
  712. {
  713. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  714. minimalPairs.push_back(stackPairs[0]);
  715. for(int b=1; b<stackPairs.size(); ++b)
  716. {
  717. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  718. {
  719. minimalPairs.clear();
  720. minimalPairs.push_back(stackPairs[b]);
  721. }
  722. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  723. {
  724. minimalPairs.push_back(stackPairs[b]);
  725. }
  726. }
  727. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  728. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  729. }
  730. return std::make_pair<const CStack * , THex>(NULL, THex::INVALID);
  731. }
  732. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  733. {
  734. ui32 ret = baseDamage;
  735. //applying sorcery secondary skill
  736. if(caster)
  737. {
  738. ret *= (100.f + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::SORCERY)) / 100.0f;
  739. ret *= (100.f + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0f;
  740. if(sp->air)
  741. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  742. else if(sp->fire) //only one type of bonus for Magic Arrow
  743. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  744. else if(sp->water)
  745. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  746. else if(sp->earth)
  747. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  748. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  749. ret *= (100.f + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0f;
  750. }
  751. return ret;
  752. }
  753. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  754. {
  755. ui32 ret = 0; //value to return
  756. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  757. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  758. //FIXME: what point of dmgMultipliers map? all damage multipliers are already present in CSpell::power
  759. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50)(77, 10);
  760. //check if spell really does damage - if not, return 0
  761. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  762. return 0;
  763. ret = usedSpellPower * dmgMultipliers[sp->id];
  764. ret += sp->powers[spellSchoolLevel];
  765. //affected creature-specific part
  766. if(affectedCreature)
  767. {
  768. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  769. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  770. {
  771. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  772. ret /= 100;
  773. }
  774. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  775. {
  776. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  777. ret /= 100;
  778. }
  779. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  780. {
  781. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  782. ret /= 100;
  783. }
  784. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  785. {
  786. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  787. ret /= 100;
  788. }
  789. //general spell dmg reduction
  790. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  791. {
  792. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  793. ret /= 100;
  794. }
  795. //dmg increasing
  796. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  797. {
  798. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  799. ret /= 100;
  800. }
  801. }
  802. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  803. return ret;
  804. }
  805. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const
  806. {
  807. int powerPerLevel;
  808. bool resurrect;
  809. switch(spell->id)
  810. {
  811. case 37: //cure
  812. {
  813. powerPerLevel = 5;
  814. resurrect = false;
  815. break;
  816. }
  817. case 38: //resurrection
  818. case 39: //animate dead
  819. {
  820. powerPerLevel = 50;
  821. resurrect = true;
  822. break;
  823. }
  824. }
  825. int healedHealth = caster->getPrimSkillLevel(2) * powerPerLevel + spell->powers[caster->getSpellSchoolLevel(spell)];
  826. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  827. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  828. }
  829. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  830. {
  831. //we'll split creatures with remaining movement to 4 parts
  832. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  833. int toMove = 0; //how many stacks still has move
  834. const CStack *active = getStack(activeStack);
  835. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  836. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  837. {
  838. out.push_back(active);
  839. if(out.size() == howMany)
  840. return;
  841. }
  842. for(unsigned int i=0; i<stacks.size(); ++i)
  843. {
  844. const CStack * const s = stacks[i];
  845. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  846. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  847. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  848. {
  849. continue;
  850. }
  851. int p = -1; //in which phase this tack will move?
  852. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  853. {
  854. if(vstd::contains(s->state, HAD_MORALE))
  855. p = 2;
  856. else
  857. p = 3;
  858. }
  859. else if(s->getCreature()->idNumber == 145 || s->getCreature()->idNumber == 149) //catapult and turrets are first
  860. {
  861. p = 0;
  862. }
  863. else
  864. {
  865. p = 1;
  866. }
  867. phase[p].push_back(s);
  868. toMove++;
  869. }
  870. for(int i = 0; i < 4; i++)
  871. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  872. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  873. out.push_back(phase[0][i]);
  874. if(out.size() == howMany)
  875. return;
  876. if(lastMoved == -1)
  877. {
  878. if(active)
  879. {
  880. if(out.size() && out.front() == active)
  881. lastMoved = active->attackerOwned;
  882. else
  883. lastMoved = active->attackerOwned;
  884. }
  885. else
  886. {
  887. lastMoved = 0;
  888. }
  889. }
  890. int pi = 1;
  891. while(out.size() < howMany)
  892. {
  893. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  894. if(!hlp)
  895. {
  896. pi++;
  897. if(pi > 3)
  898. {
  899. //if(turn != 2)
  900. getStackQueue(out, howMany, turn + 1, lastMoved);
  901. return;
  902. }
  903. }
  904. else
  905. {
  906. out.push_back(hlp);
  907. }
  908. }
  909. }
  910. si8 BattleInfo::hasDistancePenalty( const CStack * stack, THex destHex ) const
  911. {
  912. struct HLP
  913. {
  914. static bool lowerAnalyze(const CStack * stack, THex hex)
  915. {
  916. int distance = THex::getDistance(hex, stack->position);
  917. //I hope it's approximately correct
  918. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  919. }
  920. };
  921. const CStack * dstStack = getStackT(destHex, false);
  922. if (dstStack->doubleWide())
  923. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  924. else
  925. return HLP::lowerAnalyze(stack, destHex);
  926. }
  927. si8 BattleInfo::sameSideOfWall(int pos1, int pos2) const
  928. {
  929. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  930. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  931. bool stackLeft = pos1 < wallInStackLine;
  932. bool destLeft = pos2 < wallInDestLine;
  933. return stackLeft != destLeft;
  934. }
  935. si8 BattleInfo::hasWallPenalty( const CStack* stack, THex destHex ) const
  936. {
  937. if (siege == 0)
  938. {
  939. return false;
  940. }
  941. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  942. {
  943. return false;
  944. }
  945. return !sameSideOfWall(stack->position, destHex);
  946. }
  947. si8 BattleInfo::canTeleportTo(const CStack * stack, THex destHex, int telportLevel) const
  948. {
  949. bool ac[BFIELD_SIZE];
  950. std::set<THex> occupyable;
  951. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, false, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  952. if (siege && telportLevel < 2) //check for wall
  953. {
  954. return ac[destHex] && sameSideOfWall(stack->position, destHex);
  955. }
  956. else
  957. {
  958. return ac[destHex];
  959. }
  960. }
  961. // void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  962. // {
  963. // CBonusSystemNode::getBonuses(out, selector, root);
  964. //
  965. // const CStack *dest = dynamic_cast<const CStack*>(root);
  966. // if (!dest)
  967. // return;
  968. //
  969. // //TODO: make it in clean way
  970. // if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  971. // {
  972. // BOOST_FOREACH(const CStack *s, stacks)
  973. // {
  974. // if(s->owner == dest->owner)
  975. // s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  976. // else
  977. // s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  978. // }
  979. // }
  980. // }
  981. bool BattleInfo::battleCanShoot(const CStack * stack, THex dest) const
  982. {
  983. const CStack *dst = getStackT(dest);
  984. if(!stack || !dst) return false;
  985. const CGHeroInstance * stackHero = battleGetOwner(stack);
  986. if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  987. return false;
  988. if(stack->getCreature()->idNumber == 145 && dst) //catapult cannot attack creatures
  989. return false;
  990. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  991. && stack->owner != dst->owner
  992. && dst->alive()
  993. && (!isStackBlocked(stack) || NBonus::hasOfType(stackHero, Bonus::FREE_SHOOTING))
  994. && stack->shots
  995. )
  996. return true;
  997. return false;
  998. }
  999. bool BattleInfo::battleCanFlee(int player) const
  1000. {
  1001. if (player == sides[0])
  1002. {
  1003. if (!heroes[0])
  1004. return false;//current player have no hero
  1005. }
  1006. else
  1007. {
  1008. if (!heroes[1])
  1009. return false;
  1010. }
  1011. if( ( heroes[0] && heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) ) //eg. one of heroes is wearing shakles of war
  1012. || ( heroes[1] && heroes[1]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE)))
  1013. return false;
  1014. if (player == sides[1] && siege //defender in siege
  1015. && !(town->subID == 6 && vstd::contains(town->builtBuildings, 17)))//without escape tunnel
  1016. return false;
  1017. return true;
  1018. }
  1019. const CStack * BattleInfo::battleGetStack(THex pos, bool onlyAlive)
  1020. {
  1021. for(unsigned int g=0; g<stacks.size(); ++g)
  1022. {
  1023. if((stacks[g]->position == pos
  1024. || (stacks[g]->doubleWide()
  1025. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  1026. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  1027. ))
  1028. && (!onlyAlive || stacks[g]->alive())
  1029. )
  1030. return stacks[g];
  1031. }
  1032. return NULL;
  1033. }
  1034. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  1035. {
  1036. return heroes[!stack->attackerOwned];
  1037. }
  1038. si8 BattleInfo::battleMaxSpellLevel() const
  1039. {
  1040. // if(!curB) //there is not battle
  1041. // {
  1042. // tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  1043. // throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  1044. // }
  1045. si8 levelLimit = SPELL_LEVELS;
  1046. const CGHeroInstance *h1 = heroes[0];
  1047. if(h1)
  1048. {
  1049. BOOST_FOREACH(const Bonus *i, h1->bonuses)
  1050. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1051. amin(levelLimit, i->val);
  1052. }
  1053. const CGHeroInstance *h2 = heroes[1];
  1054. if(h2)
  1055. {
  1056. BOOST_FOREACH(const Bonus *i, h2->bonuses)
  1057. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1058. amin(levelLimit, i->val);
  1059. }
  1060. return levelLimit;
  1061. }
  1062. void BattleInfo::localInit()
  1063. {
  1064. belligerents[0]->battle = belligerents[1]->battle = this;
  1065. //TODO: attach battle to belligerents
  1066. BOOST_FOREACH(CStack *s, stacks)
  1067. {
  1068. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  1069. {
  1070. s->attachTo(const_cast<CStackInstance*>(s->base));
  1071. }
  1072. else //attach directly to obj to which stack belongs and creature type
  1073. {
  1074. CArmedInstance *army = belligerents[!s->attackerOwned];
  1075. s->attachTo(army);
  1076. assert(s->type);
  1077. s->attachTo(const_cast<CCreature*>(s->type));
  1078. }
  1079. s->postInit();
  1080. }
  1081. }
  1082. namespace CGH
  1083. {
  1084. using namespace std;
  1085. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1086. {
  1087. for(int j=0; j<7; ++j)
  1088. {
  1089. std::vector<int> pom;
  1090. for(int g=0; g<j+1; ++g)
  1091. {
  1092. int hlp; input>>hlp;
  1093. pom.push_back(hlp);
  1094. }
  1095. dest.push_back(pom);
  1096. }
  1097. }
  1098. }
  1099. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  1100. {
  1101. CMP_stack cmpst;
  1102. BattleInfo *curB = new BattleInfo;
  1103. curB->sides[0] = armies[0]->tempOwner;
  1104. curB->sides[1] = armies[1]->tempOwner;
  1105. if(curB->sides[1] == 254)
  1106. curB->sides[1] = 255;
  1107. std::vector<CStack*> & stacks = (curB->stacks);
  1108. curB->tile = tile;
  1109. curB->battlefieldType = terType;
  1110. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  1111. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  1112. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  1113. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  1114. curB->round = -2;
  1115. curB->activeStack = -1;
  1116. if(town)
  1117. {
  1118. curB->town = town;
  1119. curB->siege = town->fortLevel();
  1120. }
  1121. else
  1122. {
  1123. curB->town = NULL;
  1124. curB->siege = 0;
  1125. }
  1126. //reading battleStartpos
  1127. std::ifstream positions;
  1128. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1129. if(!positions.is_open())
  1130. {
  1131. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1132. }
  1133. std::string dump;
  1134. positions>>dump; positions>>dump;
  1135. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1136. CGH::readItTo(positions, attackerLoose);
  1137. positions>>dump;
  1138. CGH::readItTo(positions, defenderLoose);
  1139. positions>>dump;
  1140. positions>>dump;
  1141. CGH::readItTo(positions, attackerTight);
  1142. positions>>dump;
  1143. CGH::readItTo(positions, defenderTight);
  1144. positions>>dump;
  1145. positions>>dump;
  1146. CGH::readItTo(positions, attackerCreBank);
  1147. positions>>dump;
  1148. CGH::readItTo(positions, defenderCreBank);
  1149. positions.close();
  1150. //battleStartpos read
  1151. int k = 0; //stack serial
  1152. for(TSlots::const_iterator i = armies[0]->Slots().begin(); i!=armies[0]->Slots().end(); i++, k++)
  1153. {
  1154. int pos;
  1155. if(creatureBank)
  1156. pos = attackerCreBank[armies[0]->stacksCount()-1][k];
  1157. else if(armies[0]->formation)
  1158. pos = attackerTight[armies[0]->stacksCount()-1][k];
  1159. else
  1160. pos = attackerLoose[armies[0]->stacksCount()-1][k];
  1161. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), true, i->first, pos);
  1162. stacks.push_back(stack);
  1163. }
  1164. k = 0;
  1165. for(TSlots::const_iterator i = armies[1]->Slots().begin(); i!=armies[1]->Slots().end(); i++, k++)
  1166. {
  1167. int pos;
  1168. if(creatureBank)
  1169. pos = defenderCreBank[armies[1]->stacksCount()-1][k];
  1170. else if(armies[1]->formation)
  1171. pos = defenderTight[armies[1]->stacksCount()-1][k];
  1172. else
  1173. pos = defenderLoose[armies[1]->stacksCount()-1][k];
  1174. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), false, i->first, pos);
  1175. stacks.push_back(stack);
  1176. }
  1177. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1178. {
  1179. //we should do that for creature bank too
  1180. if(stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1181. {
  1182. stacks[g]->position += THex::RIGHT;
  1183. }
  1184. else if(stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1185. {
  1186. stacks[g]->position += THex::LEFT;
  1187. }
  1188. }
  1189. //adding war machines
  1190. if(heroes[0])
  1191. {
  1192. if(heroes[0]->getArt(13)) //ballista
  1193. {
  1194. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), true, 255, 52);
  1195. stacks.push_back(stack);
  1196. }
  1197. if(heroes[0]->getArt(14)) //ammo cart
  1198. {
  1199. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), true, 255, 18);
  1200. stacks.push_back(stack);
  1201. }
  1202. if(heroes[0]->getArt(15)) //first aid tent
  1203. {
  1204. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), true, 255, 154);
  1205. stacks.push_back(stack);
  1206. }
  1207. }
  1208. if(heroes[1])
  1209. {
  1210. //defending hero shouldn't receive ballista (bug #551)
  1211. if(heroes[1]->getArt(13) && !town) //ballista
  1212. {
  1213. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), false, 255, 66);
  1214. stacks.push_back(stack);
  1215. }
  1216. if(heroes[1]->getArt(14)) //ammo cart
  1217. {
  1218. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), false, 255, 32);
  1219. stacks.push_back(stack);
  1220. }
  1221. if(heroes[1]->getArt(15)) //first aid tent
  1222. {
  1223. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), false, 255, 168);
  1224. stacks.push_back(stack);
  1225. }
  1226. }
  1227. if(town && heroes[0] && town->hasFort()) //catapult
  1228. {
  1229. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(145, 1), stacks.size(), true, 255, 120);
  1230. stacks.push_back(stack);
  1231. }
  1232. //war machines added
  1233. switch(curB->siege) //adding towers
  1234. {
  1235. case 3: //castle
  1236. {//lower tower / upper tower
  1237. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -4);
  1238. stacks.push_back(stack);
  1239. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -3);
  1240. stacks.push_back(stack);
  1241. }
  1242. case 2: //citadel
  1243. {//main tower
  1244. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -2);
  1245. stacks.push_back(stack);
  1246. }
  1247. }
  1248. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1249. //seting up siege
  1250. if(town && town->hasFort())
  1251. {
  1252. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1253. {
  1254. curB->si.wallState[b] = 1;
  1255. }
  1256. }
  1257. //randomize obstacles
  1258. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1259. {
  1260. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1261. std::vector<int> possibleObstacles;
  1262. for(int i=0; i<BFIELD_SIZE; ++i)
  1263. {
  1264. if(i%17 < 4 || i%17 > 12)
  1265. {
  1266. obAv[i] = false;
  1267. }
  1268. else
  1269. {
  1270. obAv[i] = true;
  1271. }
  1272. }
  1273. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1274. {
  1275. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1276. {
  1277. possibleObstacles.push_back(g->first);
  1278. }
  1279. }
  1280. srand(time(NULL));
  1281. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1282. {
  1283. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1284. while(toBlock>0)
  1285. {
  1286. CObstacleInstance coi;
  1287. coi.uniqueID = curB->obstacles.size();
  1288. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1289. coi.pos = rand()%BFIELD_SIZE;
  1290. std::vector<THex> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1291. bool badObstacle = false;
  1292. for(int b=0; b<block.size(); ++b)
  1293. {
  1294. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1295. {
  1296. badObstacle = true;
  1297. break;
  1298. }
  1299. }
  1300. if(badObstacle) continue;
  1301. //obstacle can be placed
  1302. curB->obstacles.push_back(coi);
  1303. for(int b=0; b<block.size(); ++b)
  1304. {
  1305. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1306. obAv[block[b]] = false;
  1307. }
  1308. toBlock -= block.size();
  1309. }
  1310. }
  1311. }
  1312. // //giving building bonuses, if siege and we have harrisoned hero
  1313. // if (town)
  1314. // {
  1315. // if (heroes[1])
  1316. // {
  1317. // for (int i=0; i<4; i++)
  1318. // {
  1319. // int val = town->defenceBonus(i);
  1320. // if (val)
  1321. // {
  1322. // GiveBonus gs;
  1323. // gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::OBJECT, val, -1, "", i);
  1324. // gs.id = heroes[1]->id;
  1325. // sendAndApply(&gs);
  1326. // }
  1327. // }
  1328. // }
  1329. // else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1330. // {
  1331. // if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1332. // for(int g=0; g<stacks.size(); ++g)
  1333. // stacks[g]->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1334. //
  1335. // else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1336. // for(int g=0; g<stacks.size(); ++g)
  1337. // stacks[g]->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TOWN_STRUCTURE));
  1338. //
  1339. // if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1340. // for(int g=0; g<stacks.size(); ++g)
  1341. // stacks[g]->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1342. // }
  1343. // }
  1344. //giving terrain overalay premies
  1345. int bonusSubtype = -1;
  1346. switch(terType)
  1347. {
  1348. case 9: //magic plains
  1349. {
  1350. bonusSubtype = 0;
  1351. }
  1352. case 14: //fiery fields
  1353. {
  1354. if(bonusSubtype == -1) bonusSubtype = 1;
  1355. }
  1356. case 15: //rock lands
  1357. {
  1358. if(bonusSubtype == -1) bonusSubtype = 8;
  1359. }
  1360. case 16: //magic clouds
  1361. {
  1362. if(bonusSubtype == -1) bonusSubtype = 2;
  1363. }
  1364. case 17: //lucid pools
  1365. {
  1366. if(bonusSubtype == -1) bonusSubtype = 4;
  1367. }
  1368. { //common part for cases 9, 14, 15, 16, 17
  1369. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  1370. break;
  1371. }
  1372. case 18: //holy ground
  1373. {
  1374. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1375. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1376. break;
  1377. }
  1378. case 19: //clover field
  1379. { //+2 luck bonus for neutral creatures
  1380. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureFactionLimiter(-1)));
  1381. break;
  1382. }
  1383. case 20: //evil fog
  1384. {
  1385. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1386. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1387. break;
  1388. }
  1389. case 22: //cursed ground
  1390. {
  1391. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1392. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1393. curB->addNewBonus(makeFeature(Bonus::BLOCK_SPELLS_ABOVE_LEVEL, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1394. break;
  1395. }
  1396. }
  1397. //overlay premies given
  1398. //native terrain bonuses
  1399. if(town) //during siege always take premies for native terrain of faction
  1400. terrain = VLC->heroh->nativeTerrains[town->town->typeID];
  1401. ILimiter *nativeTerrain = new CreatureNativeTerrainLimiter(terrain);
  1402. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1403. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1404. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1405. //////////////////////////////////////////////////////////////////////////
  1406. int tacticLvls[2] = {0};
  1407. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  1408. {
  1409. if(heroes[i])
  1410. tacticLvls[i] += heroes[i]->getSecSkillLevel(CGHeroInstance::TACTICS);
  1411. }
  1412. if(int diff = tacticLvls[0] - tacticLvls[1])
  1413. {
  1414. curB->tacticsSide = diff < 0;
  1415. curB->tacticDistance = std::abs(diff)*2 + 1;
  1416. }
  1417. return curB;
  1418. }
  1419. bool BattleInfo::isInTacticRange( THex dest ) const
  1420. {
  1421. return ((tacticsSide && dest.getX() > 0 && dest.getX() <= tacticDistance)
  1422. || (!tacticsSide && dest.getX() < BFIELD_WIDTH - 1 && dest.getX() >= BFIELD_WIDTH - tacticDistance - 1));
  1423. }
  1424. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  1425. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  1426. counterAttacks(1)
  1427. {
  1428. assert(base);
  1429. type = base->type;
  1430. count = baseAmount = base->count;
  1431. nodeType = STACK_BATTLE;
  1432. }
  1433. CStack::CStack()
  1434. {
  1435. init();
  1436. nodeType = STACK_BATTLE;
  1437. }
  1438. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  1439. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  1440. {
  1441. type = stack->type;
  1442. count = baseAmount = stack->count;
  1443. nodeType = STACK_BATTLE;
  1444. }
  1445. void CStack::init()
  1446. {
  1447. base = NULL;
  1448. type = NULL;
  1449. ID = -1;
  1450. count = baseAmount = -1;
  1451. firstHPleft = -1;
  1452. owner = 255;
  1453. slot = 255;
  1454. attackerOwned = false;
  1455. position = THex();
  1456. counterAttacks = -1;
  1457. }
  1458. void CStack::postInit()
  1459. {
  1460. assert(type);
  1461. assert(parents.size());
  1462. firstHPleft = valOfBonuses(Bonus::STACK_HEALTH);
  1463. shots = getCreature()->shots;
  1464. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  1465. state.insert(ALIVE); //alive state indication
  1466. assert(firstHPleft > 0);
  1467. }
  1468. ui32 CStack::Speed( int turn /*= 0*/ ) const
  1469. {
  1470. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  1471. return 0;
  1472. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  1473. int percentBonus = 0;
  1474. BOOST_FOREACH(const Bonus *b, bonuses)
  1475. {
  1476. if(b->type == Bonus::STACKS_SPEED)
  1477. {
  1478. percentBonus += b->additionalInfo;
  1479. }
  1480. }
  1481. speed = ((100 + percentBonus) * speed)/100;
  1482. //bind effect check
  1483. if(getEffect(72))
  1484. {
  1485. return 0;
  1486. }
  1487. return speed;
  1488. }
  1489. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  1490. {
  1491. BOOST_FOREACH(Bonus *it, bonuses)
  1492. {
  1493. if(it->source == Bonus::SPELL_EFFECT && it->id == id)
  1494. {
  1495. if(!turn || it->turnsRemain > turn)
  1496. return &(*it);
  1497. }
  1498. }
  1499. return NULL;
  1500. }
  1501. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  1502. {
  1503. si32 power = VLC->spellh->spells[sse.id]->powers[sse.val];
  1504. //why, why, WHY this code is here?!?
  1505. // Bonus * bonus = getBonus(Selector::typeSybtype(Bonus::SPECIAL_PECULIAR_ENCHANT, sse.id));
  1506. // if (bonus)
  1507. // {
  1508. // switch(bonus->additionalInfo)
  1509. // {
  1510. // case 0: //normal
  1511. // switch(type->level)
  1512. // {
  1513. // case 1: case 2:
  1514. // power += 3; //it doesn't necessarily make sense for some spells, use it wisely
  1515. // break;
  1516. // case 3: case 4:
  1517. // power += 2;
  1518. // break;
  1519. // case 5: case 6:
  1520. // power += 1;
  1521. // break;
  1522. // }
  1523. // break;
  1524. // case 1: //only Coronius as yet
  1525. // power = std::max(5 - type->level, 0);
  1526. // break;
  1527. // }
  1528. // }
  1529. switch(sse.id)
  1530. {
  1531. case 27: //shield
  1532. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1533. sf.back().id = sse.id;
  1534. break;
  1535. case 28: //air shield
  1536. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1537. sf.back().id = sse.id;
  1538. break;
  1539. case 29: //fire shield
  1540. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  1541. sf.back().id = sse.id;
  1542. break;
  1543. case 30: //protection from air
  1544. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1545. sf.back().id = sse.id;
  1546. break;
  1547. case 31: //protection from fire
  1548. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1549. sf.back().id = sse.id;
  1550. break;
  1551. case 32: //protection from water
  1552. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  1553. sf.back().id = sse.id;
  1554. break;
  1555. case 33: //protection from earth
  1556. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  1557. sf.back().id = sse.id;
  1558. break;
  1559. case 34: //anti-magic
  1560. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, 0, power - 1, sse.turnsRemain));
  1561. sf.back().id = sse.id;
  1562. break;
  1563. case 41: //bless
  1564. // if (hasBonusOfType(Bonus::SPECIAL_BLESS_DAMAGE, 41)) //TODO: better handling of bonus percentages
  1565. // {
  1566. // int damagePercent = dynamic_cast<const CGHeroInstance*>(armyObj)->level * valOfBonuses(Bonus::SPECIAL_BLESS_DAMAGE, 41) / type->level;
  1567. // sf.push_back(featureGenerator(Bonus::CREATURE_DAMAGE, 0, damagePercent, sse.turnsRemain));
  1568. // sf.back().id = sse.id;
  1569. // sf.back().valType = Bonus::PERCENT_TO_ALL;
  1570. // }
  1571. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  1572. sf.back().id = sse.id;
  1573. break;
  1574. case 42: //curse
  1575. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, -1 * power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  1576. sf.back().id = sse.id;
  1577. break;
  1578. case 43: //bloodlust
  1579. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  1580. sf.back().id = sse.id;
  1581. break;
  1582. case 44: //precision
  1583. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  1584. sf.back().id = sse.id;
  1585. break;
  1586. case 45: //weakness
  1587. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  1588. sf.back().id = sse.id;
  1589. break;
  1590. case 46: //stone skin
  1591. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1592. sf.back().id = sse.id;
  1593. break;
  1594. case 47: //disrupting ray
  1595. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  1596. sf.back().id = sse.id;
  1597. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1598. break;
  1599. case 48: //prayer
  1600. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1601. sf.back().id = sse.id;
  1602. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1603. sf.back().id = sse.id;
  1604. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1605. sf.back().id = sse.id;
  1606. break;
  1607. case 49: //mirth
  1608. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  1609. sf.back().id = sse.id;
  1610. break;
  1611. case 50: //sorrow
  1612. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  1613. sf.back().id = sse.id;
  1614. break;
  1615. case 51: //fortune
  1616. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  1617. sf.back().id = sse.id;
  1618. break;
  1619. case 52: //misfortune
  1620. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  1621. sf.back().id = sse.id;
  1622. break;
  1623. case 53: //haste
  1624. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1625. sf.back().id = sse.id;
  1626. break;
  1627. case 54: //slow
  1628. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1629. sf.back().id = sse.id;
  1630. break;
  1631. case 55: //slayer
  1632. // if (bonus) //Coronius
  1633. // {
  1634. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1635. // sf.back().id = sse.id;
  1636. // }
  1637. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  1638. sf.back().id = sse.id;
  1639. break;
  1640. case 56: //frenzy
  1641. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  1642. sf.back().id = sse.id;
  1643. break;
  1644. case 58: //counterstrike
  1645. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  1646. sf.back().id = sse.id;
  1647. break;
  1648. case 59: //bersek
  1649. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  1650. sf.back().id = sse.id;
  1651. break;
  1652. case 60: //hypnotize
  1653. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  1654. sf.back().id = sse.id;
  1655. break;
  1656. case 61: //forgetfulness
  1657. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  1658. sf.back().id = sse.id;
  1659. break;
  1660. case 62: //blind
  1661. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, 0, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1662. sf.back().id = sse.id;
  1663. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1664. sf.back().id = sse.id;
  1665. break;
  1666. }
  1667. }
  1668. ui8 CStack::howManyEffectsSet(ui16 id) const
  1669. {
  1670. ui8 ret = 0;
  1671. BOOST_FOREACH(const Bonus *it, bonuses)
  1672. if(it->source == Bonus::SPELL_EFFECT && it->id == id) //effect found
  1673. {
  1674. ++ret;
  1675. }
  1676. return ret;
  1677. }
  1678. bool CStack::willMove(int turn /*= 0*/) const
  1679. {
  1680. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  1681. && !moved(turn)
  1682. && canMove(turn);
  1683. }
  1684. bool CStack::canMove( int turn /*= 0*/ ) const
  1685. {
  1686. return alive()
  1687. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  1688. }
  1689. bool CStack::moved( int turn /*= 0*/ ) const
  1690. {
  1691. if(!turn)
  1692. return vstd::contains(state, MOVED);
  1693. else
  1694. return false;
  1695. }
  1696. bool CStack::doubleWide() const
  1697. {
  1698. return getCreature()->doubleWide;
  1699. }
  1700. THex CStack::occupiedHex() const
  1701. {
  1702. if (doubleWide())
  1703. {
  1704. if (attackerOwned)
  1705. return position - 1;
  1706. else
  1707. return position + 1;
  1708. }
  1709. else
  1710. {
  1711. return THex::INVALID;
  1712. }
  1713. }
  1714. BonusList CStack::getSpellBonuses() const
  1715. {
  1716. return getBonuses(Selector::sourceTypeSel(Bonus::SPELL_EFFECT));
  1717. }
  1718. std::vector<si32> CStack::activeSpells() const
  1719. {
  1720. std::vector<si32> ret;
  1721. BonusList spellEffects = getSpellBonuses();
  1722. BOOST_FOREACH(const Bonus *it, spellEffects)
  1723. {
  1724. if (!vstd::contains(ret, it->id)) //do not duplicate spells with multiple effects
  1725. ret.push_back(it->id);
  1726. }
  1727. return ret;
  1728. }
  1729. CStack::~CStack()
  1730. {
  1731. detachFromAll();
  1732. if(vstd::contains(state, SUMMONED))
  1733. delNull(base);
  1734. }
  1735. const CGHeroInstance * CStack::getMyHero() const
  1736. {
  1737. if(base)
  1738. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  1739. else //we are attached directly?
  1740. BOOST_FOREACH(const CBonusSystemNode *n, parents)
  1741. if(n->nodeType == HERO)
  1742. dynamic_cast<const CGHeroInstance *>(n);
  1743. return NULL;
  1744. }
  1745. std::string CStack::nodeName() const
  1746. {
  1747. std::ostringstream oss;
  1748. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  1749. if(type)
  1750. oss << type->namePl;
  1751. else
  1752. oss << "[UNDEFINED TYPE]";
  1753. oss << " from slot " << (int)slot;
  1754. if(base && base->armyObj)
  1755. oss << " of armyobj=" << base->armyObj->id;
  1756. return oss.str();
  1757. }
  1758. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  1759. {
  1760. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  1761. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  1762. if( firstHPleft <= damageFirst )
  1763. {
  1764. bsa.killedAmount++;
  1765. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  1766. }
  1767. else
  1768. {
  1769. bsa.newHP = firstHPleft - damageFirst;
  1770. }
  1771. if(count <= bsa.killedAmount) //stack killed
  1772. {
  1773. bsa.newAmount = 0;
  1774. bsa.flags |= 1;
  1775. bsa.killedAmount = count; //we cannot kill more creatures than we have
  1776. }
  1777. else
  1778. {
  1779. bsa.newAmount = count - bsa.killedAmount;
  1780. }
  1781. }
  1782. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, THex attackerPos /*= THex::INVALID*/, THex defenderPos /*= THex::INVALID*/)
  1783. {
  1784. if (!attackerPos.isValid())
  1785. {
  1786. attackerPos = attacker->position;
  1787. }
  1788. if (!defenderPos.isValid())
  1789. {
  1790. defenderPos = defender->position;
  1791. }
  1792. return
  1793. (THex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  1794. || (attacker->doubleWide() //back <=> front
  1795. && THex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  1796. || (defender->doubleWide() //front <=> back
  1797. && THex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  1798. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  1799. && THex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  1800. }
  1801. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1802. {
  1803. switch(phase)
  1804. {
  1805. case 0: //catapult moves after turrets
  1806. return a->getCreature()->idNumber < b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1807. //TODO? turrets order
  1808. case 1: //fastest first, upper slot first
  1809. {
  1810. int as = a->Speed(turn), bs = b->Speed(turn);
  1811. if(as != bs)
  1812. return as > bs;
  1813. else
  1814. return a->slot < b->slot;
  1815. }
  1816. case 2: //fastest last, upper slot first
  1817. //TODO: should be replaced with order of receiving morale!
  1818. case 3: //fastest last, upper slot first
  1819. {
  1820. int as = a->Speed(turn), bs = b->Speed(turn);
  1821. if(as != bs)
  1822. return as < bs;
  1823. else
  1824. return a->slot < b->slot;
  1825. }
  1826. default:
  1827. assert(0);
  1828. return false;
  1829. }
  1830. }
  1831. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1832. {
  1833. phase = Phase;
  1834. turn = Turn;
  1835. }