CBattleInfoCallback.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  1. /*
  2. * CBattleInfoCallback.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CBattleInfoCallback.h"
  12. #include "../CStack.h"
  13. #include "BattleInfo.h"
  14. #include "../NetPacks.h"
  15. #include "../spells/CSpellHandler.h"
  16. #include "../mapObjects/CGTownInstance.h"
  17. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  18. {
  19. static void retreiveTurretDamageRange(const CGTownInstance * town, const CStack * turret, double & outMinDmg, double & outMaxDmg)
  20. {
  21. assert(turret->getCreature()->idNumber == CreatureID::ARROW_TOWERS);
  22. assert(town);
  23. assert(turret->position >= -4 && turret->position <= -2);
  24. float multiplier = (turret->position == -2) ? 1 : 0.5;
  25. int baseMin = 6;
  26. int baseMax = 10;
  27. outMinDmg = multiplier * (baseMin + town->getTownLevel() * 2);
  28. outMaxDmg = multiplier * (baseMax + town->getTownLevel() * 3);
  29. }
  30. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  31. {
  32. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  33. return lineToHex[line];
  34. }
  35. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  36. {
  37. const int wallInStackLine = lineToWallHex(pos1.getY());
  38. const int wallInDestLine = lineToWallHex(pos2.getY());
  39. const bool stackLeft = pos1 < wallInStackLine;
  40. const bool destLeft = pos2 < wallInDestLine;
  41. return stackLeft == destLeft;
  42. }
  43. // parts of wall
  44. static const std::pair<int, EWallPart::EWallPart> wallParts[] =
  45. {
  46. std::make_pair(50, EWallPart::KEEP),
  47. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  48. std::make_pair(182, EWallPart::BOTTOM_WALL),
  49. std::make_pair(130, EWallPart::BELOW_GATE),
  50. std::make_pair(78, EWallPart::OVER_GATE),
  51. std::make_pair(29, EWallPart::UPPER_WALL),
  52. std::make_pair(12, EWallPart::UPPER_TOWER),
  53. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  54. std::make_pair(96, EWallPart::GATE),
  55. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  56. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  57. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  58. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  59. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  60. };
  61. static EWallPart::EWallPart hexToWallPart(BattleHex hex)
  62. {
  63. for(auto & elem : wallParts)
  64. {
  65. if(elem.first == hex)
  66. return elem.second;
  67. }
  68. return EWallPart::INVALID; //not found!
  69. }
  70. static BattleHex WallPartToHex(EWallPart::EWallPart part)
  71. {
  72. for(auto & elem : wallParts)
  73. {
  74. if(elem.second == part)
  75. return elem.first;
  76. }
  77. return BattleHex::INVALID; //not found!
  78. }
  79. }
  80. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  81. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const ISpellCaster * caster, ECastingMode::ECastingMode mode) const
  82. {
  83. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  84. if(caster == nullptr)
  85. {
  86. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  87. return ESpellCastProblem::INVALID;
  88. }
  89. const PlayerColor player = caster->getOwner();
  90. const auto side = playerToSide(player);
  91. if(!side)
  92. return ESpellCastProblem::INVALID;
  93. if(!battleDoWeKnowAbout(side.get()))
  94. {
  95. logGlobal->warn("You can't check if enemy can cast given spell!");
  96. return ESpellCastProblem::INVALID;
  97. }
  98. if(battleTacticDist())
  99. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  100. switch (mode)
  101. {
  102. case ECastingMode::HERO_CASTING:
  103. {
  104. if(battleCastSpells(side.get()) > 0)
  105. return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
  106. auto hero = dynamic_cast<const CGHeroInstance *>(caster);
  107. if(!hero)
  108. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  109. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  110. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  111. }
  112. break;
  113. default:
  114. break;
  115. }
  116. return ESpellCastProblem::OK;
  117. }
  118. si8 CBattleInfoCallback::battleHasWallPenalty(const CStack * stack, BattleHex destHex) const
  119. {
  120. return battleHasWallPenalty(stack, stack->position, destHex);
  121. }
  122. si8 CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  123. {
  124. RETURN_IF_NOT_BATTLE(false);
  125. if (!battleGetSiegeLevel() || bonusBearer->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  126. return false;
  127. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  128. const int wallInDestLine = lineToWallHex(destHex.getY());
  129. const bool stackLeft = shooterPosition < wallInStackLine;
  130. const bool destRight = destHex > wallInDestLine;
  131. if (stackLeft && destRight) //shooting from outside to inside
  132. {
  133. int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  134. if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  135. row -= 2;
  136. const int wallPos = lineToWallHex(row);
  137. if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
  138. }
  139. return false;
  140. }
  141. si8 CBattleInfoCallback::battleCanTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
  142. {
  143. RETURN_IF_NOT_BATTLE(false);
  144. if (!getAccesibility(stack).accessible(destHex, stack))
  145. return false;
  146. const ui8 siegeLevel = battleGetSiegeLevel();
  147. //check for wall
  148. //advanced teleport can pass wall of fort|citadel, expert - of castle
  149. if ((siegeLevel > CGTownInstance::NONE && telportLevel < 2) || (siegeLevel >= CGTownInstance::CASTLE && telportLevel < 3))
  150. return sameSideOfWall(stack->position, destHex);
  151. return true;
  152. }
  153. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  154. {
  155. std::set<BattleHex> attackedHexes;
  156. RETURN_IF_NOT_BATTLE(attackedHexes);
  157. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  158. for (BattleHex tile : at.hostileCreaturePositions)
  159. {
  160. const CStack * st = battleGetStackByPos(tile, true);
  161. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  162. {
  163. attackedHexes.insert(tile);
  164. }
  165. }
  166. for (BattleHex tile : at.friendlyCreaturePositions)
  167. {
  168. if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  169. {
  170. attackedHexes.insert(tile);
  171. }
  172. }
  173. return attackedHexes;
  174. }
  175. SpellID CBattleInfoCallback::battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const
  176. {
  177. switch (mode)
  178. {
  179. case RANDOM_GENIE:
  180. return getRandomBeneficialSpell(rand, stack); //target
  181. break;
  182. case RANDOM_AIMED:
  183. return getRandomCastedSpell(rand, stack); //caster
  184. break;
  185. default:
  186. logGlobal->error("Incorrect mode of battleGetRandomSpell (%d)", static_cast<int>(mode));
  187. return SpellID::NONE;
  188. }
  189. }
  190. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  191. {
  192. RETURN_IF_NOT_BATTLE(nullptr);
  193. for(auto s : battleGetAllStacks(true))
  194. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  195. return s;
  196. return nullptr;
  197. }
  198. void CBattleInfoCallback::battleGetStackQueue(std::vector<const CStack *> &out, const int howMany, const int turn, int lastMoved) const
  199. {
  200. RETURN_IF_NOT_BATTLE();
  201. //let's define a huge lambda
  202. auto takeStack = [&](std::vector<const CStack *> &st) -> const CStack*
  203. {
  204. const CStack * ret = nullptr;
  205. unsigned i, //fastest stack
  206. j=0; //fastest stack of the other side
  207. for(i = 0; i < st.size(); i++)
  208. if(st[i])
  209. break;
  210. //no stacks left
  211. if(i == st.size())
  212. return nullptr;
  213. const CStack * fastest = st[i], *other = nullptr;
  214. int bestSpeed = fastest->Speed(turn);
  215. //FIXME: comparison between bool and integer. Logic does not makes sense either
  216. if(fastest->side != lastMoved)
  217. {
  218. ret = fastest;
  219. }
  220. else
  221. {
  222. for(j = i + 1; j < st.size(); j++)
  223. {
  224. if(!st[j]) continue;
  225. if(st[j]->side != lastMoved || st[j]->Speed(turn) != bestSpeed)
  226. break;
  227. }
  228. if(j >= st.size())
  229. {
  230. ret = fastest;
  231. }
  232. else
  233. {
  234. other = st[j];
  235. if(other->Speed(turn) != bestSpeed)
  236. ret = fastest;
  237. else
  238. ret = other;
  239. }
  240. }
  241. assert(ret);
  242. if(ret == fastest)
  243. st[i] = nullptr;
  244. else
  245. st[j] = nullptr;
  246. lastMoved = ret->side;
  247. return ret;
  248. };
  249. //We'll split creatures with remaining movement to 4 buckets
  250. // [0] - turrets/catapult,
  251. // [1] - normal (unmoved) creatures, other war machines,
  252. // [2] - waited cres that had morale,
  253. // [3] - rest of waited cres
  254. std::vector<const CStack *> phase[4];
  255. int toMove = 0; //how many stacks still has move
  256. const CStack * active = battleActiveStack();
  257. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  258. if(!turn && active && active->willMove() && !active->waited())
  259. {
  260. out.push_back(active);
  261. if(out.size() == howMany)
  262. return;
  263. }
  264. auto allStacks = battleGetAllStacks(true);
  265. if(!vstd::contains_if(allStacks, [](const CStack *stack) { return stack->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  266. {
  267. //No stack will be able to move, battle is over.
  268. out.clear();
  269. return;
  270. }
  271. for(auto s : battleGetAllStacks(true))
  272. {
  273. if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
  274. || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
  275. || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
  276. {
  277. continue;
  278. }
  279. int p = -1; //in which phase this tack will move?
  280. if(turn <= 0 && s->waited()) //consider waiting state only for ongoing round
  281. {
  282. if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
  283. p = 2;
  284. else
  285. p = 3;
  286. }
  287. else if(s->getCreature()->idNumber == CreatureID::CATAPULT || s->getCreature()->idNumber == CreatureID::ARROW_TOWERS) //catapult and turrets are first
  288. {
  289. p = 0;
  290. }
  291. else
  292. {
  293. p = 1;
  294. }
  295. phase[p].push_back(s);
  296. toMove++;
  297. }
  298. for(int i = 0; i < 4; i++)
  299. boost::sort(phase[i], CMP_stack(i, turn > 0 ? turn : 0));
  300. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  301. out.push_back(phase[0][i]);
  302. if(out.size() == howMany)
  303. return;
  304. if(lastMoved == -1)
  305. {
  306. if(active)
  307. {
  308. //FIXME: both branches contain same code!!!
  309. if(out.size() && out.front() == active)
  310. lastMoved = active->side;
  311. else
  312. lastMoved = active->side;
  313. }
  314. else
  315. {
  316. lastMoved = 0;
  317. }
  318. }
  319. int pi = 1;
  320. while(out.size() < howMany)
  321. {
  322. const CStack * hlp = takeStack(phase[pi]);
  323. if(!hlp)
  324. {
  325. pi++;
  326. if(pi > 3)
  327. {
  328. //if(turn != 2)
  329. battleGetStackQueue(out, howMany, turn + 1, lastMoved);
  330. return;
  331. }
  332. }
  333. else
  334. {
  335. out.push_back(hlp);
  336. }
  337. }
  338. }
  339. void CBattleInfoCallback::battleGetStackCountOutsideHexes(bool *ac) const
  340. {
  341. RETURN_IF_NOT_BATTLE();
  342. auto accessibility = getAccesibility();
  343. for(int i = 0; i < accessibility.size(); i++)
  344. ac[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  345. }
  346. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable) const
  347. {
  348. std::vector<BattleHex> ret;
  349. RETURN_IF_NOT_BATTLE(ret);
  350. if(!stack->position.isValid()) //turrets
  351. return ret;
  352. auto reachability = getReachability(stack);
  353. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  354. {
  355. // If obstacles or other stacks makes movement impossible, it can't be helped.
  356. if(!reachability.isReachable(i))
  357. continue;
  358. if(battleTacticDist() && battleGetTacticsSide() == stack->side)
  359. {
  360. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  361. if(!isInTacticRange(i))
  362. continue;
  363. }
  364. else
  365. {
  366. //Not tactics phase -> destination must be reachable and within stack range.
  367. if(reachability.distances[i] > stack->Speed(0, true))
  368. continue;
  369. }
  370. ret.push_back(i);
  371. if(addOccupiable && stack->doubleWide())
  372. {
  373. //If two-hex stack can stand on hex i then obviously it can occupy its second hex from that position
  374. ret.push_back(stack->occupiedHex(i));
  375. }
  376. }
  377. if(attackable)
  378. {
  379. auto meleeAttackable = [&](BattleHex hex) -> bool
  380. {
  381. // Return true if given hex has at least one available neighbour.
  382. // Available hexes are already present in ret vector.
  383. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  384. {
  385. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  386. });
  387. return availableNeighbor != ret.end();
  388. };
  389. for(const CStack * otherSt : battleAliveStacks(1-stack->side))
  390. {
  391. if(!otherSt->isValidTarget(false))
  392. continue;
  393. std::vector<BattleHex> occupied = otherSt->getHexes();
  394. if(battleCanShoot(stack, otherSt->position))
  395. {
  396. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  397. continue;
  398. }
  399. for(BattleHex he : occupied)
  400. {
  401. if(meleeAttackable(he))
  402. attackable->push_back(he);
  403. }
  404. }
  405. }
  406. //adding occupiable likely adds duplicates to ret -> clean it up
  407. boost::sort(ret);
  408. ret.erase(boost::unique(ret).end(), ret.end());
  409. return ret;
  410. }
  411. bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
  412. {
  413. RETURN_IF_NOT_BATTLE(false);
  414. if(battleTacticDist())
  415. return false;
  416. if (!stack || !target)
  417. return false;
  418. if(!battleMatchOwner(stack, target))
  419. return false;
  420. auto &id = stack->getCreature()->idNumber;
  421. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  422. return false;
  423. if (!target->alive())
  424. return false;
  425. return true;
  426. }
  427. bool CBattleInfoCallback::battleCanShoot(const CStack * stack, BattleHex dest) const
  428. {
  429. RETURN_IF_NOT_BATTLE(false);
  430. if(battleTacticDist()) //no shooting during tactics
  431. return false;
  432. const CStack * dst = battleGetStackByPos(dest);
  433. if(!stack || !dst)
  434. return false;
  435. //forgetfulness
  436. TBonusListPtr forgetfulList = stack->getBonuses(Selector::type(Bonus::FORGETFULL),"");
  437. if(!forgetfulList->empty())
  438. {
  439. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  440. //advanced+ level
  441. if(forgetful > 1)
  442. return false;
  443. }
  444. if(stack->getCreature()->idNumber == CreatureID::CATAPULT && dst) //catapult cannot attack creatures
  445. return false;
  446. if(stack->canShoot()
  447. && battleMatchOwner(stack, dst)
  448. && dst->alive()
  449. && (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING)))
  450. return true;
  451. return false;
  452. }
  453. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  454. {
  455. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  456. {
  457. auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
  458. auto limitMatches = info.shooting
  459. ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
  460. : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
  461. //any regular bonuses or just ones for melee/ranged
  462. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  463. };
  464. double additiveBonus = 1.0, multBonus = 1.0,
  465. minDmg = info.attackerBonuses->getMinDamage() * info.attackerHealth.getCount(),//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
  466. maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerHealth.getCount();
  467. const CCreature *attackerType = info.attacker->getCreature(),
  468. *defenderType = info.defender->getCreature();
  469. if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
  470. {
  471. SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  472. }
  473. if(info.attackerBonuses->hasBonusOfType(Bonus::SIEGE_WEAPON) && attackerType->idNumber != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  474. { //minDmg and maxDmg are multiplied by hero attack + 1
  475. auto retreiveHeroPrimSkill = [&](int skill) -> int
  476. {
  477. const std::shared_ptr<Bonus> b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  478. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  479. };
  480. minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  481. maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  482. }
  483. int attackDefenceDifference = 0;
  484. double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
  485. attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
  486. double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
  487. attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
  488. if(const std::shared_ptr<Bonus> slayerEffect = info.attackerBonuses->getBonus(Selector::type(Bonus::SLAYER))) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  489. {
  490. std::vector<int> affectedIds;
  491. int spLevel = slayerEffect->val;
  492. //FIXME: do not check all creatures
  493. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  494. {
  495. for(const std::shared_ptr<Bonus> b : VLC->creh->creatures[g]->getBonusList())
  496. {
  497. if ((b->type == Bonus::KING3 && spLevel >= 3) || //expert
  498. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  499. (b->type == Bonus::KING1 && spLevel >= 0)) //none or basic +
  500. {
  501. affectedIds.push_back(g);
  502. break;
  503. }
  504. }
  505. }
  506. for(auto & affectedId : affectedIds)
  507. {
  508. if(defenderType->idNumber == affectedId)
  509. {
  510. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
  511. break;
  512. }
  513. }
  514. }
  515. //bonus from attack/defense skills
  516. if(attackDefenceDifference < 0) //decreasing dmg
  517. {
  518. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  519. multBonus *= 1.0 - dec;
  520. }
  521. else //increasing dmg
  522. {
  523. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  524. additiveBonus += inc;
  525. }
  526. //applying jousting bonus
  527. if(info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY))
  528. additiveBonus += info.chargedFields * 0.05;
  529. //handling secondary abilities and artifacts giving premies to them
  530. if(info.shooting)
  531. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
  532. else
  533. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
  534. if(info.defenderBonuses)
  535. multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
  536. //handling hate effect
  537. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
  538. //luck bonus
  539. if (info.luckyHit)
  540. {
  541. additiveBonus += 1.0;
  542. }
  543. //unlucky hit, used only if negative luck is enabled
  544. if (info.unluckyHit)
  545. {
  546. additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
  547. }
  548. //ballista double dmg
  549. if(info.ballistaDoubleDamage)
  550. {
  551. additiveBonus += 1.0;
  552. }
  553. if (info.deathBlow) //Dread Knight and many WoGified creatures
  554. {
  555. additiveBonus += 1.0;
  556. }
  557. //handling spell effects
  558. if(!info.shooting) //eg. shield
  559. {
  560. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
  561. }
  562. else if(info.shooting) //eg. air shield
  563. {
  564. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
  565. }
  566. if(info.shooting)
  567. {
  568. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  569. //get list first, total value of 0 also counts
  570. TBonusListPtr forgetfulList = info.attackerBonuses->getBonuses(Selector::type(Bonus::FORGETFULL),"");
  571. if(!forgetfulList->empty())
  572. {
  573. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  574. //none of basic level
  575. if(forgetful == 0 || forgetful == 1)
  576. multBonus *= 0.5;
  577. else
  578. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  579. }
  580. }
  581. TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
  582. TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
  583. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  584. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo<std::shared_ptr<Bonus>>))->additionalInfo : 0;
  585. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  586. {
  587. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  588. }
  589. auto isAdvancedAirShield = [](const Bonus* bonus)
  590. {
  591. return bonus->source == Bonus::SPELL_EFFECT
  592. && bonus->sid == SpellID::AIR_SHIELD
  593. && bonus->val >= SecSkillLevel::ADVANCED;
  594. };
  595. //wall / distance penalty + advanced air shield
  596. const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  597. const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  598. if(info.shooting)
  599. {
  600. if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
  601. {
  602. multBonus *= 0.5;
  603. }
  604. if (obstaclePenalty)
  605. {
  606. multBonus *= 0.5; //cumulative
  607. }
  608. }
  609. if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  610. {
  611. multBonus *= 0.5;
  612. }
  613. // psychic elementals versus mind immune units 50%
  614. if(attackerType->idNumber == CreatureID::PSYCHIC_ELEMENTAL
  615. && info.defenderBonuses->hasBonusOfType(Bonus::MIND_IMMUNITY))
  616. {
  617. multBonus *= 0.5;
  618. }
  619. // TODO attack on petrified unit 50%
  620. // blinded unit retaliates
  621. minDmg *= additiveBonus * multBonus;
  622. maxDmg *= additiveBonus * multBonus;
  623. TDmgRange returnedVal;
  624. if(curseEffects->size()) //curse handling (rest)
  625. {
  626. minDmg += curseBlessAdditiveModifier;
  627. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  628. }
  629. else if(blessEffects->size()) //bless handling
  630. {
  631. maxDmg += curseBlessAdditiveModifier;
  632. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  633. }
  634. else
  635. {
  636. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  637. }
  638. //damage cannot be less than 1
  639. vstd::amax(returnedVal.first, 1);
  640. vstd::amax(returnedVal.second, 1);
  641. return returnedVal;
  642. }
  643. TDmgRange CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  644. {
  645. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  646. const bool shooting = battleCanShoot(attacker, defender->position);
  647. const BattleAttackInfo bai(attacker, defender, shooting);
  648. return battleEstimateDamage(rand, bai, retaliationDmg);
  649. }
  650. std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const BattleAttackInfo & bai, std::pair<ui32, ui32> * retaliationDmg) const
  651. {
  652. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  653. //const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
  654. TDmgRange ret = calculateDmgRange(bai);
  655. if(retaliationDmg)
  656. {
  657. if(bai.shooting)
  658. {
  659. retaliationDmg->first = retaliationDmg->second = 0;
  660. }
  661. else
  662. {
  663. ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  664. for (int i=0; i<2; ++i)
  665. {
  666. BattleStackAttacked bsa;
  667. bsa.damageAmount = ret.*pairElems[i];
  668. bai.defender->prepareAttacked(bsa, rand, bai.defenderHealth);
  669. auto retaliationAttack = bai.reverse();
  670. retaliationAttack.attackerHealth = retaliationAttack.attacker->healthAfterAttacked(bsa.damageAmount);
  671. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  672. }
  673. }
  674. }
  675. return ret;
  676. }
  677. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  678. {
  679. std::vector<std::shared_ptr<const CObstacleInstance>> obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  680. RETURN_IF_NOT_BATTLE(obstacles);
  681. for(auto & obs : battleGetAllObstacles())
  682. {
  683. if(vstd::contains(obs->getBlockedTiles(), tile)
  684. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  685. {
  686. obstacles.push_back(obs);
  687. }
  688. }
  689. return obstacles;
  690. }
  691. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const CStack * stack) const
  692. {
  693. std::vector<std::shared_ptr<const CObstacleInstance>> affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  694. RETURN_IF_NOT_BATTLE(affectedObstacles);
  695. if(stack->alive())
  696. {
  697. affectedObstacles = battleGetAllObstaclesOnPos(stack->position, false);
  698. if(stack->doubleWide())
  699. {
  700. BattleHex otherHex = stack->occupiedHex(stack->position);
  701. if(otherHex.isValid())
  702. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  703. affectedObstacles.push_back(i);
  704. }
  705. for(auto hex : stack->getHexes())
  706. if(hex == ESiegeHex::GATE_BRIDGE)
  707. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  708. for(int i=0; i<affectedObstacles.size(); i++)
  709. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  710. affectedObstacles.erase(affectedObstacles.begin()+i);
  711. }
  712. return affectedObstacles;
  713. }
  714. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  715. {
  716. AccessibilityInfo ret;
  717. ret.fill(EAccessibility::ACCESSIBLE);
  718. //removing accessibility for side columns of hexes
  719. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  720. {
  721. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  722. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  723. }
  724. //special battlefields with logically unavailable tiles
  725. std::vector<BattleHex> impassableHexes;
  726. if(battleGetBattlefieldType().num == BFieldType::SHIP_TO_SHIP)
  727. {
  728. impassableHexes =
  729. {
  730. 6, 7, 8, 9,
  731. 24, 25, 26,
  732. 58, 59, 60,
  733. 75, 76, 77,
  734. 92, 93, 94,
  735. 109, 110, 111,
  736. 126, 127, 128,
  737. 159, 160, 161, 162, 163,
  738. 176, 177, 178, 179, 180
  739. };
  740. }
  741. for(auto hex : impassableHexes)
  742. ret[hex] = EAccessibility::UNAVAILABLE;
  743. //gate -> should be before stacks
  744. if(battleGetSiegeLevel() > 0)
  745. {
  746. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  747. switch(battleGetGateState())
  748. {
  749. case EGateState::CLOSED:
  750. accessability = EAccessibility::GATE;
  751. break;
  752. case EGateState::BLOCKED:
  753. accessability = EAccessibility::UNAVAILABLE;
  754. break;
  755. }
  756. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  757. }
  758. //tiles occupied by standing stacks
  759. for(auto stack : battleAliveStacks())
  760. {
  761. for(auto hex : stack->getHexes())
  762. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  763. ret[hex] = EAccessibility::ALIVE_STACK;
  764. }
  765. //obstacles
  766. for(const auto &obst : battleGetAllObstacles())
  767. {
  768. for(auto hex : obst->getBlockedTiles())
  769. ret[hex] = EAccessibility::OBSTACLE;
  770. }
  771. //walls
  772. if(battleGetSiegeLevel() > 0)
  773. {
  774. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  775. for(auto hex : permanentlyLocked)
  776. ret[hex] = EAccessibility::UNAVAILABLE;
  777. //TODO likely duplicated logic
  778. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] =
  779. {
  780. //which part of wall, which hex is blocked if this part of wall is not destroyed
  781. std::make_pair(2, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  782. std::make_pair(3, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  783. std::make_pair(4, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  784. std::make_pair(5, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  785. };
  786. for(auto & elem : lockedIfNotDestroyed)
  787. {
  788. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  789. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  790. }
  791. }
  792. return ret;
  793. }
  794. AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack * stack) const
  795. {
  796. return getAccesibility(stack->getHexes());
  797. }
  798. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  799. {
  800. auto ret = getAccesibility();
  801. for(auto hex : accessibleHexes)
  802. if(hex.isValid())
  803. ret[hex] = EAccessibility::ACCESSIBLE;
  804. return ret;
  805. }
  806. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  807. {
  808. ReachabilityInfo ret;
  809. ret.accessibility = accessibility;
  810. ret.params = params;
  811. ret.predecessors.fill(BattleHex::INVALID);
  812. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  813. if(!params.startPosition.isValid()) //if got call for arrow turrets
  814. return ret;
  815. const std::set<BattleHex> quicksands = getStoppers(params.perspective);
  816. //const bool twoHexCreature = params.doubleWide;
  817. std::queue<BattleHex> hexq; //bfs queue
  818. //first element
  819. hexq.push(params.startPosition);
  820. ret.distances[params.startPosition] = 0;
  821. while(!hexq.empty()) //bfs loop
  822. {
  823. const BattleHex curHex = hexq.front();
  824. hexq.pop();
  825. //walking stack can't step past the quicksands
  826. //TODO what if second hex of two-hex creature enters quicksand
  827. if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
  828. continue;
  829. const int costToNeighbour = ret.distances[curHex] + 1;
  830. for(BattleHex neighbour : curHex.neighbouringTiles())
  831. {
  832. const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.side);
  833. const int costFoundSoFar = ret.distances[neighbour];
  834. if(accessible && costToNeighbour < costFoundSoFar)
  835. {
  836. hexq.push(neighbour);
  837. ret.distances[neighbour] = costToNeighbour;
  838. ret.predecessors[neighbour] = curHex;
  839. }
  840. }
  841. }
  842. return ret;
  843. }
  844. ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack * stack) const
  845. {
  846. return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
  847. }
  848. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  849. {
  850. std::set<BattleHex> ret;
  851. RETURN_IF_NOT_BATTLE(ret);
  852. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  853. {
  854. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  855. {
  856. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  857. }
  858. }
  859. return ret;
  860. }
  861. std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, BattleSideOpt side) const
  862. {
  863. auto reachability = getReachability(closest);
  864. auto avHexes = battleGetAvailableHexes(closest, false);
  865. // I hate std::pairs with their undescriptive member names first / second
  866. struct DistStack
  867. {
  868. int distanceToPred;
  869. BattleHex destination;
  870. const CStack * stack;
  871. };
  872. std::vector<DistStack> stackPairs;
  873. std::vector<const CStack *> possibleStacks = battleGetStacksIf([=](const CStack * s)
  874. {
  875. return s->isValidTarget(false) && s != closest && (!side || side.get() == s->side);
  876. });
  877. for(const CStack * st : possibleStacks)
  878. for(BattleHex hex : avHexes)
  879. if(CStack::isMeleeAttackPossible(closest, st, hex))
  880. {
  881. DistStack hlp = {reachability.distances[hex], hex, st};
  882. stackPairs.push_back(hlp);
  883. }
  884. if (stackPairs.size())
  885. {
  886. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  887. auto minimal = boost::min_element(stackPairs, comparator);
  888. return std::make_pair(minimal->stack, minimal->destination);
  889. }
  890. else
  891. return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
  892. }
  893. si8 CBattleInfoCallback::battleGetTacticDist() const
  894. {
  895. RETURN_IF_NOT_BATTLE(0);
  896. //TODO get rid of this method
  897. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  898. return battleTacticDist();
  899. return 0;
  900. }
  901. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  902. {
  903. RETURN_IF_NOT_BATTLE(false);
  904. auto side = battleGetTacticsSide();
  905. auto dist = battleGetTacticDist();
  906. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  907. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  908. }
  909. ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
  910. {
  911. ReachabilityInfo::Parameters params(stack);
  912. if(!battleDoWeKnowAbout(stack->side))
  913. {
  914. //Stack is held by enemy, we can't use his perspective to check for reachability.
  915. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  916. params.perspective = battleGetMySide();
  917. }
  918. return getReachability(params);
  919. }
  920. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  921. {
  922. if(params.flying)
  923. return getFlyingReachability(params);
  924. else
  925. return makeBFS(getAccesibility(params.knownAccessible), params);
  926. }
  927. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  928. {
  929. ReachabilityInfo ret;
  930. ret.accessibility = getAccesibility(params.knownAccessible);
  931. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  932. {
  933. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  934. {
  935. ret.predecessors[i] = params.startPosition;
  936. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  937. }
  938. }
  939. return ret;
  940. }
  941. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  942. {
  943. //does not return hex attacked directly
  944. //TODO: apply rotation to two-hex attackers
  945. bool isAttacker = attacker->side == BattleSide::ATTACKER;
  946. AttackableTiles at;
  947. RETURN_IF_NOT_BATTLE(at);
  948. const int WN = GameConstants::BFIELD_WIDTH;
  949. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  950. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  951. bool reverse = isToReverse(hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  952. if(reverse && attacker->doubleWide())
  953. {
  954. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  955. }
  956. if(attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  957. {
  958. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  959. }
  960. if(attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  961. {
  962. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  963. for(BattleHex tile : hexes)
  964. {
  965. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  966. {
  967. const CStack * st = battleGetStackByPos(tile, true);
  968. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  969. {
  970. at.hostileCreaturePositions.insert(tile);
  971. }
  972. }
  973. }
  974. }
  975. if(attacker->hasBonusOfType(Bonus::WIDE_BREATH))
  976. {
  977. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  978. for(int i = 0; i<hexes.size(); i++)
  979. {
  980. if(hexes.at(i) == hex) {
  981. hexes.erase(hexes.begin() + i);
  982. i = 0;
  983. }
  984. }
  985. for(BattleHex tile : hexes)
  986. {
  987. //friendly stacks can also be damaged by Dragon Breath
  988. if(battleGetStackByPos(tile, true))
  989. if(battleGetStackByPos(tile, true) != attacker)
  990. at.friendlyCreaturePositions.insert(tile);
  991. }
  992. }
  993. else if(attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition(destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  994. {
  995. std::vector<BattleHex> hexes; //only one, in fact
  996. int pseudoVector = destinationTile.hex - hex;
  997. switch(pseudoVector)
  998. {
  999. case 1:
  1000. case -1:
  1001. BattleHex::checkAndPush(destinationTile.hex + pseudoVector, hexes);
  1002. break;
  1003. case WN: //17 //left-down or right-down
  1004. case -WN: //-17 //left-up or right-up
  1005. case WN + 1: //18 //right-down
  1006. case -WN + 1: //-16 //right-up
  1007. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : -1), hexes);
  1008. break;
  1009. case WN - 1: //16 //left-down
  1010. case -WN - 1: //-18 //left-up
  1011. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : 0), hexes);
  1012. break;
  1013. }
  1014. for(BattleHex tile : hexes)
  1015. {
  1016. //friendly stacks can also be damaged by Dragon Breath
  1017. if(battleGetStackByPos(tile, true))
  1018. at.friendlyCreaturePositions.insert(tile);
  1019. }
  1020. }
  1021. return at;
  1022. }
  1023. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const CStack * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1024. {
  1025. //does not return hex attacked directly
  1026. AttackableTiles at;
  1027. RETURN_IF_NOT_BATTLE(at);
  1028. if(attacker->hasBonusOfType(Bonus::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1029. {
  1030. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1031. targetHexes.push_back(destinationTile);
  1032. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1033. }
  1034. return at;
  1035. }
  1036. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1037. {
  1038. std::set<const CStack*> attackedCres;
  1039. RETURN_IF_NOT_BATTLE(attackedCres);
  1040. AttackableTiles at;
  1041. if(rangedAttack)
  1042. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1043. else
  1044. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1045. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1046. {
  1047. const CStack * st = battleGetStackByPos(tile, true);
  1048. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1049. {
  1050. attackedCres.insert(st);
  1051. }
  1052. }
  1053. for (BattleHex tile : at.friendlyCreaturePositions)
  1054. {
  1055. const CStack * st = battleGetStackByPos(tile, true);
  1056. if(st) //friendly stacks can also be damaged by Dragon Breath
  1057. {
  1058. attackedCres.insert(st);
  1059. }
  1060. }
  1061. return attackedCres;
  1062. }
  1063. //TODO: this should apply also to mechanics and cursor interface
  1064. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1065. {
  1066. int fromX = hexFrom.getX();
  1067. int fromY = hexFrom.getY();
  1068. int toX = hexTo.getX();
  1069. int toY = hexTo.getY();
  1070. if (curDir) // attacker, facing right
  1071. {
  1072. if (fromX < toX)
  1073. return false;
  1074. if (fromX > toX)
  1075. return true;
  1076. if (fromY % 2 == 0 && toY % 2 == 1)
  1077. return true;
  1078. return false;
  1079. }
  1080. else // defender, facing left
  1081. {
  1082. if(fromX < toX)
  1083. return true;
  1084. if(fromX > toX)
  1085. return false;
  1086. if (fromY % 2 == 1 && toY % 2 == 0)
  1087. return true;
  1088. return false;
  1089. }
  1090. }
  1091. //TODO: this should apply also to mechanics and cursor interface
  1092. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1093. {
  1094. if (hexTo < 0 || hexFrom < 0) //turret
  1095. return false;
  1096. if (toDoubleWide)
  1097. {
  1098. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1099. {
  1100. if (toDir)
  1101. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1102. else
  1103. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1104. }
  1105. return false;
  1106. }
  1107. else
  1108. {
  1109. return isToReverseHlp(hexFrom, hexTo, curDir);
  1110. }
  1111. }
  1112. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex, BattleHex * predecessors) const
  1113. {
  1114. ReachabilityInfo::TDistances ret;
  1115. ret.fill(-1);
  1116. RETURN_IF_NOT_BATTLE(ret);
  1117. ReachabilityInfo::Parameters params(stack);
  1118. params.perspective = battleGetMySide();
  1119. params.startPosition = hex.isValid() ? hex : stack->position;
  1120. auto reachability = getReachability(params);
  1121. boost::copy(reachability.distances, ret.begin());
  1122. if(predecessors)
  1123. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1124. predecessors[i] = reachability.predecessors[i];
  1125. return ret;
  1126. }
  1127. si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
  1128. {
  1129. return battleHasDistancePenalty(stack, stack->position, destHex);
  1130. }
  1131. si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  1132. {
  1133. RETURN_IF_NOT_BATTLE(false);
  1134. if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
  1135. return false;
  1136. if(const CStack * dstStack = battleGetStackByPos(destHex, false))
  1137. {
  1138. //If any hex of target creature is within range, there is no penalty
  1139. for(auto hex : dstStack->getHexes())
  1140. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1141. return false;
  1142. //TODO what about two-hex shooters?
  1143. }
  1144. else
  1145. {
  1146. if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1147. return false;
  1148. }
  1149. return true;
  1150. }
  1151. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1152. {
  1153. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1154. return WallPartToHex(part);
  1155. }
  1156. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1157. {
  1158. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1159. return hexToWallPart(hex);
  1160. }
  1161. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1162. {
  1163. RETURN_IF_NOT_BATTLE(false);
  1164. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1165. wallPart != EWallPart::INVALID;
  1166. }
  1167. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1168. {
  1169. std::vector<BattleHex> attackableBattleHexes;
  1170. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1171. for(auto & wallPartPair : wallParts)
  1172. {
  1173. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1174. {
  1175. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1176. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1177. {
  1178. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1179. }
  1180. }
  1181. }
  1182. return attackableBattleHexes;
  1183. }
  1184. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1185. {
  1186. RETURN_IF_NOT_BATTLE(-1);
  1187. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1188. ui32 ret = caster->getSpellCost(sp);
  1189. //checking for friendly stacks reducing cost of the spell and
  1190. //enemy stacks increasing it
  1191. si32 manaReduction = 0;
  1192. si32 manaIncrease = 0;
  1193. for(auto stack : battleAliveStacks())
  1194. {
  1195. if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1196. {
  1197. vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1198. }
  1199. if(stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1200. {
  1201. vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1202. }
  1203. }
  1204. return ret - manaReduction + manaIncrease;
  1205. }
  1206. const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
  1207. {
  1208. RETURN_IF_NOT_BATTLE(nullptr);
  1209. auto stacks = battleGetAllStacks();
  1210. auto stackItr = range::find_if(stacks, pred);
  1211. return stackItr == stacks.end() ? nullptr : *stackItr;
  1212. }
  1213. si8 CBattleInfoCallback::battleHasShootingPenalty(const CStack * stack, BattleHex destHex)
  1214. {
  1215. return battleHasDistancePenalty(stack, destHex) || battleHasWallPenalty(stack, destHex);
  1216. }
  1217. bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
  1218. {
  1219. RETURN_IF_NOT_BATTLE(false);
  1220. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1221. return false;
  1222. for(const CStack * s : batteAdjacentCreatures(stack))
  1223. {
  1224. if (s->owner != stack->owner) //blocked by enemy stack
  1225. return true;
  1226. }
  1227. return false;
  1228. }
  1229. std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
  1230. {
  1231. std::set<const CStack*> stacks;
  1232. RETURN_IF_NOT_BATTLE(stacks);
  1233. for (BattleHex hex : stack->getSurroundingHexes())
  1234. if(const CStack * neighbour = battleGetStackByPos(hex, true))
  1235. stacks.insert(neighbour);
  1236. return stacks;
  1237. }
  1238. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1239. {
  1240. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1241. //This is complete list. No spells from mods.
  1242. //todo: this should be Spellbook of caster Stack
  1243. static const std::set<SpellID> allPossibleSpells =
  1244. {
  1245. SpellID::AIR_SHIELD,
  1246. SpellID::ANTI_MAGIC,
  1247. SpellID::BLESS,
  1248. SpellID::BLOODLUST,
  1249. SpellID::COUNTERSTRIKE,
  1250. SpellID::CURE,
  1251. SpellID::FIRE_SHIELD,
  1252. SpellID::FORTUNE,
  1253. SpellID::HASTE,
  1254. SpellID::MAGIC_MIRROR,
  1255. SpellID::MIRTH,
  1256. SpellID::PRAYER,
  1257. SpellID::PRECISION,
  1258. SpellID::PROTECTION_FROM_AIR,
  1259. SpellID::PROTECTION_FROM_EARTH,
  1260. SpellID::PROTECTION_FROM_FIRE,
  1261. SpellID::PROTECTION_FROM_WATER,
  1262. SpellID::SHIELD,
  1263. SpellID::SLAYER,
  1264. SpellID::STONE_SKIN
  1265. };
  1266. std::vector<SpellID> beneficialSpells;
  1267. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred)
  1268. {
  1269. return getStackIf([=](const CStack * stack)
  1270. {
  1271. return pred(stack) && stack->owner != subject->owner && stack->alive();
  1272. });
  1273. };
  1274. for(const SpellID spellID : allPossibleSpells)
  1275. {
  1276. std::stringstream cachingStr;
  1277. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1278. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1279. //TODO: this ability has special limitations
  1280. || spellID.toSpell()->canBeCast(this, ECastingMode::CREATURE_ACTIVE_CASTING, subject) != ESpellCastProblem::OK)
  1281. continue;
  1282. switch (spellID)
  1283. {
  1284. case SpellID::SHIELD:
  1285. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1286. {
  1287. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1288. {
  1289. return !stack->canShoot();
  1290. });
  1291. if (!walker)
  1292. continue;
  1293. }
  1294. break;
  1295. case SpellID::AIR_SHIELD: //only against active shooters
  1296. {
  1297. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1298. {
  1299. return stack->canShoot();
  1300. });
  1301. if (!shooter)
  1302. continue;
  1303. }
  1304. break;
  1305. case SpellID::ANTI_MAGIC:
  1306. case SpellID::MAGIC_MIRROR:
  1307. case SpellID::PROTECTION_FROM_AIR:
  1308. case SpellID::PROTECTION_FROM_EARTH:
  1309. case SpellID::PROTECTION_FROM_FIRE:
  1310. case SpellID::PROTECTION_FROM_WATER:
  1311. {
  1312. const ui8 enemySide = 1 - subject->side;
  1313. //todo: only if enemy has spellbook
  1314. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1315. continue;
  1316. }
  1317. break;
  1318. case SpellID::CURE: //only damaged units
  1319. {
  1320. //do not cast on affected by debuffs
  1321. if(!subject->canBeHealed())
  1322. continue;
  1323. }
  1324. break;
  1325. case SpellID::BLOODLUST:
  1326. {
  1327. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1328. continue;
  1329. }
  1330. break;
  1331. case SpellID::PRECISION:
  1332. {
  1333. if(!subject->canShoot())
  1334. continue;
  1335. }
  1336. break;
  1337. case SpellID::SLAYER://only if monsters are present
  1338. {
  1339. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1340. {
  1341. const auto isKing = Selector::type(Bonus::KING1)
  1342. .Or(Selector::type(Bonus::KING2))
  1343. .Or(Selector::type(Bonus::KING3));
  1344. return stack->hasBonus(isKing);
  1345. });
  1346. if (!kingMonster)
  1347. continue;
  1348. }
  1349. break;
  1350. }
  1351. beneficialSpells.push_back(spellID);
  1352. }
  1353. if(!beneficialSpells.empty())
  1354. {
  1355. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1356. }
  1357. else
  1358. {
  1359. return SpellID::NONE;
  1360. }
  1361. }
  1362. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1363. {
  1364. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1365. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1366. if (!bl->size())
  1367. return SpellID::NONE;
  1368. int totalWeight = 0;
  1369. for(auto b : *bl)
  1370. {
  1371. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1372. }
  1373. int randomPos = rand.nextInt(totalWeight - 1);
  1374. for(auto b : *bl)
  1375. {
  1376. randomPos -= std::max(b->additionalInfo, 1);
  1377. if(randomPos < 0)
  1378. {
  1379. return SpellID(b->subtype);
  1380. }
  1381. }
  1382. return SpellID::NONE;
  1383. }
  1384. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1385. {
  1386. RETURN_IF_NOT_BATTLE(-3);
  1387. if(!battleCanSurrender(Player))
  1388. return -1;
  1389. const auto side = playerToSide(Player);
  1390. if(!side)
  1391. return -1;
  1392. int ret = 0;
  1393. double discount = 0;
  1394. for(const CStack * s : battleAliveStacks(side.get()))
  1395. if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
  1396. ret += s->getCreature()->cost[Res::GOLD] * s->getCount(); //todo: extract CStack method
  1397. if(const CGHeroInstance * h = battleGetFightingHero(side.get()))
  1398. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1399. ret *= (100.0 - discount) / 100.0;
  1400. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1401. return ret;
  1402. }
  1403. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1404. {
  1405. const IBonusBearer *node = nullptr;
  1406. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1407. node = h;
  1408. else
  1409. node = getBattleNode();
  1410. if(!node)
  1411. return 1;
  1412. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_BELOW));
  1413. if(b->size())
  1414. return b->totalValue();
  1415. return 1;
  1416. }
  1417. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1418. {
  1419. const IBonusBearer *node = nullptr;
  1420. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1421. node = h;
  1422. else
  1423. node = getBattleNode();
  1424. if(!node)
  1425. return GameConstants::SPELL_LEVELS;
  1426. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1427. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1428. if(b->size())
  1429. return b->totalValue();
  1430. return GameConstants::SPELL_LEVELS;
  1431. }
  1432. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1433. {
  1434. auto stacks = battleGetAllStacks();
  1435. //checking winning condition
  1436. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
  1437. hasStack[0] = hasStack[1] = false;
  1438. for(auto & stack : stacks)
  1439. {
  1440. if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1441. {
  1442. hasStack[stack->side] = true;
  1443. }
  1444. }
  1445. if(!hasStack[0] && !hasStack[1])
  1446. return 2;
  1447. if(!hasStack[1])
  1448. return 0;
  1449. if(!hasStack[0])
  1450. return 1;
  1451. return boost::none;
  1452. }