BattleState.cpp 99 KB

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