BattleState.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888
  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 "../lib/JsonNode.h"
  13. /*
  14. * BattleState.h, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. extern boost::rand48 ran;
  23. const CStack * BattleInfo::getNextStack() const
  24. {
  25. std::vector<const CStack *> hlp;
  26. getStackQueue(hlp, 1, -1);
  27. if(hlp.size())
  28. return hlp[0];
  29. else
  30. return NULL;
  31. }
  32. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  33. {
  34. const CStack *ret = NULL;
  35. unsigned i, //fastest stack
  36. j; //fastest stack of the other side
  37. for(i = 0; i < st.size(); i++)
  38. if(st[i])
  39. break;
  40. //no stacks left
  41. if(i == st.size())
  42. return NULL;
  43. const CStack *fastest = st[i], *other = NULL;
  44. int bestSpeed = fastest->Speed(turn);
  45. if(fastest->attackerOwned != curside)
  46. {
  47. ret = fastest;
  48. }
  49. else
  50. {
  51. for(j = i + 1; j < st.size(); j++)
  52. {
  53. if(!st[j]) continue;
  54. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  55. break;
  56. }
  57. if(j >= st.size())
  58. {
  59. ret = fastest;
  60. }
  61. else
  62. {
  63. other = st[j];
  64. if(other->Speed(turn) != bestSpeed)
  65. ret = fastest;
  66. else
  67. ret = other;
  68. }
  69. }
  70. assert(ret);
  71. if(ret == fastest)
  72. st[i] = NULL;
  73. else
  74. st[j] = NULL;
  75. curside = ret->attackerOwned;
  76. return ret;
  77. }
  78. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  79. {
  80. for(ui32 g=0; g<stacks.size(); ++g)
  81. {
  82. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  83. return stacks[g];
  84. }
  85. return NULL;
  86. }
  87. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  88. {
  89. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  90. }
  91. CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive)
  92. {
  93. for(ui32 g=0; g<stacks.size(); ++g)
  94. {
  95. if(stacks[g]->position == tileID
  96. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  97. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  98. {
  99. if(!onlyAlive || stacks[g]->alive())
  100. {
  101. return stacks[g];
  102. }
  103. }
  104. }
  105. return NULL;
  106. }
  107. const CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive) const
  108. {
  109. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  110. }
  111. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<BattleHex> & occupyable, bool flying, const CStack * stackToOmmit) const
  112. {
  113. memset(accessibility, 1, GameConstants::BFIELD_SIZE); //initialize array with trues
  114. //removing accessibility for side columns of hexes
  115. for(int v = 0; v < GameConstants::BFIELD_SIZE; ++v)
  116. {
  117. if( v % GameConstants::BFIELD_WIDTH == 0 || v % GameConstants::BFIELD_WIDTH == (GameConstants::BFIELD_WIDTH - 1) )
  118. accessibility[v] = false;
  119. }
  120. for(ui32 g=0; g<stacks.size(); ++g)
  121. {
  122. 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)
  123. continue;
  124. accessibility[stacks[g]->position] = false;
  125. if(stacks[g]->doubleWide()) //if it's a double hex creature
  126. {
  127. if(stacks[g]->attackerOwned)
  128. accessibility[stacks[g]->position-1] = false;
  129. else
  130. accessibility[stacks[g]->position+1] = false;
  131. }
  132. }
  133. //obstacles
  134. for(ui32 b=0; b<obstacles.size(); ++b)
  135. {
  136. std::vector<BattleHex> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  137. for(ui32 c=0; c<blocked.size(); ++c)
  138. {
  139. if(blocked[c] >=0 && blocked[c] < GameConstants::BFIELD_SIZE)
  140. accessibility[blocked[c]] = false;
  141. }
  142. }
  143. //walls
  144. if(siege > 0)
  145. {
  146. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  147. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  148. {
  149. accessibility[permanentlyLocked[b]] = false;
  150. }
  151. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  152. {std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
  153. std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
  154. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  155. {
  156. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  157. {
  158. accessibility[lockedIfNotDestroyed[b].second] = false;
  159. }
  160. }
  161. //gate
  162. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  163. {
  164. accessibility[95] = accessibility[96] = false; //block gate's hexes
  165. }
  166. }
  167. //occupyability
  168. if(addOccupiable && twoHex)
  169. {
  170. std::set<BattleHex> rem; //tiles to unlock
  171. for(int h=0; h<GameConstants::BFIELD_HEIGHT; ++h)
  172. {
  173. for(int w=1; w<GameConstants::BFIELD_WIDTH-1; ++w)
  174. {
  175. BattleHex hex(w, h);
  176. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  177. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  178. )
  179. rem.insert(hex);
  180. }
  181. }
  182. occupyable = rem;
  183. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  184. {
  185. accessibility[*it] = true;
  186. }*/
  187. }
  188. }
  189. bool BattleInfo::isAccessible(BattleHex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  190. {
  191. if(flying && !lastPos)
  192. return true;
  193. if(twoHex)
  194. {
  195. //if given hex is accessible and appropriate adjacent one is free too
  196. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  197. }
  198. else
  199. {
  200. return accessibility[hex];
  201. }
  202. }
  203. void BattleInfo::makeBFS(BattleHex start, bool *accessibility, BattleHex *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  204. {
  205. //inits
  206. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  207. predecessor[b] = -1;
  208. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  209. dists[g] = 100000000;
  210. std::queue< std::pair<BattleHex, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  211. hexq.push(std::make_pair(start, true));
  212. dists[hexq.front().first] = 0;
  213. int curNext = -1; //for bfs loop only (helper var)
  214. while(!hexq.empty()) //bfs loop
  215. {
  216. std::pair<BattleHex, bool> curHex = hexq.front();
  217. std::vector<BattleHex> neighbours = curHex.first.neighbouringTiles();
  218. hexq.pop();
  219. for(ui32 nr=0; nr<neighbours.size(); nr++)
  220. {
  221. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  222. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  223. if( dists[curHex.first]+1 >= dists[curNext] )
  224. continue;
  225. if(accessible && curHex.second)
  226. {
  227. hexq.push(std::make_pair(curNext, true));
  228. dists[curNext] = dists[curHex.first] + 1;
  229. }
  230. else if(fillPredecessors && !(accessible && !curHex.second))
  231. {
  232. hexq.push(std::make_pair(curNext, false));
  233. dists[curNext] = dists[curHex.first] + 1;
  234. }
  235. predecessor[curNext] = curHex.first;
  236. }
  237. }
  238. };
  239. std::vector<BattleHex> BattleInfo::getAccessibility( const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable ) const
  240. {
  241. std::vector<BattleHex> ret;
  242. bool ac[GameConstants::BFIELD_SIZE];
  243. if(stack->position < 0) //turrets
  244. return std::vector<BattleHex>();
  245. std::set<BattleHex> occupyable;
  246. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, addOccupiable, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  247. BattleHex pr[GameConstants::BFIELD_SIZE];
  248. int dist[GameConstants::BFIELD_SIZE];
  249. makeBFS(stack->position, ac, pr, dist, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), false);
  250. if(stack->doubleWide())
  251. {
  252. if(!addOccupiable)
  253. {
  254. std::vector<BattleHex> rem;
  255. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  256. {
  257. //don't take into account most left and most right columns of hexes
  258. if( b % GameConstants::BFIELD_WIDTH == 0 || b % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1 )
  259. continue;
  260. if( ac[b] && !(stack->attackerOwned ? ac[b-1] : ac[b+1]) )
  261. {
  262. rem.push_back(b);
  263. }
  264. }
  265. for(ui32 g=0; g<rem.size(); ++g)
  266. {
  267. ac[rem[g]] = false;
  268. }
  269. //removing accessibility for side hexes
  270. for(int v=0; v<GameConstants::BFIELD_SIZE; ++v)
  271. if(stack->attackerOwned ? (v%GameConstants::BFIELD_WIDTH)==1 : (v%GameConstants::BFIELD_WIDTH)==(GameConstants::BFIELD_WIDTH - 2))
  272. ac[v] = false;
  273. }
  274. }
  275. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  276. {
  277. bool rangeFits;
  278. if (tacticDistance)
  279. rangeFits = isInTacticRange(i);
  280. else
  281. rangeFits = dist[i] <= stack->Speed(0, true); //we can reach the stack
  282. if( ( !addOccupiable && rangeFits && ac[i] )
  283. || ( addOccupiable && rangeFits && isAccessible(i, ac, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), true) )//we can reach it
  284. || (vstd::contains(occupyable, i) && (!tacticDistance && dist[ i + (stack->attackerOwned ? 1 : -1 ) ] <= stack->Speed(0, true) ) && ac[i + (stack->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  285. )
  286. {
  287. ret.push_back(i);
  288. }
  289. }
  290. if(attackable)
  291. {
  292. struct HLP
  293. {
  294. static bool meleeAttackable(BattleHex hex, const std::vector<BattleHex> & baseRng)
  295. {
  296. BOOST_FOREACH(BattleHex h, baseRng)
  297. {
  298. if(BattleHex::mutualPosition(h, hex) > 0)
  299. return true;
  300. }
  301. return false;
  302. }
  303. };
  304. BOOST_FOREACH(const CStack * otherSt, stacks)
  305. {
  306. if(otherSt->owner == stack->owner || !otherSt->isValidTarget(false))
  307. continue;
  308. std::vector<BattleHex> occupiedBySecond;
  309. occupiedBySecond.push_back(otherSt->position);
  310. if(otherSt->doubleWide())
  311. occupiedBySecond.push_back(otherSt->occupiedHex());
  312. if(battleCanShoot(stack, otherSt->position))
  313. {
  314. attackable->insert(attackable->end(), occupiedBySecond.begin(), occupiedBySecond.end());
  315. continue;
  316. }
  317. BOOST_FOREACH(BattleHex he, occupiedBySecond)
  318. {
  319. if(HLP::meleeAttackable(he, ret))
  320. attackable->push_back(he);
  321. }
  322. }
  323. }
  324. return ret;
  325. }
  326. int BattleInfo::getAvaliableHex(TCreature creID, bool attackerOwned, int initialPos) const
  327. {
  328. int pos;
  329. if (initialPos > -1)
  330. pos = initialPos;
  331. else
  332. {
  333. if (attackerOwned)
  334. pos = 0; //top left
  335. else
  336. pos = GameConstants::BFIELD_WIDTH; //top right
  337. }
  338. bool ac[GameConstants::BFIELD_SIZE];
  339. std::set<BattleHex> occupyable;
  340. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  341. bool flying = VLC->creh->creatures[creID]->isFlying();// vstd::contains(VLC->creh->creatures[creID]->bonuses, Bonus::FLYING);
  342. getAccessibilityMap(ac, twoHex, attackerOwned, true, occupyable, flying);
  343. for (int g = pos; (-1 < g) && (g < GameConstants::BFIELD_SIZE); )
  344. {
  345. if ((g % GameConstants::BFIELD_WIDTH != 0) && (g % GameConstants::BFIELD_WIDTH != GameConstants::BFIELD_WIDTH-1) && BattleInfo::isAccessible (g, ac, twoHex, attackerOwned, flying, true))
  346. {
  347. pos = g;
  348. break;
  349. }
  350. if (attackerOwned)
  351. ++g; //probably some more sophisticated range-based iteration is needed
  352. else
  353. --g;
  354. }
  355. return pos;
  356. }
  357. bool BattleInfo::isStackBlocked(const CStack * stack) const
  358. {
  359. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  360. return false;
  361. BOOST_FOREACH(CStack * s, getAdjacentCreatures(stack))
  362. {
  363. if (s->owner != stack->owner) //blocked by enemy stack
  364. return true;
  365. }
  366. return false;
  367. }
  368. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  369. {
  370. BattleHex predecessor[GameConstants::BFIELD_SIZE]; //for getting the Path
  371. int dist[GameConstants::BFIELD_SIZE]; //calculated distances
  372. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  373. if(predecessor[dest] == -1) //cannot reach destination
  374. {
  375. return std::make_pair(std::vector<BattleHex>(), 0);
  376. }
  377. //making the Path
  378. std::vector<BattleHex> path;
  379. BattleHex curElem = dest;
  380. while(curElem != start)
  381. {
  382. path.push_back(curElem);
  383. curElem = predecessor[curElem];
  384. }
  385. return std::make_pair(path, dist[dest]);
  386. }
  387. TDmgRange BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount, TQuantity defenderCount, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  388. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg ) const
  389. {
  390. double additiveBonus = 1.0, multBonus = 1.0,
  391. minDmg = attacker->getMinDamage() * attackerCount,
  392. maxDmg = attacker->getMaxDamage() * attackerCount;
  393. if(attacker->getCreature()->idNumber == 149) //arrow turret
  394. {
  395. switch(attacker->position)
  396. {
  397. case -2: //keep
  398. minDmg = 15;
  399. maxDmg = 15;
  400. break;
  401. case -3: case -4: //turrets
  402. minDmg = 7.5;
  403. maxDmg = 7.5;
  404. break;
  405. }
  406. }
  407. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->getCreature()->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  408. { //minDmg and maxDmg are multiplied by hero attack + 1
  409. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  410. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  411. }
  412. int attackDefenceDifference = 0;
  413. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  414. {
  415. double multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0;
  416. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  417. }
  418. else
  419. {
  420. attackDefenceDifference = attacker->Attack();
  421. }
  422. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  423. {
  424. double multDefenceReduction = (100 - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0;
  425. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  426. }
  427. else
  428. {
  429. attackDefenceDifference -= defender->Defense();
  430. }
  431. //calculating total attack/defense skills modifier
  432. if(shooting) //precision handling (etc.)
  433. attackDefenceDifference += attacker->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT))->totalValue();
  434. else //bloodlust handling (etc.)
  435. attackDefenceDifference += attacker->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT))->totalValue();
  436. if(attacker->getEffect(55)) //slayer handling
  437. {
  438. std::vector<int> affectedIds;
  439. int spLevel = attacker->getEffect(55)->val;
  440. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  441. {
  442. BOOST_FOREACH(const Bonus *b, VLC->creh->creatures[g]->getBonusList())
  443. {
  444. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  445. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  446. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  447. {
  448. affectedIds.push_back(g);
  449. break;
  450. }
  451. }
  452. }
  453. for(ui32 g=0; g<affectedIds.size(); ++g)
  454. {
  455. if(defender->getCreature()->idNumber == affectedIds[g])
  456. {
  457. attackDefenceDifference += VLC->spellh->spells[55]->powers[attacker->getEffect(55)->val];
  458. break;
  459. }
  460. }
  461. }
  462. //bonus from attack/defense skills
  463. if(attackDefenceDifference < 0) //decreasing dmg
  464. {
  465. double dec = 0.025 * (-attackDefenceDifference);
  466. if(dec > 0.7)
  467. {
  468. multBonus *= 0.3; //1.0 - 0.7
  469. }
  470. else
  471. {
  472. multBonus *= 1.0 - dec;
  473. }
  474. }
  475. else //increasing dmg
  476. {
  477. double inc = 0.05 * attackDefenceDifference;
  478. if(inc > 4.0)
  479. {
  480. additiveBonus += 4.0;
  481. }
  482. else
  483. {
  484. additiveBonus += inc;
  485. }
  486. }
  487. //applying jousting bonus
  488. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  489. additiveBonus += charge * 0.05;
  490. //handling secondary abilities and artifacts giving premies to them
  491. if(attackerHero)
  492. {
  493. if(shooting)
  494. {
  495. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARCHERY) / 100.0;
  496. }
  497. else
  498. {
  499. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::OFFENCE) / 100.0;
  500. }
  501. }
  502. if(defendingHero)
  503. {
  504. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARMORER))) / 100.0;
  505. }
  506. //handling hate effect
  507. additiveBonus += attacker->valOfBonuses(Bonus::HATE, defender->getCreature()->idNumber) / 100.;
  508. //luck bonus
  509. if (lucky)
  510. {
  511. additiveBonus += 1.0;
  512. }
  513. //ballista double dmg
  514. if(ballistaDoubleDmg)
  515. {
  516. additiveBonus += 1.0;
  517. }
  518. if (deathBlow) //Dread Knight and many WoGified creatures
  519. {
  520. additiveBonus += 1.0;
  521. }
  522. //handling spell effects
  523. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  524. {
  525. multBonus *= defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0) / 100.0;
  526. }
  527. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  528. {
  529. multBonus *= defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1) / 100.0;
  530. }
  531. TBonusListPtr curseEffects = attacker->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE)); //attacker->getEffect(42);
  532. TBonusListPtr blessEffects = attacker->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE)); //attacker->getEffect(43);
  533. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  534. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo))->additionalInfo : 0;
  535. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  536. {
  537. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  538. }
  539. class HLP
  540. {
  541. public:
  542. static bool hasAdvancedAirShield(const CStack * stack)
  543. {
  544. BOOST_FOREACH(const Bonus *it, stack->getBonusList())
  545. {
  546. if (it->source == Bonus::SPELL_EFFECT && it->sid == 28 && it->val >= 2)
  547. {
  548. return true;
  549. }
  550. }
  551. return false;
  552. }
  553. };
  554. //wall / distance penalty + advanced air shield
  555. bool distPenalty = !NBonus::hasOfType(attackerHero, Bonus::NO_DISTANCE_PENALTY) &&
  556. hasDistancePenalty(attacker, defender->position);
  557. bool obstaclePenalty = hasWallPenalty(attacker, defender->position);
  558. if (shooting)
  559. {
  560. if (distPenalty || HLP::hasAdvancedAirShield(defender))
  561. {
  562. multBonus *= 0.5;
  563. }
  564. if (obstaclePenalty)
  565. {
  566. multBonus *= 0.5; //cumulative
  567. }
  568. }
  569. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  570. {
  571. multBonus *= 0.5;
  572. }
  573. minDmg *= additiveBonus * multBonus;
  574. maxDmg *= additiveBonus * multBonus;
  575. TDmgRange returnedVal;
  576. if(curseEffects->size()) //curse handling (rest)
  577. {
  578. minDmg += curseBlessAdditiveModifier;
  579. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  580. }
  581. else if(blessEffects->size()) //bless handling
  582. {
  583. maxDmg += curseBlessAdditiveModifier;
  584. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  585. }
  586. else
  587. {
  588. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  589. }
  590. //damage cannot be less than 1
  591. vstd::amax(returnedVal.first, 1);
  592. vstd::amax(returnedVal.second, 1);
  593. return returnedVal;
  594. }
  595. TDmgRange BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  596. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg) const
  597. {
  598. return calculateDmgRange(attacker, defender, attacker->count, defender->count, attackerHero, defendingHero, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  599. }
  600. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  601. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg )
  602. {
  603. TDmgRange range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  604. if(range.first != range.second)
  605. {
  606. int valuesToAverage[10];
  607. int howManyToAv = std::min<ui32>(10, attacker->count);
  608. for (int g=0; g<howManyToAv; ++g)
  609. {
  610. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  611. }
  612. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  613. }
  614. else
  615. return range.first;
  616. }
  617. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  618. {
  619. for(ui32 i=0; i<stacks.size();i++)//setting casualties
  620. {
  621. const CStack * const st = stacks[i];
  622. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  623. vstd::amax(killed, 0);
  624. if(killed)
  625. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  626. }
  627. }
  628. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, BattleHex destinationTile )
  629. {
  630. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  631. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  632. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  633. if(s->id == Spells::DEATH_RIPPLE || s->id == Spells::DESTROY_UNDEAD || s->id == Spells::ARMAGEDDON)
  634. {
  635. for(int it=0; it<stacks.size(); ++it)
  636. {
  637. if((s->id == Spells::DEATH_RIPPLE && !stacks[it]->getCreature()->isUndead()) //death ripple
  638. || (s->id == Spells::DESTROY_UNDEAD && stacks[it]->getCreature()->isUndead()) //destroy undead
  639. || (s->id == Spells::ARMAGEDDON) //Armageddon
  640. )
  641. {
  642. if(stacks[it]->isValidTarget())
  643. attackedCres.insert(stacks[it]);
  644. }
  645. }
  646. }
  647. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  648. {
  649. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  650. {
  651. CStack * st = getStackT(*it, onlyAlive);
  652. if(st)
  653. {
  654. if (s->id == 76) //Death Cloud //TODO: fireball and fire immunity
  655. {
  656. if (st->isLiving() || st->coversPos(destinationTile)) //directly hit or alive
  657. {
  658. attackedCres.insert(st);
  659. }
  660. }
  661. else
  662. attackedCres.insert(st);
  663. }
  664. }
  665. }
  666. else if(s->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  667. {
  668. if(skillLevel < 3) /*not expert */
  669. {
  670. CStack * st = getStackT(destinationTile, onlyAlive);
  671. if(st)
  672. attackedCres.insert(st);
  673. }
  674. else
  675. {
  676. for(int it=0; it<stacks.size(); ++it)
  677. {
  678. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  679. if((!s->isNegative() && stacks[it]->owner == attackerOwner)
  680. ||(!s->isPositive() && stacks[it]->owner != attackerOwner )
  681. )
  682. {
  683. if(stacks[it]->isValidTarget(!onlyAlive))
  684. attackedCres.insert(stacks[it]);
  685. }
  686. }
  687. } //if(caster->getSpellSchoolLevel(s) < 3)
  688. }
  689. else if(s->getTargetType() == CSpell::CREATURE)
  690. {
  691. CStack * st = getStackT(destinationTile, onlyAlive);
  692. if(st)
  693. attackedCres.insert(st);
  694. }
  695. else //custom range from attackedHexes
  696. {
  697. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  698. {
  699. CStack * st = getStackT(*it, onlyAlive);
  700. if(st)
  701. attackedCres.insert(st);
  702. }
  703. }
  704. return attackedCres;
  705. }
  706. void BattleInfo::getPotentiallyAttackableHexes(AttackableTiles &at, const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  707. {
  708. const int WN = GameConstants::BFIELD_WIDTH;
  709. ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  710. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  711. {
  712. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  713. BOOST_FOREACH (BattleHex tile, hexes)
  714. {
  715. at.hostileCreaturePositions.insert(tile);
  716. }
  717. }
  718. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  719. {
  720. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  721. BOOST_FOREACH (BattleHex tile, hexes)
  722. {
  723. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, hex) > -1) //adjacent both to attacker's head and attacked tile
  724. || tile == destinationTile) //or simply attacked directly
  725. {
  726. CStack * st = getStackT(tile, true);
  727. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  728. {
  729. at.hostileCreaturePositions.insert(tile);
  730. }
  731. }
  732. }
  733. }
  734. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  735. {
  736. std::vector<BattleHex> hexes; //only one, in fact
  737. int pseudoVector = destinationTile.hex - hex;
  738. switch (pseudoVector)
  739. {
  740. case 1:
  741. case -1:
  742. BattleHex::checkAndPush(destinationTile.hex + pseudoVector, hexes);
  743. break;
  744. case WN: //17
  745. case WN + 1: //18
  746. case -WN: //-17
  747. case -WN + 1: //-16
  748. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : -1 ), hexes);
  749. break;
  750. case WN-1: //16
  751. case -WN-1: //-18
  752. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : 0), hexes);
  753. break;
  754. }
  755. BOOST_FOREACH (BattleHex tile, hexes)
  756. {
  757. CStack * st = getStackT(tile, true);
  758. if(st) //friendly stacks can also be damaged by Dragon Breath
  759. {
  760. at.friendlyCreaturePositions.insert(tile);
  761. }
  762. }
  763. }
  764. }
  765. std::set<CStack*> BattleInfo::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  766. { //TODO: caching?
  767. AttackableTiles at;
  768. getPotentiallyAttackableHexes(at, attacker, destinationTile, attackerPos);
  769. std::set<CStack*> attackedCres;
  770. BOOST_FOREACH (BattleHex tile, at.hostileCreaturePositions) //all around & three-headed attack
  771. {
  772. CStack * st = getStackT(tile, true);
  773. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  774. {
  775. attackedCres.insert(st);
  776. }
  777. }
  778. BOOST_FOREACH (BattleHex tile, at.friendlyCreaturePositions)
  779. {
  780. CStack * st = getStackT(tile, true);
  781. if(st) //friendly stacks can also be damaged by Dragon Breath
  782. {
  783. attackedCres.insert(st);
  784. }
  785. }
  786. return attackedCres;
  787. }
  788. std::set<BattleHex> BattleInfo::getAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  789. {
  790. AttackableTiles at;
  791. getPotentiallyAttackableHexes(at, attacker, destinationTile, attackerPos);
  792. std::set<BattleHex> attackedHexes;
  793. BOOST_FOREACH (BattleHex tile, at.hostileCreaturePositions)
  794. {
  795. CStack * st = getStackT(tile, true);
  796. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  797. {
  798. attackedHexes.insert(tile);
  799. }
  800. }
  801. BOOST_FOREACH (BattleHex tile, at.friendlyCreaturePositions)
  802. {
  803. CStack * st = getStackT(tile, true);
  804. if(st) //friendly stacks can also be damaged by Dragon Breath
  805. {
  806. attackedHexes.insert(tile);
  807. }
  808. }
  809. return attackedHexes;
  810. }
  811. std::set<CStack*> BattleInfo::getAdjacentCreatures (const CStack * stack) const
  812. {
  813. std::set<CStack*> stacks;
  814. CStack * localStack;
  815. BOOST_FOREACH (BattleHex hex, stack->getSurroundingHexes())
  816. {
  817. localStack = const_cast<CStack*>(getStackT(hex, true)); //only alive?
  818. if (localStack)
  819. stacks.insert(localStack);
  820. }
  821. return stacks;
  822. }
  823. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower)
  824. {
  825. if(!caster)
  826. {
  827. if (!usedSpellPower)
  828. return 3; //default duration of all creature spells
  829. else
  830. return usedSpellPower; //use creature spell power
  831. }
  832. switch(spell->id)
  833. {
  834. case Spells::FRENZY:
  835. return 1;
  836. default: //other spells
  837. return caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  838. }
  839. }
  840. CStack * BattleInfo::generateNewStack(const CStackInstance &base, bool attackerOwned, int slot, BattleHex position) const
  841. {
  842. int stackID = getIdForNewStack();
  843. int owner = attackerOwned ? sides[0] : sides[1];
  844. assert((owner >= GameConstants::PLAYER_LIMIT) ||
  845. (base.armyObj && base.armyObj->tempOwner == owner));
  846. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  847. ret->position = position;
  848. return ret;
  849. }
  850. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, int slot, BattleHex position) const
  851. {
  852. int stackID = getIdForNewStack();
  853. int owner = attackerOwned ? sides[0] : sides[1];
  854. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  855. ret->position = position;
  856. return ret;
  857. }
  858. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  859. {
  860. ui32 ret = caster->getSpellCost(sp);
  861. //checking for friendly stacks reducing cost of the spell and
  862. //enemy stacks increasing it
  863. si32 manaReduction = 0;
  864. si32 manaIncrease = 0;
  865. for(int g=0; g<stacks.size(); ++g)
  866. {
  867. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  868. {
  869. vstd::amax(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  870. }
  871. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  872. {
  873. vstd::amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  874. }
  875. }
  876. return ret - manaReduction + manaIncrease;
  877. }
  878. int BattleInfo::hexToWallPart(BattleHex hex) const
  879. {
  880. if(siege == 0) //there is no battle!
  881. return -1;
  882. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  883. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  884. 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),
  885. std::make_pair(45, -2), std::make_pair(78, -2), std::make_pair(112, -2), std::make_pair(147, -2)}; // -2 - indestructible walls
  886. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  887. {
  888. if(attackable[g].first == hex)
  889. return attackable[g].second;
  890. }
  891. return -1; //not found!
  892. }
  893. int BattleInfo::lineToWallHex( int line ) const
  894. {
  895. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  896. return lineToHex[line];
  897. }
  898. std::pair<const CStack *, BattleHex> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  899. {
  900. bool ac[GameConstants::BFIELD_SIZE];
  901. std::set<BattleHex> occupyable;
  902. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest);
  903. BattleHex predecessor[GameConstants::BFIELD_SIZE];
  904. int dist[GameConstants::BFIELD_SIZE];
  905. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  906. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  907. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  908. {
  909. const CStack * atG = getStackT(g);
  910. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  911. continue;
  912. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  913. {
  914. if(predecessor[g] == -1) //TODO: is it really the best solution?
  915. continue;
  916. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  917. }
  918. }
  919. if(stackPairs.size() > 0)
  920. {
  921. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  922. minimalPairs.push_back(stackPairs[0]);
  923. for(int b=1; b<stackPairs.size(); ++b)
  924. {
  925. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  926. {
  927. minimalPairs.clear();
  928. minimalPairs.push_back(stackPairs[b]);
  929. }
  930. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  931. {
  932. minimalPairs.push_back(stackPairs[b]);
  933. }
  934. }
  935. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  936. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  937. }
  938. return std::make_pair<const CStack * , BattleHex>(NULL, BattleHex::INVALID);
  939. }
  940. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  941. {
  942. ui32 ret = baseDamage;
  943. //applying sorcery secondary skill
  944. if(caster)
  945. {
  946. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::SORCERY)) / 100.0;
  947. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0;
  948. if(sp->air)
  949. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  950. else if(sp->fire) //only one type of bonus for Magic Arrow
  951. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  952. else if(sp->water)
  953. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  954. else if(sp->earth)
  955. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  956. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  957. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  958. }
  959. return ret;
  960. }
  961. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  962. {
  963. ui32 ret = 0; //value to return
  964. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  965. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  966. //check if spell really does damage - if not, return 0
  967. if(VLC->spellh->damageSpells.find(sp->id) == VLC->spellh->damageSpells.end())
  968. return 0;
  969. ret = usedSpellPower * sp->power;
  970. ret += sp->powers[spellSchoolLevel];
  971. //affected creature-specific part
  972. if(affectedCreature)
  973. {
  974. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  975. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  976. {
  977. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  978. ret /= 100;
  979. }
  980. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  981. {
  982. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  983. ret /= 100;
  984. }
  985. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  986. {
  987. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  988. ret /= 100;
  989. }
  990. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  991. {
  992. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  993. ret /= 100;
  994. }
  995. //general spell dmg reduction
  996. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  997. {
  998. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  999. ret /= 100;
  1000. }
  1001. //dmg increasing
  1002. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  1003. {
  1004. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  1005. ret /= 100;
  1006. }
  1007. }
  1008. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  1009. return ret;
  1010. }
  1011. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const
  1012. {
  1013. bool resurrect = resurrects(spell->id);
  1014. int healedHealth = caster->getPrimSkillLevel(2) * spell->power + spell->powers[caster->getSpellSchoolLevel(spell)];
  1015. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  1016. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1017. }
  1018. ui32 BattleInfo::calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const
  1019. {
  1020. bool resurrect = resurrects(spell->id);
  1021. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1022. }
  1023. ui32 BattleInfo::calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const
  1024. {
  1025. bool resurrect = resurrects(spell->id);
  1026. int healedHealth = usedSpellPower * spell->power + spell->powers[spellSchoolLevel];
  1027. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1028. }
  1029. bool BattleInfo::resurrects(TSpell spellid) const
  1030. {
  1031. return vstd::contains(VLC->spellh->risingSpells, spellid);
  1032. }
  1033. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  1034. {
  1035. //we'll split creatures with remaining movement to 4 parts
  1036. 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
  1037. int toMove = 0; //how many stacks still has move
  1038. const CStack *active = getStack(activeStack);
  1039. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  1040. if(!turn && active && active->willMove() && !vstd::contains(active->state, EBattleStackState::WAITING))
  1041. {
  1042. out.push_back(active);
  1043. if(out.size() == howMany)
  1044. return;
  1045. }
  1046. for(ui32 i=0; i<stacks.size(); ++i)
  1047. {
  1048. const CStack * const s = stacks[i];
  1049. if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
  1050. || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
  1051. || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
  1052. {
  1053. continue;
  1054. }
  1055. int p = -1; //in which phase this tack will move?
  1056. if(turn <= 0 && vstd::contains(s->state, EBattleStackState::WAITING)) //consider waiting state only for ongoing round
  1057. {
  1058. if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
  1059. p = 2;
  1060. else
  1061. p = 3;
  1062. }
  1063. else if(s->getCreature()->idNumber == 145 || s->getCreature()->idNumber == 149) //catapult and turrets are first
  1064. {
  1065. p = 0;
  1066. }
  1067. else
  1068. {
  1069. p = 1;
  1070. }
  1071. phase[p].push_back(s);
  1072. toMove++;
  1073. }
  1074. for(int i = 0; i < 4; i++)
  1075. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  1076. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  1077. out.push_back(phase[0][i]);
  1078. if(out.size() == howMany)
  1079. return;
  1080. if(lastMoved == -1)
  1081. {
  1082. if(active)
  1083. {
  1084. if(out.size() && out.front() == active)
  1085. lastMoved = active->attackerOwned;
  1086. else
  1087. lastMoved = active->attackerOwned;
  1088. }
  1089. else
  1090. {
  1091. lastMoved = 0;
  1092. }
  1093. }
  1094. int pi = 1;
  1095. while(out.size() < howMany)
  1096. {
  1097. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  1098. if(!hlp)
  1099. {
  1100. pi++;
  1101. if(pi > 3)
  1102. {
  1103. //if(turn != 2)
  1104. getStackQueue(out, howMany, turn + 1, lastMoved);
  1105. return;
  1106. }
  1107. }
  1108. else
  1109. {
  1110. out.push_back(hlp);
  1111. }
  1112. }
  1113. }
  1114. si8 BattleInfo::hasDistancePenalty( const CStack * stack, BattleHex destHex ) const
  1115. {
  1116. struct HLP
  1117. {
  1118. static bool lowerAnalyze(const CStack * stack, BattleHex hex)
  1119. {
  1120. int distance = BattleHex::getDistance(hex, stack->position);
  1121. //I hope it's approximately correct
  1122. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  1123. }
  1124. };
  1125. const CStack * dstStack = getStackT(destHex, false);
  1126. if (dstStack->doubleWide())
  1127. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  1128. else
  1129. return HLP::lowerAnalyze(stack, destHex);
  1130. }
  1131. si8 BattleInfo::sameSideOfWall(int pos1, int pos2) const
  1132. {
  1133. int wallInStackLine = lineToWallHex(pos1/GameConstants::BFIELD_WIDTH);
  1134. int wallInDestLine = lineToWallHex(pos2/GameConstants::BFIELD_WIDTH);
  1135. bool stackLeft = pos1 < wallInStackLine;
  1136. bool destLeft = pos2 < wallInDestLine;
  1137. return stackLeft != destLeft;
  1138. }
  1139. si8 BattleInfo::hasWallPenalty( const CStack* stack, BattleHex destHex ) const
  1140. {
  1141. if (!siege || stack->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  1142. {
  1143. return false;
  1144. }
  1145. int wallInStackLine = lineToWallHex(stack->position/GameConstants::BFIELD_WIDTH);
  1146. int wallInDestLine = lineToWallHex(destHex/GameConstants::BFIELD_WIDTH);
  1147. bool stackLeft = stack->position < wallInStackLine;
  1148. bool destRight = destHex > wallInDestLine;
  1149. if (stackLeft && destRight) //shooting from outside to inside
  1150. {
  1151. int row = (stack->position + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  1152. if (stack->position > destHex && ((destHex % GameConstants::BFIELD_WIDTH - stack->position % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  1153. row -= 2;
  1154. int wallPos = lineToWallHex(row);
  1155. if (hexToWallPart(wallPos) != -1) //wall still exists or is indestructible
  1156. return true;
  1157. }
  1158. return false;
  1159. }
  1160. si8 BattleInfo::canTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
  1161. {
  1162. bool ac[GameConstants::BFIELD_SIZE];
  1163. std::set<BattleHex> occupyable;
  1164. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, false, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  1165. if (siege && telportLevel < 2) //check for wall
  1166. {
  1167. return ac[destHex] && sameSideOfWall(stack->position, destHex);
  1168. }
  1169. else
  1170. {
  1171. return ac[destHex];
  1172. }
  1173. }
  1174. bool BattleInfo::battleCanShoot(const CStack * stack, BattleHex dest) const
  1175. {
  1176. const CStack *dst = getStackT(dest);
  1177. if(!stack || !dst) return false;
  1178. const CGHeroInstance * stackHero = battleGetOwner(stack);
  1179. if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  1180. return false;
  1181. if(stack->getCreature()->idNumber == 145 && dst) //catapult cannot attack creatures
  1182. return false;
  1183. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  1184. && stack->owner != dst->owner
  1185. && dst->alive()
  1186. && (!isStackBlocked(stack) || NBonus::hasOfType(stackHero, Bonus::FREE_SHOOTING))
  1187. && stack->shots
  1188. )
  1189. return true;
  1190. return false;
  1191. }
  1192. bool BattleInfo::battleCanFlee(int player) const
  1193. {
  1194. if (player == sides[0])
  1195. {
  1196. if (!heroes[0])
  1197. return false;//current player have no hero
  1198. }
  1199. else
  1200. {
  1201. if (!heroes[1])
  1202. return false;
  1203. }
  1204. if( ( heroes[0] && heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) ) //eg. one of heroes is wearing shakles of war
  1205. || ( heroes[1] && heroes[1]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE)))
  1206. return false;
  1207. if (player == sides[1] && siege //defender in siege
  1208. && !(town->subID == 6 && vstd::contains(town->builtBuildings, 17)))//without escape tunnel
  1209. return false;
  1210. return true;
  1211. }
  1212. const CStack * BattleInfo::battleGetStack(BattleHex pos, bool onlyAlive)
  1213. {
  1214. CStack * stack = NULL;
  1215. for(ui32 g=0; g<stacks.size(); ++g)
  1216. {
  1217. if(stacks[g]->position == pos
  1218. || (stacks[g]->doubleWide()
  1219. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  1220. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  1221. ) )
  1222. {
  1223. if (stacks[g]->alive())
  1224. return stacks[g]; //we prefer living stacks - there cna be only one stack on te tile, so return it imediately
  1225. else if (!onlyAlive)
  1226. stack = stacks[g]; //dead stacks are only accessible when there's no alive stack on this tile
  1227. }
  1228. }
  1229. return stack;
  1230. }
  1231. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  1232. {
  1233. return heroes[!stack->attackerOwned];
  1234. }
  1235. si8 BattleInfo::battleMinSpellLevel() const
  1236. {
  1237. si8 levelLimit = 0;
  1238. if(const CGHeroInstance *h1 = heroes[0])
  1239. {
  1240. vstd::amax(levelLimit, h1->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1241. }
  1242. if(const CGHeroInstance *h2 = heroes[1])
  1243. {
  1244. vstd::amax(levelLimit, h2->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1245. }
  1246. return levelLimit;
  1247. }
  1248. void BattleInfo::localInit()
  1249. {
  1250. belligerents[0]->battle = belligerents[1]->battle = this;
  1251. BOOST_FOREACH(CArmedInstance *b, belligerents)
  1252. b->attachTo(this);
  1253. BOOST_FOREACH(CStack *s, stacks)
  1254. localInitStack(s);
  1255. exportBonuses();
  1256. }
  1257. void BattleInfo::localInitStack(CStack * s)
  1258. {
  1259. s->exportBonuses();
  1260. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  1261. {
  1262. s->attachTo(const_cast<CStackInstance*>(s->base));
  1263. }
  1264. else //attach directly to obj to which stack belongs and creature type
  1265. {
  1266. CArmedInstance *army = belligerents[!s->attackerOwned];
  1267. s->attachTo(army);
  1268. assert(s->type);
  1269. s->attachTo(const_cast<CCreature*>(s->type));
  1270. }
  1271. s->postInit();
  1272. }
  1273. namespace CGH
  1274. {
  1275. using namespace std;
  1276. static void readBattlePositions(const JsonNode &node, vector< vector<int> > & dest)
  1277. {
  1278. BOOST_FOREACH(const JsonNode &level, node.Vector())
  1279. {
  1280. std::vector<int> pom;
  1281. BOOST_FOREACH(const JsonNode &value, level.Vector())
  1282. {
  1283. pom.push_back(value.Float());
  1284. }
  1285. dest.push_back(pom);
  1286. }
  1287. }
  1288. }
  1289. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  1290. {
  1291. CMP_stack cmpst;
  1292. BattleInfo *curB = new BattleInfo;
  1293. curB->sides[0] = armies[0]->tempOwner;
  1294. curB->sides[1] = armies[1]->tempOwner;
  1295. if(curB->sides[1] == 254)
  1296. curB->sides[1] = 255;
  1297. std::vector<CStack*> & stacks = (curB->stacks);
  1298. curB->tile = tile;
  1299. curB->battlefieldType = terType;
  1300. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  1301. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  1302. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  1303. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  1304. curB->round = -2;
  1305. curB->activeStack = -1;
  1306. curB->enchanterCounter[0] = curB->enchanterCounter[1] = 0; //ready to cast
  1307. if(town)
  1308. {
  1309. curB->town = town;
  1310. curB->siege = town->fortLevel();
  1311. }
  1312. else
  1313. {
  1314. curB->town = NULL;
  1315. curB->siege = 0;
  1316. }
  1317. //reading battleStartpos
  1318. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1319. const JsonNode config(GameConstants::DATA_DIR + "/config/battleStartpos.json");
  1320. const JsonVector &positions = config["battle_positions"].Vector();
  1321. CGH::readBattlePositions(positions[0]["levels"], attackerLoose);
  1322. CGH::readBattlePositions(positions[1]["levels"], defenderLoose);
  1323. CGH::readBattlePositions(positions[2]["levels"], attackerTight);
  1324. CGH::readBattlePositions(positions[3]["levels"], defenderTight);
  1325. CGH::readBattlePositions(positions[4]["levels"], attackerCreBank);
  1326. CGH::readBattlePositions(positions[5]["levels"], defenderCreBank);
  1327. //battleStartpos read
  1328. int k = 0; //stack serial
  1329. for(TSlots::const_iterator i = armies[0]->Slots().begin(); i!=armies[0]->Slots().end(); i++, k++)
  1330. {
  1331. int pos;
  1332. if(creatureBank)
  1333. pos = attackerCreBank[armies[0]->stacksCount()-1][k];
  1334. else if(armies[0]->formation)
  1335. pos = attackerTight[armies[0]->stacksCount()-1][k];
  1336. else
  1337. pos = attackerLoose[armies[0]->stacksCount()-1][k];
  1338. CStack * stack = curB->generateNewStack(*i->second, true, i->first, pos);
  1339. stacks.push_back(stack);
  1340. }
  1341. k = 0;
  1342. for(TSlots::const_iterator i = armies[1]->Slots().begin(); i!=armies[1]->Slots().end(); i++, k++)
  1343. {
  1344. int pos;
  1345. if(creatureBank)
  1346. pos = defenderCreBank[armies[1]->stacksCount()-1][k];
  1347. else if(armies[1]->formation)
  1348. pos = defenderTight[armies[1]->stacksCount()-1][k];
  1349. else
  1350. pos = defenderLoose[armies[1]->stacksCount()-1][k];
  1351. CStack * stack = curB->generateNewStack(*i->second, false, i->first, pos);
  1352. stacks.push_back(stack);
  1353. }
  1354. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1355. {
  1356. //we should do that for creature bank too
  1357. if(stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1358. {
  1359. stacks[g]->position += BattleHex::RIGHT;
  1360. }
  1361. else if(stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1362. {
  1363. if (stacks[g]->position.getX() > 1)
  1364. stacks[g]->position += BattleHex::LEFT;
  1365. }
  1366. }
  1367. //adding war machines
  1368. if(!creatureBank)
  1369. {
  1370. if(heroes[0])
  1371. {
  1372. if(heroes[0]->getArt(13)) //ballista
  1373. {
  1374. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), true, 255, 52);
  1375. stacks.push_back(stack);
  1376. }
  1377. if(heroes[0]->getArt(14)) //ammo cart
  1378. {
  1379. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), true, 255, 18);
  1380. stacks.push_back(stack);
  1381. }
  1382. if(heroes[0]->getArt(15)) //first aid tent
  1383. {
  1384. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), true, 255, 154);
  1385. stacks.push_back(stack);
  1386. }
  1387. }
  1388. if(heroes[1])
  1389. {
  1390. //defending hero shouldn't receive ballista (bug #551)
  1391. if(heroes[1]->getArt(13) && !town) //ballista
  1392. {
  1393. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), false, 255, 66);
  1394. stacks.push_back(stack);
  1395. }
  1396. if(heroes[1]->getArt(14)) //ammo cart
  1397. {
  1398. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), false, 255, 32);
  1399. stacks.push_back(stack);
  1400. }
  1401. if(heroes[1]->getArt(15)) //first aid tent
  1402. {
  1403. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), false, 255, 168);
  1404. stacks.push_back(stack);
  1405. }
  1406. }
  1407. if(town && heroes[0] && town->hasFort()) //catapult
  1408. {
  1409. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(145, 1), true, 255, 120);
  1410. stacks.push_back(stack);
  1411. }
  1412. }
  1413. //war machines added
  1414. if (curB->siege == 2 || curB->siege == 3)
  1415. {
  1416. // keep tower
  1417. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -2);
  1418. stacks.push_back(stack);
  1419. if (curB->siege == 3)
  1420. {
  1421. // lower tower + upper tower
  1422. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -4);
  1423. stacks.push_back(stack);
  1424. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -3);
  1425. stacks.push_back(stack);
  1426. }
  1427. }
  1428. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1429. //setting up siege
  1430. if(town && town->hasFort())
  1431. {
  1432. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1433. {
  1434. curB->si.wallState[b] = 1;
  1435. }
  1436. }
  1437. //randomize obstacles
  1438. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1439. {
  1440. bool obAv[GameConstants::BFIELD_SIZE]; //availability of hexes for obstacles;
  1441. std::vector<int> possibleObstacles;
  1442. for(int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  1443. {
  1444. if(i%17 < 4 || i%17 > 12)
  1445. {
  1446. obAv[i] = false;
  1447. }
  1448. else
  1449. {
  1450. obAv[i] = true;
  1451. }
  1452. }
  1453. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1454. {
  1455. 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
  1456. {
  1457. possibleObstacles.push_back(g->first);
  1458. }
  1459. }
  1460. srand(time(NULL));
  1461. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1462. {
  1463. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1464. while(toBlock>0)
  1465. {
  1466. CObstacleInstance coi;
  1467. coi.uniqueID = curB->obstacles.size();
  1468. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1469. coi.pos = rand()%GameConstants::BFIELD_SIZE;
  1470. std::vector<BattleHex> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1471. bool badObstacle = false;
  1472. for(int b=0; b<block.size(); ++b)
  1473. {
  1474. if(block[b] < 0 || block[b] >= GameConstants::BFIELD_SIZE || !obAv[block[b]])
  1475. {
  1476. badObstacle = true;
  1477. break;
  1478. }
  1479. }
  1480. if(badObstacle) continue;
  1481. //obstacle can be placed
  1482. curB->obstacles.push_back(coi);
  1483. for(int b=0; b<block.size(); ++b)
  1484. {
  1485. if(block[b] >= 0 && block[b] < GameConstants::BFIELD_SIZE)
  1486. obAv[block[b]] = false;
  1487. }
  1488. toBlock -= block.size();
  1489. }
  1490. }
  1491. }
  1492. //spell level limiting bonus
  1493. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  1494. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  1495. //giving terrain overalay premies
  1496. int bonusSubtype = -1;
  1497. switch(terType)
  1498. {
  1499. case 9: //magic plains
  1500. {
  1501. bonusSubtype = 0;
  1502. }
  1503. case 14: //fiery fields
  1504. {
  1505. if(bonusSubtype == -1) bonusSubtype = 1;
  1506. }
  1507. case 15: //rock lands
  1508. {
  1509. if(bonusSubtype == -1) bonusSubtype = 8;
  1510. }
  1511. case 16: //magic clouds
  1512. {
  1513. if(bonusSubtype == -1) bonusSubtype = 2;
  1514. }
  1515. case 17: //lucid pools
  1516. {
  1517. if(bonusSubtype == -1) bonusSubtype = 4;
  1518. }
  1519. { //common part for cases 9, 14, 15, 16, 17
  1520. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  1521. break;
  1522. }
  1523. case 18: //holy ground
  1524. {
  1525. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::GOOD)));
  1526. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::EVIL)));
  1527. break;
  1528. }
  1529. case 19: //clover field
  1530. { //+2 luck bonus for neutral creatures
  1531. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureFactionLimiter(-1)));
  1532. break;
  1533. }
  1534. case 20: //evil fog
  1535. {
  1536. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::GOOD)));
  1537. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::EVIL)));
  1538. break;
  1539. }
  1540. case 22: //cursed ground
  1541. {
  1542. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1543. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1544. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, GameConstants::SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  1545. b->valType = Bonus::INDEPENDENT_MAX;
  1546. curB->addNewBonus(b);
  1547. break;
  1548. }
  1549. }
  1550. //overlay premies given
  1551. //native terrain bonuses
  1552. if(town) //during siege always take premies for native terrain of faction
  1553. terrain = VLC->heroh->nativeTerrains[town->town->typeID];
  1554. boost::shared_ptr<ILimiter> nativeTerrain(new CreatureNativeTerrainLimiter(terrain));
  1555. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1556. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1557. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1558. //////////////////////////////////////////////////////////////////////////
  1559. //tactics
  1560. int tacticLvls[2] = {0};
  1561. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  1562. {
  1563. if(heroes[i])
  1564. tacticLvls[i] += heroes[i]->getSecSkillLevel(CGHeroInstance::TACTICS);
  1565. }
  1566. if(int diff = tacticLvls[0] - tacticLvls[1])
  1567. {
  1568. curB->tacticsSide = diff < 0;
  1569. curB->tacticDistance = std::abs(diff)*2 + 1;
  1570. }
  1571. else
  1572. curB->tacticDistance = 0;
  1573. // workaround — bonuses affecting only enemy
  1574. for(int i = 0; i < 2; i++)
  1575. {
  1576. TNodes nodes;
  1577. curB->belligerents[i]->getRedAncestors(nodes);
  1578. BOOST_FOREACH(CBonusSystemNode *n, nodes)
  1579. {
  1580. BOOST_FOREACH(Bonus *b, n->getExportedBonusList())
  1581. {
  1582. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  1583. {
  1584. Bonus *bCopy = new Bonus(*b);
  1585. bCopy->effectRange = Bonus::NO_LIMIT;
  1586. bCopy->propagator.reset();
  1587. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i]));
  1588. curB->addNewBonus(bCopy);
  1589. }
  1590. }
  1591. }
  1592. }
  1593. return curB;
  1594. }
  1595. bool BattleInfo::isInTacticRange( BattleHex dest ) const
  1596. {
  1597. return ((!tacticsSide && dest.getX() > 0 && dest.getX() <= tacticDistance)
  1598. || (tacticsSide && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - tacticDistance - 1));
  1599. }
  1600. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastSpell(int player, ECastingMode::ECastingMode mode) const
  1601. {
  1602. int side = sides[0] == player ? 0 : 1;
  1603. switch (mode)
  1604. {
  1605. case ECastingMode::HERO_CASTING:
  1606. {
  1607. if(castSpells[side] > 0)
  1608. return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
  1609. if(!heroes[side])
  1610. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  1611. if(!heroes[side]->getArt(17))
  1612. return ESpellCastProblem::NO_SPELLBOOK;
  1613. }
  1614. break;
  1615. }
  1616. return ESpellCastProblem::OK;
  1617. }
  1618. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastThisSpell( int player, const CSpell * spell, ECastingMode::ECastingMode mode ) const
  1619. {
  1620. ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
  1621. if(genProblem != ESpellCastProblem::OK)
  1622. return genProblem;
  1623. int cside = sides[0] == player ? 0 : 1; //caster's side
  1624. switch(mode)
  1625. {
  1626. case ECastingMode::HERO_CASTING:
  1627. {
  1628. const CGHeroInstance * caster = heroes[cside];
  1629. if(!caster->canCastThisSpell(spell))
  1630. return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  1631. if(caster->mana < getSpellCost(spell, caster)) //not enough mana
  1632. return ESpellCastProblem::NOT_ENOUGH_MANA;
  1633. }
  1634. break;
  1635. }
  1636. if(spell->id < 10) //it's adventure spell (not combat))
  1637. return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  1638. if(NBonus::hasOfType(heroes[1-cside], Bonus::SPELL_IMMUNITY, spell->id)) //non - casting hero provides immunity for this spell
  1639. return ESpellCastProblem::SECOND_HEROS_SPELL_IMMUNITY;
  1640. if(battleMinSpellLevel() > spell->level) //non - casting hero stops caster from casting this spell
  1641. return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
  1642. int spellIDs[] = {66, 67, 68, 69}; //IDs of summon elemental spells (fire, earth, water, air)
  1643. int creIDs[] = {114, 113, 115, 112}; //(fire, earth, water, air)
  1644. int * idp = std::find(spellIDs, spellIDs + ARRAY_COUNT(spellIDs), spell->id);
  1645. int arpos = idp - spellIDs;
  1646. if(arpos < ARRAY_COUNT(spellIDs))
  1647. {
  1648. //check if there are summoned elementals of other type
  1649. BOOST_FOREACH ( const CStack * st, stacks)
  1650. {
  1651. if (vstd::contains(st->state, EBattleStackState::SUMMONED) && st->getCreature()->idNumber != creIDs[arpos])
  1652. {
  1653. return ESpellCastProblem::ANOTHER_ELEMENTAL_SUMMONED;
  1654. }
  1655. }
  1656. }
  1657. //checking if there exists an appropriate target
  1658. switch(spell->getTargetType())
  1659. {
  1660. case CSpell::CREATURE:
  1661. case CSpell::CREATURE_EXPERT_MASSIVE:
  1662. if(mode == ECastingMode::HERO_CASTING)
  1663. {
  1664. const CGHeroInstance * caster = getHero(player);
  1665. bool targetExists = false;
  1666. BOOST_FOREACH(const CStack * stack, stacks)
  1667. {
  1668. switch (spell->positiveness)
  1669. {
  1670. case CSpell::POSITIVE:
  1671. if(stack->owner == caster->getOwner())
  1672. {
  1673. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1674. {
  1675. targetExists = true;
  1676. break;
  1677. }
  1678. }
  1679. break;
  1680. case CSpell::NEUTRAL:
  1681. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1682. {
  1683. targetExists = true;
  1684. break;
  1685. }
  1686. break;
  1687. case CSpell::NEGATIVE:
  1688. if(stack->owner != caster->getOwner())
  1689. {
  1690. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1691. {
  1692. targetExists = true;
  1693. break;
  1694. }
  1695. }
  1696. break;
  1697. }
  1698. }
  1699. if(!targetExists)
  1700. {
  1701. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1702. }
  1703. }
  1704. break;
  1705. case CSpell::OBSTACLE:
  1706. break;
  1707. }
  1708. return ESpellCastProblem::OK;
  1709. }
  1710. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastThisSpellHere( int player, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest ) const
  1711. {
  1712. ESpellCastProblem::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(player, spell, mode);
  1713. if(moreGeneralProblem != ESpellCastProblem::OK)
  1714. return moreGeneralProblem;
  1715. if (mode != ECastingMode::CREATURE_ACTIVE_CASTING && mode != ECastingMode::ENCHANTER_CASTING)
  1716. return battleIsImmune(getHero(player), spell, mode, dest);
  1717. else
  1718. return battleIsImmune(NULL, spell, mode, dest);
  1719. }
  1720. TSpell BattleInfo::getRandomBeneficialSpell(const CStack * subject) const
  1721. {
  1722. std::vector<TSpell> possibleSpells;
  1723. CSpell * spell;
  1724. for (int i = 0; i < GameConstants::SPELLS_QUANTITY; ++i) //should not use future spells added by mods
  1725. {
  1726. spell = VLC->spellh->spells[i];
  1727. if (spell->isPositive()) //only positive
  1728. {
  1729. if (subject->hasBonusFrom(Bonus::SPELL_EFFECT, i) ||
  1730. battleCanCastThisSpellHere(subject->owner, spell, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1731. continue;
  1732. switch (i)
  1733. {
  1734. case Spells::SHIELD:
  1735. case Spells::FIRE_SHIELD: // not if all enemy units are shooters
  1736. {
  1737. bool walkerPresent = false;
  1738. BOOST_FOREACH (CStack * stack, stacks)
  1739. {
  1740. if ((stack->owner != subject->owner) && !stack->shots)
  1741. {
  1742. walkerPresent = true;
  1743. break;
  1744. }
  1745. }
  1746. if (!walkerPresent)
  1747. continue;
  1748. }
  1749. break;
  1750. case Spells::AIR_SHIELD: //only against active shooters
  1751. {
  1752. bool shooterPresent = false;
  1753. BOOST_FOREACH (CStack * stack, stacks)
  1754. {
  1755. if ((stack->owner != subject->owner) && stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots)
  1756. {
  1757. shooterPresent = true;
  1758. break;
  1759. }
  1760. }
  1761. if (!shooterPresent)
  1762. continue;
  1763. break;
  1764. }
  1765. case Spells::ANTI_MAGIC:
  1766. case Spells::MAGIC_MIRROR:
  1767. {
  1768. if (!heroes[whatSide(theOtherPlayer(subject->owner))]) //only if there is enemy hero
  1769. continue;
  1770. }
  1771. break;
  1772. case Spells::CURE: //only damaged units - what about affected by curse?
  1773. {
  1774. if (subject->firstHPleft >= subject->MaxHealth())
  1775. continue;
  1776. }
  1777. break;
  1778. case Spells::BLOODLUST:
  1779. {
  1780. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1781. continue;
  1782. }
  1783. break;
  1784. case Spells::PRECISION:
  1785. {
  1786. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1787. continue;
  1788. }
  1789. break;
  1790. case Spells::SLAYER://only if monsters are present
  1791. {
  1792. bool monsterPresent = false;
  1793. BOOST_FOREACH (CStack * stack, stacks)
  1794. {
  1795. if ((stack->owner != subject->owner) &&
  1796. (stack->hasBonus(Selector::type(Bonus::KING1) || Selector::type(Bonus::KING2) || Selector::type(Bonus::KING3))))
  1797. {
  1798. monsterPresent = true;
  1799. break;
  1800. }
  1801. }
  1802. if (!monsterPresent)
  1803. continue;
  1804. }
  1805. break;
  1806. case Spells::CLONE: //not allowed
  1807. continue;
  1808. break;
  1809. }
  1810. possibleSpells.push_back(i);
  1811. }
  1812. }
  1813. if (possibleSpells.size())
  1814. return possibleSpells[ran() % possibleSpells.size()];
  1815. else
  1816. return -1;
  1817. }
  1818. TSpell BattleInfo::getRandomCastedSpell(const CStack * caster) const
  1819. {
  1820. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1821. if (!bl->size())
  1822. return -1;
  1823. int totalWeight = 0;
  1824. BOOST_FOREACH(Bonus * b, *bl)
  1825. {
  1826. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1827. }
  1828. int randomPos = ran() % totalWeight;
  1829. BOOST_FOREACH(Bonus * b, *bl)
  1830. {
  1831. randomPos -= std::max(b->additionalInfo, 1);
  1832. if(randomPos < 0)
  1833. {
  1834. return b->subtype;
  1835. }
  1836. }
  1837. return -1;
  1838. }
  1839. const CGHeroInstance * BattleInfo::getHero( int player ) const
  1840. {
  1841. assert(sides[0] == player || sides[1] == player);
  1842. if(heroes[0] && heroes[0]->getOwner() == player)
  1843. return heroes[0];
  1844. return heroes[1];
  1845. }
  1846. bool NegateRemover(const Bonus* b)
  1847. {
  1848. return b->source == Bonus::CREATURE_ABILITY;
  1849. }
  1850. bool BattleInfo::battleTestElementalImmunity(const CStack * subject, const CSpell * spell, Bonus::BonusType element, bool damageSpell) const //helper for battleisImmune
  1851. {
  1852. if (!spell->isPositive()) //negative or indifferent
  1853. {
  1854. if ((damageSpell && subject->hasBonusOfType(element, 2)) || subject->hasBonusOfType(element, 1))
  1855. return true;
  1856. }
  1857. else if (spell->isPositive()) //positive
  1858. {
  1859. if (subject->hasBonusOfType(element, 0)) //must be immune to all spells
  1860. return true;
  1861. }
  1862. return false;
  1863. }
  1864. ESpellCastProblem::ESpellCastProblem BattleInfo::battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
  1865. {
  1866. const CStack * subject = getStackT(dest, false);
  1867. if(subject)
  1868. {
  1869. if (spell->isPositive() && subject->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  1870. return ESpellCastProblem::OK;
  1871. switch (spell->id) //TODO: more general logic for new spells?
  1872. {
  1873. case Spells::DESTROY_UNDEAD:
  1874. if (!subject->hasBonusOfType(Bonus::UNDEAD))
  1875. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1876. break;
  1877. case Spells::DEATH_RIPPLE:
  1878. if (subject->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1879. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //don't break here - undeads and war machines are immune, non-living are not
  1880. case Spells::BLESS:
  1881. case Spells::CURSE: //undeads are immune to bless & curse
  1882. if (subject->hasBonusOfType(Bonus::UNDEAD))
  1883. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1884. break;
  1885. case Spells::HASTE:
  1886. case Spells::SLOW:
  1887. case Spells::TELEPORT:
  1888. case Spells::CLONE:
  1889. if (subject->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1890. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //war machines are immune to some spells than involve movement
  1891. if (spell->id == Spells::CLONE && caster) //TODO: how about stacks casting Clone?
  1892. {
  1893. if (vstd::contains(subject->state, EBattleStackState::CLONED))
  1894. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //can't clone already cloned creature
  1895. int maxLevel = (std::max(caster->getSpellSchoolLevel(spell), (ui8)1) + 4);
  1896. int creLevel = subject->getCreature()->level;
  1897. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, 1-7 for expert
  1898. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1899. }
  1900. break;
  1901. case Spells::FORGETFULNESS:
  1902. if (!subject->hasBonusOfType(Bonus::SHOOTER))
  1903. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1904. break;
  1905. case Spells::DISPEL_HELPFUL_SPELLS:
  1906. {
  1907. TBonusListPtr spellBon = subject->getSpellBonuses();
  1908. bool hasPositiveSpell = false;
  1909. BOOST_FOREACH(const Bonus * b, *spellBon)
  1910. {
  1911. if(VLC->spellh->spells[b->sid]->isPositive())
  1912. {
  1913. hasPositiveSpell = true;
  1914. break;
  1915. }
  1916. }
  1917. if(!hasPositiveSpell)
  1918. {
  1919. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  1920. }
  1921. }
  1922. break;
  1923. }
  1924. bool damageSpell = (vstd::contains(VLC->spellh->damageSpells, spell->id));
  1925. if (damageSpell && subject->hasBonusOfType(Bonus::DIRECT_DAMAGE_IMMUNITY))
  1926. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1927. if (spell->fire)
  1928. {
  1929. if (battleTestElementalImmunity(subject, spell, Bonus::FIRE_IMMUNITY, damageSpell))
  1930. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1931. }
  1932. if (spell->water)
  1933. {
  1934. if (battleTestElementalImmunity(subject, spell, Bonus::WATER_IMMUNITY, damageSpell))
  1935. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1936. }
  1937. if (spell->earth)
  1938. {
  1939. if (battleTestElementalImmunity(subject, spell, Bonus::EARTH_IMMUNITY, damageSpell))
  1940. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1941. }
  1942. if (spell->air)
  1943. {
  1944. if (battleTestElementalImmunity(subject, spell, Bonus::AIR_IMMUNITY, damageSpell))
  1945. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1946. }
  1947. if (vstd::contains(VLC->spellh->mindSpells, spell->id))
  1948. {
  1949. if (subject->hasBonusOfType(Bonus::MIND_IMMUNITY))
  1950. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1951. }
  1952. if (vstd::contains(VLC->spellh->risingSpells, spell->id))
  1953. {
  1954. if (subject->count >= subject->baseAmount) //TODO: calculate potential hp raised
  1955. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1956. }
  1957. TBonusListPtr immunities = subject->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  1958. if(subject->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  1959. {
  1960. //std::remove_if(immunities->begin(), immunities->end(), NegateRemover);
  1961. immunities->remove_if(NegateRemover);
  1962. }
  1963. if(subject->hasBonusOfType(Bonus::SPELL_IMMUNITY, spell->id) ||
  1964. ( immunities->size() > 0 && immunities->totalValue() >= spell->level && spell->level))
  1965. {
  1966. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1967. }
  1968. }
  1969. else
  1970. {
  1971. if(spell->getTargetType() == CSpell::CREATURE ||
  1972. (spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE && mode == ECastingMode::HERO_CASTING && caster && caster->getSpellSchoolLevel(spell) < 3))
  1973. {
  1974. return ESpellCastProblem::WRONG_SPELL_TARGET;
  1975. }
  1976. }
  1977. return ESpellCastProblem::OK;
  1978. }
  1979. std::vector<ui32> BattleInfo::calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures, int casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const
  1980. {
  1981. std::vector<ui32> ret;
  1982. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  1983. {
  1984. if(battleIsImmune(caster, sp, mode, (*it)->position) != ESpellCastProblem::OK)
  1985. {
  1986. ret.push_back((*it)->ID);
  1987. continue;
  1988. }
  1989. //non-negative spells on friendly stacks should always succeed, unless immune
  1990. if(!sp->isNegative() && (*it)->owner == casterSideOwner)
  1991. continue;
  1992. /*
  1993. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  1994. if((*it)->owner == casterSideOwner)
  1995. bonusHero = caster;
  1996. else
  1997. bonusHero = hero2;*/
  1998. int prob = (*it)->magicResistance(); //probability of resistance in %
  1999. if(prob > 100) prob = 100;
  2000. if(rand()%100 < prob) //immunity from resistance
  2001. ret.push_back((*it)->ID);
  2002. }
  2003. if(sp->id == 60) //hypnotize
  2004. {
  2005. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2006. {
  2007. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2008. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2009. >
  2010. usedSpellPower * 25 + sp->powers[spellLevel]
  2011. )
  2012. {
  2013. ret.push_back((*it)->ID);
  2014. }
  2015. }
  2016. }
  2017. return ret;
  2018. }
  2019. int BattleInfo::getSurrenderingCost(int player) const
  2020. {
  2021. if(!battleCanFlee(player)) //to surrender, conditions of fleeing must be fulfilled
  2022. return -1;
  2023. if(!getHero(theOtherPlayer(player))) //additionally, there must be an enemy hero
  2024. return -2;
  2025. int ret = 0;
  2026. double discount = 0;
  2027. BOOST_FOREACH(const CStack *s, stacks)
  2028. if(s->owner == player && s->base) //we pay for our stack that comes from our army (the last condition eliminates summoned cres and war machines)
  2029. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  2030. if(const CGHeroInstance *h = getHero(player))
  2031. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  2032. ret *= (100.0 - discount) / 100.0;
  2033. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  2034. return ret;
  2035. }
  2036. int BattleInfo::theOtherPlayer(int player) const
  2037. {
  2038. return sides[!whatSide(player)];
  2039. }
  2040. ui8 BattleInfo::whatSide(int player) const
  2041. {
  2042. for(int i = 0; i < ARRAY_COUNT(sides); i++)
  2043. if(sides[i] == player)
  2044. return i;
  2045. tlog1 << "BattleInfo::whatSide: Player " << player << " is not in battle!\n";
  2046. return -1;
  2047. }
  2048. int BattleInfo::getIdForNewStack() const
  2049. {
  2050. if(stacks.size())
  2051. {
  2052. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  2053. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  2054. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  2055. return highestIDStack->ID + 1;
  2056. }
  2057. return 0;
  2058. }
  2059. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  2060. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  2061. counterAttacks(1)
  2062. {
  2063. assert(base);
  2064. type = base->type;
  2065. count = baseAmount = base->count;
  2066. setNodeType(STACK_BATTLE);
  2067. }
  2068. CStack::CStack()
  2069. {
  2070. init();
  2071. setNodeType(STACK_BATTLE);
  2072. }
  2073. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  2074. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  2075. {
  2076. type = stack->type;
  2077. count = baseAmount = stack->count;
  2078. setNodeType(STACK_BATTLE);
  2079. }
  2080. void CStack::init()
  2081. {
  2082. base = NULL;
  2083. type = NULL;
  2084. ID = -1;
  2085. count = baseAmount = -1;
  2086. firstHPleft = -1;
  2087. owner = 255;
  2088. slot = 255;
  2089. attackerOwned = false;
  2090. position = BattleHex();
  2091. counterAttacks = -1;
  2092. }
  2093. void CStack::postInit()
  2094. {
  2095. assert(type);
  2096. assert(getParentNodes().size());
  2097. firstHPleft = MaxHealth();
  2098. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  2099. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  2100. casts = valOfBonuses(Bonus::CASTS); //TODO: set them in cr_abils.txt
  2101. state.insert(EBattleStackState::ALIVE); //alive state indication
  2102. }
  2103. ui32 CStack::Speed( int turn /*= 0*/ , bool useBind /* = false*/) const
  2104. {
  2105. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  2106. return 0;
  2107. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  2108. int percentBonus = 0;
  2109. BOOST_FOREACH(const Bonus *b, getBonusList())
  2110. {
  2111. if(b->type == Bonus::STACKS_SPEED)
  2112. {
  2113. percentBonus += b->additionalInfo;
  2114. }
  2115. }
  2116. speed = ((100 + percentBonus) * speed)/100;
  2117. //bind effect check - doesn't influence stack initiative
  2118. if (useBind && getEffect(72))
  2119. {
  2120. return 0;
  2121. }
  2122. return speed;
  2123. }
  2124. si32 CStack::magicResistance() const
  2125. {
  2126. si32 magicResistance;
  2127. if (base) //TODO: make war machines receive aura of magic resistance
  2128. {
  2129. magicResistance = base->magicResistance();
  2130. int auraBonus = 0;
  2131. BOOST_FOREACH (CStack * stack, base->armyObj->battle->getAdjacentCreatures(this))
  2132. {
  2133. if (stack->owner == owner)
  2134. {
  2135. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  2136. }
  2137. }
  2138. magicResistance += auraBonus;
  2139. vstd::amin (magicResistance, 100);
  2140. }
  2141. else
  2142. magicResistance = type->magicResistance();
  2143. return magicResistance;
  2144. }
  2145. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  2146. {
  2147. BOOST_FOREACH(Bonus *it, getBonusList())
  2148. {
  2149. if(it->source == Bonus::SPELL_EFFECT && it->sid == id)
  2150. {
  2151. if(!turn || it->turnsRemain > turn)
  2152. return &(*it);
  2153. }
  2154. }
  2155. return NULL;
  2156. }
  2157. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  2158. {
  2159. si32 power = VLC->spellh->spells[sse.sid]->powers[sse.val];
  2160. switch(sse.sid)
  2161. {
  2162. case 27: //shield
  2163. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  2164. sf.back().sid = sse.sid;
  2165. break;
  2166. case 28: //air shield
  2167. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  2168. sf.back().sid = sse.sid;
  2169. break;
  2170. case 29: //fire shield
  2171. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  2172. sf.back().sid = sse.sid;
  2173. break;
  2174. case 30: //protection from air
  2175. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  2176. sf.back().sid = sse.sid;
  2177. break;
  2178. case 31: //protection from fire
  2179. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  2180. sf.back().sid = sse.sid;
  2181. break;
  2182. case 32: //protection from water
  2183. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  2184. sf.back().sid = sse.sid;
  2185. break;
  2186. case 33: //protection from earth
  2187. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  2188. sf.back().sid = sse.sid;
  2189. break;
  2190. case 34: //anti-magic
  2191. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, GameConstants::SPELL_LEVELS, power - 1, sse.turnsRemain));
  2192. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2193. sf.back().sid = sse.sid;
  2194. break;
  2195. case 36: //magic mirror
  2196. sf.push_back(featureGenerator(Bonus::MAGIC_MIRROR, -1, power, sse.turnsRemain));
  2197. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2198. sf.back().sid = sse.sid;
  2199. case 41: //bless
  2200. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  2201. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2202. sf.back().sid = sse.sid;
  2203. break;
  2204. case 42: //curse
  2205. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  2206. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2207. sf.back().sid = sse.sid;
  2208. break;
  2209. case 43: //bloodlust
  2210. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  2211. sf.back().sid = sse.sid;
  2212. break;
  2213. case 44: //precision
  2214. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  2215. sf.back().sid = sse.sid;
  2216. break;
  2217. case 45: //weakness
  2218. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  2219. sf.back().sid = sse.sid;
  2220. break;
  2221. case 46: //stone skin
  2222. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  2223. sf.back().sid = sse.sid;
  2224. break;
  2225. case 47: //disrupting ray
  2226. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  2227. sf.back().sid = sse.sid;
  2228. sf.back().valType = Bonus::ADDITIVE_VALUE;
  2229. break;
  2230. case 48: //prayer
  2231. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  2232. sf.back().sid = sse.sid;
  2233. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  2234. sf.back().sid = sse.sid;
  2235. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  2236. sf.back().sid = sse.sid;
  2237. break;
  2238. case 49: //mirth
  2239. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  2240. sf.back().sid = sse.sid;
  2241. break;
  2242. case 50: //sorrow
  2243. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  2244. sf.back().sid = sse.sid;
  2245. break;
  2246. case 51: //fortune
  2247. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  2248. sf.back().sid = sse.sid;
  2249. break;
  2250. case 52: //misfortune
  2251. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  2252. sf.back().sid = sse.sid;
  2253. break;
  2254. case 53: //haste
  2255. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  2256. sf.back().sid = sse.sid;
  2257. break;
  2258. case 54: //slow
  2259. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2260. sf.back().sid = sse.sid;
  2261. break;
  2262. case 55: //slayer
  2263. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  2264. sf.back().sid = sse.sid;
  2265. break;
  2266. case 56: //frenzy
  2267. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  2268. sf.back().sid = sse.sid;
  2269. break;
  2270. case 58: //counterstrike
  2271. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  2272. sf.back().sid = sse.sid;
  2273. break;
  2274. case 59: //bersek
  2275. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  2276. sf.back().sid = sse.sid;
  2277. break;
  2278. case 60: //hypnotize
  2279. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  2280. sf.back().sid = sse.sid;
  2281. break;
  2282. case 61: //forgetfulness
  2283. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  2284. sf.back().sid = sse.sid;
  2285. break;
  2286. case Spells::BLIND: //blind
  2287. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2288. sf.back().sid = sse.sid;
  2289. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2290. sf.back().sid = sse.sid;
  2291. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  2292. sf.back().sid = sse.sid;
  2293. break;
  2294. case Spells::STONE_GAZE: //Stone Gaze
  2295. case Spells::PARALYZE: //Paralyze
  2296. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2297. sf.back().sid = sse.sid;
  2298. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  2299. sf.back().sid = sse.sid;
  2300. break;
  2301. case 71: //Poison
  2302. sf.push_back(featureGeneratorVT(Bonus::POISON, 0, 30, sse.turnsRemain, Bonus::INDEPENDENT_MAX)); //max hp penalty from this source
  2303. sf.back().sid = sse.sid;
  2304. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -10, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2305. sf.back().sid = sse.sid;
  2306. break;
  2307. case 72: //Bind
  2308. sf.push_back(featureGenerator(Bonus::BIND_EFFECT, 0, 0, 1)); //marker
  2309. sf.back().duration = Bonus::PERMANENT;
  2310. sf.back().sid = sse.sid;
  2311. break;
  2312. case 73: //Disease
  2313. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -2 , sse.turnsRemain));
  2314. sf.back().sid = sse.sid;
  2315. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -2 , sse.turnsRemain));
  2316. sf.back().sid = sse.sid;
  2317. break;
  2318. case 75: //Age
  2319. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -50, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2320. sf.back().sid = sse.sid;
  2321. break;
  2322. case 80: //Acid Breath
  2323. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -sse.turnsRemain, 1));
  2324. sf.back().sid = sse.sid;
  2325. sf.back().duration = Bonus::PERMANENT;
  2326. sf.back().valType = Bonus::ADDITIVE_VALUE;
  2327. break;
  2328. }
  2329. }
  2330. ui8 CStack::howManyEffectsSet(ui16 id) const
  2331. {
  2332. ui8 ret = 0;
  2333. BOOST_FOREACH(const Bonus *it, getBonusList())
  2334. if(it->source == Bonus::SPELL_EFFECT && it->sid == id) //effect found
  2335. {
  2336. ++ret;
  2337. }
  2338. return ret;
  2339. }
  2340. bool CStack::willMove(int turn /*= 0*/) const
  2341. {
  2342. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  2343. && !moved(turn)
  2344. && canMove(turn);
  2345. }
  2346. bool CStack::canMove( int turn /*= 0*/ ) const
  2347. {
  2348. return alive()
  2349. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  2350. }
  2351. bool CStack::moved( int turn /*= 0*/ ) const
  2352. {
  2353. if(!turn)
  2354. return vstd::contains(state, EBattleStackState::MOVED);
  2355. else
  2356. return false;
  2357. }
  2358. bool CStack::doubleWide() const
  2359. {
  2360. return getCreature()->doubleWide;
  2361. }
  2362. BattleHex CStack::occupiedHex() const
  2363. {
  2364. if (doubleWide())
  2365. {
  2366. if (attackerOwned)
  2367. return position - 1;
  2368. else
  2369. return position + 1;
  2370. }
  2371. else
  2372. {
  2373. return BattleHex::INVALID;
  2374. }
  2375. }
  2376. std::vector<BattleHex> CStack::getHexes() const
  2377. {
  2378. std::vector<BattleHex> hexes;
  2379. hexes.push_back(BattleHex(position));
  2380. BattleHex occupied = occupiedHex();
  2381. if(occupied.isValid())
  2382. hexes.push_back(occupied);
  2383. return hexes;
  2384. }
  2385. bool CStack::coversPos(BattleHex pos) const
  2386. {
  2387. return vstd::contains(getHexes(), pos);
  2388. }
  2389. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  2390. {
  2391. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  2392. std::vector<BattleHex> hexes;
  2393. if (doubleWide())
  2394. {
  2395. const int WN = GameConstants::BFIELD_WIDTH;
  2396. if(attackerOwned)
  2397. { //position is equal to front hex
  2398. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  2399. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  2400. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  2401. BattleHex::checkAndPush(hex - 2, hexes);
  2402. BattleHex::checkAndPush(hex + 1, hexes);
  2403. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  2404. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  2405. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  2406. }
  2407. else
  2408. {
  2409. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  2410. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  2411. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  2412. BattleHex::checkAndPush(hex + 2, hexes);
  2413. BattleHex::checkAndPush(hex - 1, hexes);
  2414. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  2415. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  2416. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  2417. }
  2418. return hexes;
  2419. }
  2420. else
  2421. {
  2422. return hex.neighbouringTiles();
  2423. }
  2424. }
  2425. std::vector<si32> CStack::activeSpells() const
  2426. {
  2427. std::vector<si32> ret;
  2428. TBonusListPtr spellEffects = getSpellBonuses();
  2429. BOOST_FOREACH(const Bonus *it, *spellEffects)
  2430. {
  2431. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  2432. ret.push_back(it->sid);
  2433. }
  2434. return ret;
  2435. }
  2436. CStack::~CStack()
  2437. {
  2438. detachFromAll();
  2439. }
  2440. const CGHeroInstance * CStack::getMyHero() const
  2441. {
  2442. if(base)
  2443. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  2444. else //we are attached directly?
  2445. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  2446. if(n->getNodeType() == HERO)
  2447. dynamic_cast<const CGHeroInstance *>(n);
  2448. return NULL;
  2449. }
  2450. std::string CStack::nodeName() const
  2451. {
  2452. std::ostringstream oss;
  2453. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  2454. if(type)
  2455. oss << type->namePl;
  2456. else
  2457. oss << "[UNDEFINED TYPE]";
  2458. oss << " from slot " << (int)slot;
  2459. if(base && base->armyObj)
  2460. oss << " of armyobj=" << base->armyObj->id;
  2461. return oss.str();
  2462. }
  2463. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  2464. {
  2465. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  2466. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  2467. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  2468. {
  2469. bsa.killedAmount = count;
  2470. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  2471. return; // no rebirth I believe
  2472. }
  2473. if( firstHPleft <= damageFirst )
  2474. {
  2475. bsa.killedAmount++;
  2476. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  2477. }
  2478. else
  2479. {
  2480. bsa.newHP = firstHPleft - damageFirst;
  2481. }
  2482. if(count <= bsa.killedAmount) //stack killed
  2483. {
  2484. bsa.newAmount = 0;
  2485. bsa.flags |= BattleStackAttacked::KILLED;
  2486. bsa.killedAmount = count; //we cannot kill more creatures than we have
  2487. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  2488. if (resurrectFactor > 0 && casts) //there must be casts left
  2489. {
  2490. int resurrectedCount = base->count * resurrectFactor / 100;
  2491. if (resurrectedCount)
  2492. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  2493. else //only one unit
  2494. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  2495. if (hasBonusOfType(Bonus::REBIRTH, 1))
  2496. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  2497. if (resurrectedCount)
  2498. {
  2499. bsa.flags |= BattleStackAttacked::REBIRTH;
  2500. bsa.newAmount = resurrectedCount; //risky?
  2501. bsa.newHP = MaxHealth(); //resore full health
  2502. }
  2503. }
  2504. }
  2505. else
  2506. {
  2507. bsa.newAmount = count - bsa.killedAmount;
  2508. }
  2509. }
  2510. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  2511. {
  2512. if (!attackerPos.isValid())
  2513. {
  2514. attackerPos = attacker->position;
  2515. }
  2516. if (!defenderPos.isValid())
  2517. {
  2518. defenderPos = defender->position;
  2519. }
  2520. return
  2521. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  2522. || (attacker->doubleWide() //back <=> front
  2523. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  2524. || (defender->doubleWide() //front <=> back
  2525. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  2526. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  2527. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  2528. }
  2529. bool CStack::ableToRetaliate() const
  2530. {
  2531. return alive()
  2532. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  2533. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  2534. && !hasBonusOfType(Bonus::HYPNOTIZED)
  2535. && !hasBonusOfType(Bonus::NO_RETALIATION);
  2536. }
  2537. std::string CStack::getName() const
  2538. {
  2539. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  2540. }
  2541. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  2542. {
  2543. return (alive() || allowDead) && position.isValid();
  2544. }
  2545. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2546. {
  2547. switch(phase)
  2548. {
  2549. case 0: //catapult moves after turrets
  2550. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  2551. case 1: //fastest first, upper slot first
  2552. {
  2553. int as = a->Speed(turn), bs = b->Speed(turn);
  2554. if(as != bs)
  2555. return as > bs;
  2556. else
  2557. return a->slot < b->slot;
  2558. }
  2559. case 2: //fastest last, upper slot first
  2560. //TODO: should be replaced with order of receiving morale!
  2561. case 3: //fastest last, upper slot first
  2562. {
  2563. int as = a->Speed(turn), bs = b->Speed(turn);
  2564. if(as != bs)
  2565. return as < bs;
  2566. else
  2567. return a->slot < b->slot;
  2568. }
  2569. default:
  2570. assert(0);
  2571. return false;
  2572. }
  2573. }
  2574. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2575. {
  2576. phase = Phase;
  2577. turn = Turn;
  2578. }