BattleState.cpp 98 KB

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