CBattleInfoCallback.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  976. {
  977. std::vector<BattleHex> hexes; //only one, in fact
  978. int pseudoVector = destinationTile.hex - hex;
  979. switch (pseudoVector)
  980. {
  981. case 1:
  982. case -1:
  983. BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
  984. break;
  985. case WN: //17 //left-down or right-down
  986. case -WN: //-17 //left-up or right-up
  987. case WN + 1: //18 //right-down
  988. case -WN + 1: //-16 //right-up
  989. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : -1), hexes);
  990. break;
  991. case WN-1: //16 //left-down
  992. case -WN-1: //-18 //left-up
  993. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : 0), hexes);
  994. break;
  995. }
  996. for (BattleHex tile : hexes)
  997. {
  998. //friendly stacks can also be damaged by Dragon Breath
  999. if (battleGetStackByPos (tile, true))
  1000. at.friendlyCreaturePositions.insert (tile);
  1001. }
  1002. }
  1003. return at;
  1004. }
  1005. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1006. {
  1007. std::set<const CStack*> attackedCres;
  1008. RETURN_IF_NOT_BATTLE(attackedCres);
  1009. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1010. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1011. {
  1012. const CStack * st = battleGetStackByPos(tile, true);
  1013. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1014. {
  1015. attackedCres.insert(st);
  1016. }
  1017. }
  1018. for (BattleHex tile : at.friendlyCreaturePositions)
  1019. {
  1020. const CStack * st = battleGetStackByPos(tile, true);
  1021. if(st) //friendly stacks can also be damaged by Dragon Breath
  1022. {
  1023. attackedCres.insert(st);
  1024. }
  1025. }
  1026. return attackedCres;
  1027. }
  1028. //TODO: this should apply also to mechanics and cursor interface
  1029. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1030. {
  1031. int fromX = hexFrom.getX();
  1032. int fromY = hexFrom.getY();
  1033. int toX = hexTo.getX();
  1034. int toY = hexTo.getY();
  1035. if (curDir) // attacker, facing right
  1036. {
  1037. if (fromX < toX)
  1038. return false;
  1039. if (fromX > toX)
  1040. return true;
  1041. if (fromY % 2 == 0 && toY % 2 == 1)
  1042. return true;
  1043. return false;
  1044. }
  1045. else // defender, facing left
  1046. {
  1047. if(fromX < toX)
  1048. return true;
  1049. if(fromX > toX)
  1050. return false;
  1051. if (fromY % 2 == 1 && toY % 2 == 0)
  1052. return true;
  1053. return false;
  1054. }
  1055. }
  1056. //TODO: this should apply also to mechanics and cursor interface
  1057. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1058. {
  1059. if (hexTo < 0 || hexFrom < 0) //turret
  1060. return false;
  1061. if (toDoubleWide)
  1062. {
  1063. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1064. {
  1065. if (toDir)
  1066. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1067. else
  1068. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1069. }
  1070. return false;
  1071. }
  1072. else
  1073. {
  1074. return isToReverseHlp(hexFrom, hexTo, curDir);
  1075. }
  1076. }
  1077. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex, BattleHex * predecessors) const
  1078. {
  1079. ReachabilityInfo::TDistances ret;
  1080. ret.fill(-1);
  1081. RETURN_IF_NOT_BATTLE(ret);
  1082. ReachabilityInfo::Parameters params(stack);
  1083. params.perspective = battleGetMySide();
  1084. params.startPosition = hex.isValid() ? hex : stack->position;
  1085. auto reachability = getReachability(params);
  1086. boost::copy(reachability.distances, ret.begin());
  1087. if(predecessors)
  1088. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1089. predecessors[i] = reachability.predecessors[i];
  1090. return ret;
  1091. }
  1092. si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
  1093. {
  1094. return battleHasDistancePenalty(stack, stack->position, destHex);
  1095. }
  1096. si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  1097. {
  1098. RETURN_IF_NOT_BATTLE(false);
  1099. if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
  1100. return false;
  1101. if(const CStack * dstStack = battleGetStackByPos(destHex, false))
  1102. {
  1103. //If any hex of target creature is within range, there is no penalty
  1104. for(auto hex : dstStack->getHexes())
  1105. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1106. return false;
  1107. //TODO what about two-hex shooters?
  1108. }
  1109. else
  1110. {
  1111. if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1112. return false;
  1113. }
  1114. return true;
  1115. }
  1116. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1117. {
  1118. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1119. return WallPartToHex(part);
  1120. }
  1121. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1122. {
  1123. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1124. return hexToWallPart(hex);
  1125. }
  1126. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1127. {
  1128. RETURN_IF_NOT_BATTLE(false);
  1129. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1130. wallPart != EWallPart::INVALID;
  1131. }
  1132. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1133. {
  1134. std::vector<BattleHex> attackableBattleHexes;
  1135. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1136. for(auto & wallPartPair : wallParts)
  1137. {
  1138. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1139. {
  1140. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1141. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1142. {
  1143. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1144. }
  1145. }
  1146. }
  1147. return attackableBattleHexes;
  1148. }
  1149. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1150. {
  1151. RETURN_IF_NOT_BATTLE(-1);
  1152. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1153. ui32 ret = caster->getSpellCost(sp);
  1154. //checking for friendly stacks reducing cost of the spell and
  1155. //enemy stacks increasing it
  1156. si32 manaReduction = 0;
  1157. si32 manaIncrease = 0;
  1158. for(auto stack : battleAliveStacks())
  1159. {
  1160. if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1161. {
  1162. vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1163. }
  1164. if(stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1165. {
  1166. vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1167. }
  1168. }
  1169. return ret - manaReduction + manaIncrease;
  1170. }
  1171. const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
  1172. {
  1173. RETURN_IF_NOT_BATTLE(nullptr);
  1174. auto stacks = battleGetAllStacks();
  1175. auto stackItr = range::find_if(stacks, pred);
  1176. return stackItr == stacks.end() ? nullptr : *stackItr;
  1177. }
  1178. si8 CBattleInfoCallback::battleHasShootingPenalty(const CStack * stack, BattleHex destHex)
  1179. {
  1180. return battleHasDistancePenalty(stack, destHex) || battleHasWallPenalty(stack, destHex);
  1181. }
  1182. bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
  1183. {
  1184. RETURN_IF_NOT_BATTLE(false);
  1185. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1186. return false;
  1187. for(const CStack * s : batteAdjacentCreatures(stack))
  1188. {
  1189. if (s->owner != stack->owner) //blocked by enemy stack
  1190. return true;
  1191. }
  1192. return false;
  1193. }
  1194. std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
  1195. {
  1196. std::set<const CStack*> stacks;
  1197. RETURN_IF_NOT_BATTLE(stacks);
  1198. for (BattleHex hex : stack->getSurroundingHexes())
  1199. if(const CStack * neighbour = battleGetStackByPos(hex, true))
  1200. stacks.insert(neighbour);
  1201. return stacks;
  1202. }
  1203. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1204. {
  1205. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1206. //This is complete list. No spells from mods.
  1207. //todo: this should be Spellbook of caster Stack
  1208. static const std::set<SpellID> allPossibleSpells =
  1209. {
  1210. SpellID::AIR_SHIELD,
  1211. SpellID::ANTI_MAGIC,
  1212. SpellID::BLESS,
  1213. SpellID::BLOODLUST,
  1214. SpellID::COUNTERSTRIKE,
  1215. SpellID::CURE,
  1216. SpellID::FIRE_SHIELD,
  1217. SpellID::FORTUNE,
  1218. SpellID::HASTE,
  1219. SpellID::MAGIC_MIRROR,
  1220. SpellID::MIRTH,
  1221. SpellID::PRAYER,
  1222. SpellID::PRECISION,
  1223. SpellID::PROTECTION_FROM_AIR,
  1224. SpellID::PROTECTION_FROM_EARTH,
  1225. SpellID::PROTECTION_FROM_FIRE,
  1226. SpellID::PROTECTION_FROM_WATER,
  1227. SpellID::SHIELD,
  1228. SpellID::SLAYER,
  1229. SpellID::STONE_SKIN
  1230. };
  1231. std::vector<SpellID> beneficialSpells;
  1232. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred)
  1233. {
  1234. return getStackIf([=](const CStack * stack)
  1235. {
  1236. return pred(stack) && stack->owner != subject->owner && stack->alive();
  1237. });
  1238. };
  1239. for(const SpellID spellID : allPossibleSpells)
  1240. {
  1241. std::stringstream cachingStr;
  1242. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1243. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1244. //TODO: this ability has special limitations
  1245. || spellID.toSpell()->canBeCast(this, ECastingMode::CREATURE_ACTIVE_CASTING, subject) != ESpellCastProblem::OK)
  1246. continue;
  1247. switch (spellID)
  1248. {
  1249. case SpellID::SHIELD:
  1250. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1251. {
  1252. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1253. {
  1254. return !stack->canShoot();
  1255. });
  1256. if (!walker)
  1257. continue;
  1258. }
  1259. break;
  1260. case SpellID::AIR_SHIELD: //only against active shooters
  1261. {
  1262. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1263. {
  1264. return stack->canShoot();
  1265. });
  1266. if (!shooter)
  1267. continue;
  1268. }
  1269. break;
  1270. case SpellID::ANTI_MAGIC:
  1271. case SpellID::MAGIC_MIRROR:
  1272. case SpellID::PROTECTION_FROM_AIR:
  1273. case SpellID::PROTECTION_FROM_EARTH:
  1274. case SpellID::PROTECTION_FROM_FIRE:
  1275. case SpellID::PROTECTION_FROM_WATER:
  1276. {
  1277. const ui8 enemySide = 1 - subject->side;
  1278. //todo: only if enemy has spellbook
  1279. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1280. continue;
  1281. }
  1282. break;
  1283. case SpellID::CURE: //only damaged units
  1284. {
  1285. //do not cast on affected by debuffs
  1286. if(!subject->canBeHealed())
  1287. continue;
  1288. }
  1289. break;
  1290. case SpellID::BLOODLUST:
  1291. {
  1292. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1293. continue;
  1294. }
  1295. break;
  1296. case SpellID::PRECISION:
  1297. {
  1298. if(!subject->canShoot())
  1299. continue;
  1300. }
  1301. break;
  1302. case SpellID::SLAYER://only if monsters are present
  1303. {
  1304. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1305. {
  1306. const auto isKing = Selector::type(Bonus::KING1)
  1307. .Or(Selector::type(Bonus::KING2))
  1308. .Or(Selector::type(Bonus::KING3));
  1309. return stack->hasBonus(isKing);
  1310. });
  1311. if (!kingMonster)
  1312. continue;
  1313. }
  1314. break;
  1315. }
  1316. beneficialSpells.push_back(spellID);
  1317. }
  1318. if(!beneficialSpells.empty())
  1319. {
  1320. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1321. }
  1322. else
  1323. {
  1324. return SpellID::NONE;
  1325. }
  1326. }
  1327. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1328. {
  1329. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1330. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1331. if (!bl->size())
  1332. return SpellID::NONE;
  1333. int totalWeight = 0;
  1334. for(auto b : *bl)
  1335. {
  1336. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1337. }
  1338. int randomPos = rand.nextInt(totalWeight - 1);
  1339. for(auto b : *bl)
  1340. {
  1341. randomPos -= std::max(b->additionalInfo, 1);
  1342. if(randomPos < 0)
  1343. {
  1344. return SpellID(b->subtype);
  1345. }
  1346. }
  1347. return SpellID::NONE;
  1348. }
  1349. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1350. {
  1351. RETURN_IF_NOT_BATTLE(-3);
  1352. if(!battleCanSurrender(Player))
  1353. return -1;
  1354. const auto side = playerToSide(Player);
  1355. if(!side)
  1356. return -1;
  1357. int ret = 0;
  1358. double discount = 0;
  1359. for(const CStack * s : battleAliveStacks(side.get()))
  1360. if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
  1361. ret += s->getCreature()->cost[Res::GOLD] * s->getCount(); //todo: extract CStack method
  1362. if(const CGHeroInstance * h = battleGetFightingHero(side.get()))
  1363. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1364. ret *= (100.0 - discount) / 100.0;
  1365. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1366. return ret;
  1367. }
  1368. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1369. {
  1370. const IBonusBearer *node = nullptr;
  1371. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1372. node = h;
  1373. else
  1374. node = getBattleNode();
  1375. if(!node)
  1376. return GameConstants::SPELL_LEVELS;
  1377. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1378. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1379. if(b->size())
  1380. return b->totalValue();
  1381. return GameConstants::SPELL_LEVELS;
  1382. }
  1383. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1384. {
  1385. auto stacks = battleGetAllStacks();
  1386. //checking winning condition
  1387. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
  1388. hasStack[0] = hasStack[1] = false;
  1389. for(auto & stack : stacks)
  1390. {
  1391. if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1392. {
  1393. hasStack[stack->side] = true;
  1394. }
  1395. }
  1396. if(!hasStack[0] && !hasStack[1])
  1397. return 2;
  1398. if(!hasStack[1])
  1399. return 0;
  1400. if(!hasStack[0])
  1401. return 1;
  1402. return boost::none;
  1403. }