CBattleInfoCallback.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. /*
  2. * CBattleCallback.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->warnStream() << "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 /*= BattleHex::INVALID*/) 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->errorStream() << "Incorrect mode of battleGetRandomSpell (" << 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 /*= 0*/, int lastMoved /*= -1*/) 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->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  447. && battleMatchOwner(stack, dst)
  448. && dst->alive()
  449. && (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING))
  450. && stack->shots
  451. )
  452. return true;
  453. return false;
  454. }
  455. TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting,
  456. ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
  457. {
  458. return calculateDmgRange(attacker, defender, attacker->count, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  459. }
  460. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  461. {
  462. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  463. {
  464. auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
  465. auto limitMatches = info.shooting
  466. ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
  467. : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
  468. //any regular bonuses or just ones for melee/ranged
  469. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  470. };
  471. double additiveBonus = 1.0, multBonus = 1.0,
  472. minDmg = info.attackerBonuses->getMinDamage() * info.attackerCount,//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
  473. maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerCount;
  474. const CCreature *attackerType = info.attacker->getCreature(),
  475. *defenderType = info.defender->getCreature();
  476. if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
  477. {
  478. SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  479. }
  480. 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)
  481. { //minDmg and maxDmg are multiplied by hero attack + 1
  482. auto retreiveHeroPrimSkill = [&](int skill) -> int
  483. {
  484. const std::shared_ptr<Bonus> b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  485. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  486. };
  487. minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  488. maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  489. }
  490. int attackDefenceDifference = 0;
  491. double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
  492. attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
  493. double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
  494. attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
  495. if(const std::shared_ptr<Bonus> slayerEffect = info.attackerBonuses->getBonus(Selector::type(Bonus::SLAYER))) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  496. {
  497. std::vector<int> affectedIds;
  498. int spLevel = slayerEffect->val;
  499. //FIXME: do not check all creatures
  500. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  501. {
  502. for(const std::shared_ptr<Bonus> b : VLC->creh->creatures[g]->getBonusList())
  503. {
  504. if ((b->type == Bonus::KING3 && spLevel >= 3) || //expert
  505. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  506. (b->type == Bonus::KING1 && spLevel >= 0)) //none or basic +
  507. {
  508. affectedIds.push_back(g);
  509. break;
  510. }
  511. }
  512. }
  513. for(auto & affectedId : affectedIds)
  514. {
  515. if(defenderType->idNumber == affectedId)
  516. {
  517. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
  518. break;
  519. }
  520. }
  521. }
  522. //bonus from attack/defense skills
  523. if(attackDefenceDifference < 0) //decreasing dmg
  524. {
  525. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  526. multBonus *= 1.0 - dec;
  527. }
  528. else //increasing dmg
  529. {
  530. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  531. additiveBonus += inc;
  532. }
  533. //applying jousting bonus
  534. if(info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY))
  535. additiveBonus += info.chargedFields * 0.05;
  536. //handling secondary abilities and artifacts giving premies to them
  537. if(info.shooting)
  538. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
  539. else
  540. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
  541. if(info.defenderBonuses)
  542. multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
  543. //handling hate effect
  544. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
  545. //luck bonus
  546. if (info.luckyHit)
  547. {
  548. additiveBonus += 1.0;
  549. }
  550. //unlucky hit, used only if negative luck is enabled
  551. if (info.unluckyHit)
  552. {
  553. additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
  554. }
  555. //ballista double dmg
  556. if(info.ballistaDoubleDamage)
  557. {
  558. additiveBonus += 1.0;
  559. }
  560. if (info.deathBlow) //Dread Knight and many WoGified creatures
  561. {
  562. additiveBonus += 1.0;
  563. }
  564. //handling spell effects
  565. if(!info.shooting) //eg. shield
  566. {
  567. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
  568. }
  569. else if(info.shooting) //eg. air shield
  570. {
  571. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
  572. }
  573. if(info.shooting)
  574. {
  575. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  576. //get list first, total value of 0 also counts
  577. TBonusListPtr forgetfulList = info.attackerBonuses->getBonuses(Selector::type(Bonus::FORGETFULL),"");
  578. if(!forgetfulList->empty())
  579. {
  580. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  581. //none of basic level
  582. if(forgetful == 0 || forgetful == 1)
  583. multBonus *= 0.5;
  584. else
  585. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  586. }
  587. }
  588. TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
  589. TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
  590. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  591. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo<std::shared_ptr<Bonus>>))->additionalInfo : 0;
  592. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  593. {
  594. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  595. }
  596. auto isAdvancedAirShield = [](const Bonus* bonus)
  597. {
  598. return bonus->source == Bonus::SPELL_EFFECT
  599. && bonus->sid == SpellID::AIR_SHIELD
  600. && bonus->val >= SecSkillLevel::ADVANCED;
  601. };
  602. //wall / distance penalty + advanced air shield
  603. const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  604. const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  605. if(info.shooting)
  606. {
  607. if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
  608. {
  609. multBonus *= 0.5;
  610. }
  611. if (obstaclePenalty)
  612. {
  613. multBonus *= 0.5; //cumulative
  614. }
  615. }
  616. if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  617. {
  618. multBonus *= 0.5;
  619. }
  620. // psychic elementals versus mind immune units 50%
  621. if(attackerType->idNumber == CreatureID::PSYCHIC_ELEMENTAL
  622. && info.defenderBonuses->hasBonusOfType(Bonus::MIND_IMMUNITY))
  623. {
  624. multBonus *= 0.5;
  625. }
  626. // TODO attack on petrified unit 50%
  627. // blinded unit retaliates
  628. minDmg *= additiveBonus * multBonus;
  629. maxDmg *= additiveBonus * multBonus;
  630. TDmgRange returnedVal;
  631. if(curseEffects->size()) //curse handling (rest)
  632. {
  633. minDmg += curseBlessAdditiveModifier;
  634. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  635. }
  636. else if(blessEffects->size()) //bless handling
  637. {
  638. maxDmg += curseBlessAdditiveModifier;
  639. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  640. }
  641. else
  642. {
  643. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  644. }
  645. //damage cannot be less than 1
  646. vstd::amax(returnedVal.first, 1);
  647. vstd::amax(returnedVal.second, 1);
  648. return returnedVal;
  649. }
  650. TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, TQuantity attackerCount,
  651. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
  652. {
  653. BattleAttackInfo bai(attacker, defender, shooting);
  654. bai.attackerCount = attackerCount;
  655. bai.chargedFields = charge;
  656. bai.luckyHit = lucky;
  657. bai.unluckyHit = unlucky;
  658. bai.deathBlow = deathBlow;
  659. bai.ballistaDoubleDamage = ballistaDoubleDmg;
  660. return calculateDmgRange(bai);
  661. }
  662. TDmgRange CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  663. {
  664. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  665. const bool shooting = battleCanShoot(attacker, defender->position);
  666. const BattleAttackInfo bai(attacker, defender, shooting);
  667. return battleEstimateDamage(rand, bai, retaliationDmg);
  668. }
  669. std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const BattleAttackInfo & bai, std::pair<ui32, ui32> * retaliationDmg /*= nullptr*/) const
  670. {
  671. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  672. //const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
  673. TDmgRange ret = calculateDmgRange(bai);
  674. if(retaliationDmg)
  675. {
  676. if(bai.shooting)
  677. {
  678. retaliationDmg->first = retaliationDmg->second = 0;
  679. }
  680. else
  681. {
  682. ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  683. for (int i=0; i<2; ++i)
  684. {
  685. BattleStackAttacked bsa;
  686. bsa.damageAmount = ret.*pairElems[i];
  687. bai.defender->prepareAttacked(bsa, rand, bai.defenderCount);
  688. auto retaliationAttack = bai.reverse();
  689. retaliationAttack.attackerCount = bsa.newAmount;
  690. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  691. }
  692. }
  693. }
  694. return ret;
  695. }
  696. std::shared_ptr<const CObstacleInstance> CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const
  697. {
  698. RETURN_IF_NOT_BATTLE(std::shared_ptr<const CObstacleInstance>());
  699. for(auto &obs : battleGetAllObstacles())
  700. {
  701. if(vstd::contains(obs->getBlockedTiles(), tile)
  702. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  703. {
  704. return obs;
  705. }
  706. }
  707. return std::shared_ptr<const CObstacleInstance>();
  708. }
  709. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  710. {
  711. AccessibilityInfo ret;
  712. ret.fill(EAccessibility::ACCESSIBLE);
  713. //removing accessibility for side columns of hexes
  714. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  715. {
  716. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  717. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  718. }
  719. //gate -> should be before stacks
  720. if(battleGetSiegeLevel() > 0)
  721. {
  722. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  723. switch(battleGetGateState())
  724. {
  725. case EGateState::CLOSED:
  726. accessability = EAccessibility::GATE;
  727. break;
  728. case EGateState::BLOCKED:
  729. accessability = EAccessibility::UNAVAILABLE;
  730. break;
  731. }
  732. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  733. }
  734. //tiles occupied by standing stacks
  735. for(auto stack : battleAliveStacks())
  736. {
  737. for(auto hex : stack->getHexes())
  738. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  739. ret[hex] = EAccessibility::ALIVE_STACK;
  740. }
  741. //obstacles
  742. for(const auto &obst : battleGetAllObstacles())
  743. {
  744. for(auto hex : obst->getBlockedTiles())
  745. ret[hex] = EAccessibility::OBSTACLE;
  746. }
  747. //walls
  748. if(battleGetSiegeLevel() > 0)
  749. {
  750. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  751. for(auto hex : permanentlyLocked)
  752. ret[hex] = EAccessibility::UNAVAILABLE;
  753. //TODO likely duplicated logic
  754. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] =
  755. {
  756. //which part of wall, which hex is blocked if this part of wall is not destroyed
  757. std::make_pair(2, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  758. std::make_pair(3, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  759. std::make_pair(4, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  760. std::make_pair(5, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  761. };
  762. for(auto & elem : lockedIfNotDestroyed)
  763. {
  764. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  765. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  766. }
  767. }
  768. return ret;
  769. }
  770. AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack * stack) const
  771. {
  772. return getAccesibility(stack->getHexes());
  773. }
  774. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  775. {
  776. auto ret = getAccesibility();
  777. for(auto hex : accessibleHexes)
  778. if(hex.isValid())
  779. ret[hex] = EAccessibility::ACCESSIBLE;
  780. return ret;
  781. }
  782. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  783. {
  784. ReachabilityInfo ret;
  785. ret.accessibility = accessibility;
  786. ret.params = params;
  787. ret.predecessors.fill(BattleHex::INVALID);
  788. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  789. if(!params.startPosition.isValid()) //if got call for arrow turrets
  790. return ret;
  791. const std::set<BattleHex> quicksands = getStoppers(params.perspective);
  792. //const bool twoHexCreature = params.doubleWide;
  793. std::queue<BattleHex> hexq; //bfs queue
  794. //first element
  795. hexq.push(params.startPosition);
  796. ret.distances[params.startPosition] = 0;
  797. while(!hexq.empty()) //bfs loop
  798. {
  799. const BattleHex curHex = hexq.front();
  800. hexq.pop();
  801. //walking stack can't step past the quicksands
  802. //TODO what if second hex of two-hex creature enters quicksand
  803. if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
  804. continue;
  805. const int costToNeighbour = ret.distances[curHex] + 1;
  806. for(BattleHex neighbour : curHex.neighbouringTiles())
  807. {
  808. const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.side);
  809. const int costFoundSoFar = ret.distances[neighbour];
  810. if(accessible && costToNeighbour < costFoundSoFar)
  811. {
  812. hexq.push(neighbour);
  813. ret.distances[neighbour] = costToNeighbour;
  814. ret.predecessors[neighbour] = curHex;
  815. }
  816. }
  817. }
  818. return ret;
  819. }
  820. ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack * stack) const
  821. {
  822. return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
  823. }
  824. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  825. {
  826. std::set<BattleHex> ret;
  827. RETURN_IF_NOT_BATTLE(ret);
  828. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  829. {
  830. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  831. {
  832. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  833. }
  834. }
  835. return ret;
  836. }
  837. std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, BattleSideOpt side) const
  838. {
  839. auto reachability = getReachability(closest);
  840. auto avHexes = battleGetAvailableHexes(closest, false);
  841. // I hate std::pairs with their undescriptive member names first / second
  842. struct DistStack
  843. {
  844. int distanceToPred;
  845. BattleHex destination;
  846. const CStack * stack;
  847. };
  848. std::vector<DistStack> stackPairs;
  849. std::vector<const CStack *> possibleStacks = battleGetStacksIf([=](const CStack * s)
  850. {
  851. return s->isValidTarget(false) && s != closest && (!side || side.get() == s->side);
  852. });
  853. for(const CStack * st : possibleStacks)
  854. for(BattleHex hex : avHexes)
  855. if(CStack::isMeleeAttackPossible(closest, st, hex))
  856. {
  857. DistStack hlp = {reachability.distances[hex], hex, st};
  858. stackPairs.push_back(hlp);
  859. }
  860. if (stackPairs.size())
  861. {
  862. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  863. auto minimal = boost::min_element(stackPairs, comparator);
  864. return std::make_pair(minimal->stack, minimal->destination);
  865. }
  866. else
  867. return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
  868. }
  869. si8 CBattleInfoCallback::battleGetTacticDist() const
  870. {
  871. RETURN_IF_NOT_BATTLE(0);
  872. //TODO get rid of this method
  873. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  874. return battleTacticDist();
  875. return 0;
  876. }
  877. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  878. {
  879. RETURN_IF_NOT_BATTLE(false);
  880. auto side = battleGetTacticsSide();
  881. auto dist = battleGetTacticDist();
  882. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  883. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  884. }
  885. ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
  886. {
  887. ReachabilityInfo::Parameters params(stack);
  888. if(!battleDoWeKnowAbout(stack->side))
  889. {
  890. //Stack is held by enemy, we can't use his perspective to check for reachability.
  891. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  892. params.perspective = battleGetMySide();
  893. }
  894. return getReachability(params);
  895. }
  896. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  897. {
  898. if(params.flying)
  899. return getFlyingReachability(params);
  900. else
  901. return makeBFS(getAccesibility(params.knownAccessible), params);
  902. }
  903. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  904. {
  905. ReachabilityInfo ret;
  906. ret.accessibility = getAccesibility(params.knownAccessible);
  907. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  908. {
  909. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  910. {
  911. ret.predecessors[i] = params.startPosition;
  912. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  913. }
  914. }
  915. return ret;
  916. }
  917. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  918. {
  919. //does not return hex attacked directly
  920. //TODO: apply rotation to two-hex attackers
  921. bool isAttacker = attacker->side == BattleSide::ATTACKER;
  922. AttackableTiles at;
  923. RETURN_IF_NOT_BATTLE(at);
  924. const int WN = GameConstants::BFIELD_WIDTH;
  925. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  926. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  927. bool reverse = isToReverse (hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  928. if (reverse && attacker->doubleWide())
  929. {
  930. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  931. }
  932. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  933. {
  934. boost::copy (attacker->getSurroundingHexes (attackerPos), vstd::set_inserter (at.hostileCreaturePositions));
  935. }
  936. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  937. {
  938. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  939. for (BattleHex tile : hexes)
  940. {
  941. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition (tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  942. {
  943. const CStack * st = battleGetStackByPos(tile, true);
  944. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  945. {
  946. at.hostileCreaturePositions.insert(tile);
  947. }
  948. }
  949. }
  950. }
  951. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  952. {
  953. std::vector<BattleHex> hexes; //only one, in fact
  954. int pseudoVector = destinationTile.hex - hex;
  955. switch (pseudoVector)
  956. {
  957. case 1:
  958. case -1:
  959. BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
  960. break;
  961. case WN: //17 //left-down or right-down
  962. case -WN: //-17 //left-up or right-up
  963. case WN + 1: //18 //right-down
  964. case -WN + 1: //-16 //right-up
  965. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : -1), hexes);
  966. break;
  967. case WN-1: //16 //left-down
  968. case -WN-1: //-18 //left-up
  969. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : 0), hexes);
  970. break;
  971. }
  972. for (BattleHex tile : hexes)
  973. {
  974. //friendly stacks can also be damaged by Dragon Breath
  975. if (battleGetStackByPos (tile, true))
  976. at.friendlyCreaturePositions.insert (tile);
  977. }
  978. }
  979. return at;
  980. }
  981. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  982. {
  983. std::set<const CStack*> attackedCres;
  984. RETURN_IF_NOT_BATTLE(attackedCres);
  985. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  986. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  987. {
  988. const CStack * st = battleGetStackByPos(tile, true);
  989. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  990. {
  991. attackedCres.insert(st);
  992. }
  993. }
  994. for (BattleHex tile : at.friendlyCreaturePositions)
  995. {
  996. const CStack * st = battleGetStackByPos(tile, true);
  997. if(st) //friendly stacks can also be damaged by Dragon Breath
  998. {
  999. attackedCres.insert(st);
  1000. }
  1001. }
  1002. return attackedCres;
  1003. }
  1004. //TODO: this should apply also to mechanics and cursor interface
  1005. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1006. {
  1007. int fromX = hexFrom.getX();
  1008. int fromY = hexFrom.getY();
  1009. int toX = hexTo.getX();
  1010. int toY = hexTo.getY();
  1011. if (curDir) // attacker, facing right
  1012. {
  1013. if (fromX < toX)
  1014. return false;
  1015. if (fromX > toX)
  1016. return true;
  1017. if (fromY % 2 == 0 && toY % 2 == 1)
  1018. return true;
  1019. return false;
  1020. }
  1021. else // defender, facing left
  1022. {
  1023. if(fromX < toX)
  1024. return true;
  1025. if(fromX > toX)
  1026. return false;
  1027. if (fromY % 2 == 1 && toY % 2 == 0)
  1028. return true;
  1029. return false;
  1030. }
  1031. }
  1032. //TODO: this should apply also to mechanics and cursor interface
  1033. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1034. {
  1035. if (hexTo < 0 || hexFrom < 0) //turret
  1036. return false;
  1037. if (toDoubleWide)
  1038. {
  1039. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1040. {
  1041. if (toDir)
  1042. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1043. else
  1044. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1045. }
  1046. return false;
  1047. }
  1048. else
  1049. {
  1050. return isToReverseHlp(hexFrom, hexTo, curDir);
  1051. }
  1052. }
  1053. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex /*= BattleHex::INVALID*/, BattleHex * predecessors /*= nullptr*/) const
  1054. {
  1055. ReachabilityInfo::TDistances ret;
  1056. ret.fill(-1);
  1057. RETURN_IF_NOT_BATTLE(ret);
  1058. ReachabilityInfo::Parameters params(stack);
  1059. params.perspective = battleGetMySide();
  1060. params.startPosition = hex.isValid() ? hex : stack->position;
  1061. auto reachability = getReachability(params);
  1062. boost::copy(reachability.distances, ret.begin());
  1063. if(predecessors)
  1064. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1065. predecessors[i] = reachability.predecessors[i];
  1066. return ret;
  1067. }
  1068. si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
  1069. {
  1070. return battleHasDistancePenalty(stack, stack->position, destHex);
  1071. }
  1072. si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  1073. {
  1074. RETURN_IF_NOT_BATTLE(false);
  1075. if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
  1076. return false;
  1077. if(const CStack * dstStack = battleGetStackByPos(destHex, false))
  1078. {
  1079. //If any hex of target creature is within range, there is no penalty
  1080. for(auto hex : dstStack->getHexes())
  1081. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1082. return false;
  1083. //TODO what about two-hex shooters?
  1084. }
  1085. else
  1086. {
  1087. if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1088. return false;
  1089. }
  1090. return true;
  1091. }
  1092. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1093. {
  1094. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1095. return WallPartToHex(part);
  1096. }
  1097. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1098. {
  1099. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1100. return hexToWallPart(hex);
  1101. }
  1102. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1103. {
  1104. RETURN_IF_NOT_BATTLE(false);
  1105. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1106. wallPart != EWallPart::INVALID;
  1107. }
  1108. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1109. {
  1110. std::vector<BattleHex> attackableBattleHexes;
  1111. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1112. for(auto & wallPartPair : wallParts)
  1113. {
  1114. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1115. {
  1116. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1117. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1118. {
  1119. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1120. }
  1121. }
  1122. }
  1123. return attackableBattleHexes;
  1124. }
  1125. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1126. {
  1127. RETURN_IF_NOT_BATTLE(-1);
  1128. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1129. ui32 ret = caster->getSpellCost(sp);
  1130. //checking for friendly stacks reducing cost of the spell and
  1131. //enemy stacks increasing it
  1132. si32 manaReduction = 0;
  1133. si32 manaIncrease = 0;
  1134. for(auto stack : battleAliveStacks())
  1135. {
  1136. if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1137. {
  1138. vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1139. }
  1140. if(stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1141. {
  1142. vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1143. }
  1144. }
  1145. return ret - manaReduction + manaIncrease;
  1146. }
  1147. const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
  1148. {
  1149. RETURN_IF_NOT_BATTLE(nullptr);
  1150. auto stacks = battleGetAllStacks();
  1151. auto stackItr = range::find_if(stacks, pred);
  1152. return stackItr == stacks.end() ? nullptr : *stackItr;
  1153. }
  1154. si8 CBattleInfoCallback::battleHasShootingPenalty(const CStack * stack, BattleHex destHex)
  1155. {
  1156. return battleHasDistancePenalty(stack, destHex) || battleHasWallPenalty(stack, destHex);
  1157. }
  1158. bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
  1159. {
  1160. RETURN_IF_NOT_BATTLE(false);
  1161. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1162. return false;
  1163. for(const CStack * s : batteAdjacentCreatures(stack))
  1164. {
  1165. if (s->owner != stack->owner) //blocked by enemy stack
  1166. return true;
  1167. }
  1168. return false;
  1169. }
  1170. std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
  1171. {
  1172. std::set<const CStack*> stacks;
  1173. RETURN_IF_NOT_BATTLE(stacks);
  1174. for (BattleHex hex : stack->getSurroundingHexes())
  1175. if(const CStack * neighbour = battleGetStackByPos(hex, true))
  1176. stacks.insert(neighbour);
  1177. return stacks;
  1178. }
  1179. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1180. {
  1181. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1182. //This is complete list. No spells from mods.
  1183. //todo: this should be Spellbook of caster Stack
  1184. static const std::set<SpellID> allPossibleSpells =
  1185. {
  1186. SpellID::AIR_SHIELD,
  1187. SpellID::ANTI_MAGIC,
  1188. SpellID::BLESS,
  1189. SpellID::BLOODLUST,
  1190. SpellID::COUNTERSTRIKE,
  1191. SpellID::CURE,
  1192. SpellID::FIRE_SHIELD,
  1193. SpellID::FORTUNE,
  1194. SpellID::HASTE,
  1195. SpellID::MAGIC_MIRROR,
  1196. SpellID::MIRTH,
  1197. SpellID::PRAYER,
  1198. SpellID::PRECISION,
  1199. SpellID::PROTECTION_FROM_AIR,
  1200. SpellID::PROTECTION_FROM_EARTH,
  1201. SpellID::PROTECTION_FROM_FIRE,
  1202. SpellID::PROTECTION_FROM_WATER,
  1203. SpellID::SHIELD,
  1204. SpellID::SLAYER,
  1205. SpellID::STONE_SKIN
  1206. };
  1207. std::vector<SpellID> beneficialSpells;
  1208. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred)
  1209. {
  1210. return getStackIf([=](const CStack * stack)
  1211. {
  1212. return pred(stack) && stack->owner != subject->owner && stack->alive();
  1213. });
  1214. };
  1215. for(const SpellID spellID : allPossibleSpells)
  1216. {
  1217. std::stringstream cachingStr;
  1218. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1219. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1220. //TODO: this ability has special limitations
  1221. || spellID.toSpell()->canBeCastAt(this, subject, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1222. continue;
  1223. switch (spellID)
  1224. {
  1225. case SpellID::SHIELD:
  1226. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1227. {
  1228. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1229. {
  1230. return !stack->shots;
  1231. });
  1232. if (!walker)
  1233. continue;
  1234. }
  1235. break;
  1236. case SpellID::AIR_SHIELD: //only against active shooters
  1237. {
  1238. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1239. {
  1240. return stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots;
  1241. });
  1242. if (!shooter)
  1243. continue;
  1244. }
  1245. break;
  1246. case SpellID::ANTI_MAGIC:
  1247. case SpellID::MAGIC_MIRROR:
  1248. case SpellID::PROTECTION_FROM_AIR:
  1249. case SpellID::PROTECTION_FROM_EARTH:
  1250. case SpellID::PROTECTION_FROM_FIRE:
  1251. case SpellID::PROTECTION_FROM_WATER:
  1252. {
  1253. const ui8 enemySide = 1 - subject->side;
  1254. //todo: only if enemy has spellbook
  1255. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1256. continue;
  1257. }
  1258. break;
  1259. case SpellID::CURE: //only damaged units
  1260. {
  1261. //do not cast on affected by debuffs
  1262. if (subject->firstHPleft >= subject->MaxHealth())
  1263. continue;
  1264. }
  1265. break;
  1266. case SpellID::BLOODLUST:
  1267. {
  1268. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1269. continue;
  1270. }
  1271. break;
  1272. case SpellID::PRECISION:
  1273. {
  1274. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1275. continue;
  1276. }
  1277. break;
  1278. case SpellID::SLAYER://only if monsters are present
  1279. {
  1280. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1281. {
  1282. const auto isKing = Selector::type(Bonus::KING1)
  1283. .Or(Selector::type(Bonus::KING2))
  1284. .Or(Selector::type(Bonus::KING3));
  1285. return stack->hasBonus(isKing);
  1286. });
  1287. if (!kingMonster)
  1288. continue;
  1289. }
  1290. break;
  1291. }
  1292. beneficialSpells.push_back(spellID);
  1293. }
  1294. if(!beneficialSpells.empty())
  1295. {
  1296. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1297. }
  1298. else
  1299. {
  1300. return SpellID::NONE;
  1301. }
  1302. }
  1303. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1304. {
  1305. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1306. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1307. if (!bl->size())
  1308. return SpellID::NONE;
  1309. int totalWeight = 0;
  1310. for(auto b : *bl)
  1311. {
  1312. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1313. }
  1314. int randomPos = rand.nextInt(totalWeight - 1);
  1315. for(auto b : *bl)
  1316. {
  1317. randomPos -= std::max(b->additionalInfo, 1);
  1318. if(randomPos < 0)
  1319. {
  1320. return SpellID(b->subtype);
  1321. }
  1322. }
  1323. return SpellID::NONE;
  1324. }
  1325. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1326. {
  1327. RETURN_IF_NOT_BATTLE(-3);
  1328. if(!battleCanSurrender(Player))
  1329. return -1;
  1330. const auto side = playerToSide(Player);
  1331. if(!side)
  1332. return -1;
  1333. int ret = 0;
  1334. double discount = 0;
  1335. for(const CStack * s : battleAliveStacks(side.get()))
  1336. if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
  1337. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  1338. if(const CGHeroInstance * h = battleGetFightingHero(side.get()))
  1339. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1340. ret *= (100.0 - discount) / 100.0;
  1341. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1342. return ret;
  1343. }
  1344. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1345. {
  1346. const IBonusBearer *node = nullptr;
  1347. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1348. node = h;
  1349. else
  1350. node = getBattleNode();
  1351. if(!node)
  1352. return GameConstants::SPELL_LEVELS;
  1353. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1354. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1355. if(b->size())
  1356. return b->totalValue();
  1357. return GameConstants::SPELL_LEVELS;
  1358. }
  1359. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1360. {
  1361. auto stacks = battleGetAllStacks();
  1362. //checking winning condition
  1363. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
  1364. hasStack[0] = hasStack[1] = false;
  1365. for(auto & stack : stacks)
  1366. {
  1367. if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1368. {
  1369. hasStack[stack->side] = true;
  1370. }
  1371. }
  1372. if(!hasStack[0] && !hasStack[1])
  1373. return 2;
  1374. if(!hasStack[1])
  1375. return 0;
  1376. if(!hasStack[0])
  1377. return 1;
  1378. return boost::none;
  1379. }