CBattleInfoCallback.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  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 <vcmi/scripting/Service.h>
  13. #include "../CStack.h"
  14. #include "BattleInfo.h"
  15. #include "../NetPacks.h"
  16. #include "../spells/CSpellHandler.h"
  17. #include "../mapObjects/CGTownInstance.h"
  18. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  19. {
  20. /*
  21. *Here are 2 explanations how below algorithm should work in H3, looks like they are not 100% accurate as it results in one damage number, not min/max range:
  22. *
  23. *1. http://heroes.thelazy.net/wiki/Arrow_tower
  24. *
  25. *2. All towns' turrets do the same damage. If Fort, Citadel or Castle is built damage of the Middle turret is 15, and 7,5 for others.
  26. *Buildings increase turrets' damage, but only those buildings that are new in town view, not upgrades to the existing. So, every building save:
  27. *- dwellings' upgrades
  28. *- Mage Guild upgrades
  29. *- Horde buildings
  30. *- income upgrades
  31. *- some special ones
  32. *increases middle Turret damage by 3, and 1,5 for the other two.
  33. *Damage is almost always the maximum one (right click on the Turret), sometimes +1/2 points, and it does not depend on the target. Nothing can influence it, except the mentioned above (but it will be roughly double if the defender has Armorer or Air Shield).
  34. *Maximum damage for Castle, Conflux is 120, Necropolis, Inferno, Fortress 125, Stronghold, Turret, and Dungeon 130 (for all three Turrets).
  35. *Artillery allows the player to control the Turrets.
  36. */
  37. static void retrieveTurretDamageRange(const CGTownInstance * town, const battle::Unit * turret, double & outMinDmg, double & outMaxDmg)//does not match OH3 yet, but damage is somewhat close
  38. {
  39. assert(turret->creatureIndex() == CreatureID::ARROW_TOWERS);
  40. assert(town);
  41. assert(turret->getPosition() >= -4 && turret->getPosition() <= -2);
  42. const float multiplier = (turret->getPosition() == -2) ? 1.0f : 0.5f;
  43. //Revised - Where do below values come from?
  44. /*int baseMin = 6;
  45. int baseMax = 10;*/
  46. const int baseDamage = 15;
  47. outMinDmg = multiplier * (baseDamage + town->getTownLevel() * 3);
  48. outMaxDmg = multiplier * (baseDamage + town->getTownLevel() * 3);
  49. }
  50. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  51. {
  52. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  53. return lineToHex[line];
  54. }
  55. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  56. {
  57. const int wallInStackLine = lineToWallHex(pos1.getY());
  58. const int wallInDestLine = lineToWallHex(pos2.getY());
  59. const bool stackLeft = pos1 < wallInStackLine;
  60. const bool destLeft = pos2 < wallInDestLine;
  61. return stackLeft == destLeft;
  62. }
  63. // parts of wall
  64. static const std::pair<int, EWallPart::EWallPart> wallParts[] =
  65. {
  66. std::make_pair(50, EWallPart::KEEP),
  67. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  68. std::make_pair(182, EWallPart::BOTTOM_WALL),
  69. std::make_pair(130, EWallPart::BELOW_GATE),
  70. std::make_pair(78, EWallPart::OVER_GATE),
  71. std::make_pair(29, EWallPart::UPPER_WALL),
  72. std::make_pair(12, EWallPart::UPPER_TOWER),
  73. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  74. std::make_pair(96, EWallPart::GATE),
  75. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  76. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  77. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  78. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  79. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  80. };
  81. static EWallPart::EWallPart hexToWallPart(BattleHex hex)
  82. {
  83. for(auto & elem : wallParts)
  84. {
  85. if(elem.first == hex)
  86. return elem.second;
  87. }
  88. return EWallPart::INVALID; //not found!
  89. }
  90. static BattleHex WallPartToHex(EWallPart::EWallPart part)
  91. {
  92. for(auto & elem : wallParts)
  93. {
  94. if(elem.second == part)
  95. return elem.first;
  96. }
  97. return BattleHex::INVALID; //not found!
  98. }
  99. }
  100. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  101. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const spells::Caster * caster, spells::Mode mode) const
  102. {
  103. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  104. if(caster == nullptr)
  105. {
  106. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  107. return ESpellCastProblem::INVALID;
  108. }
  109. const PlayerColor player = caster->getCasterOwner();
  110. const auto side = playerToSide(player);
  111. if(!side)
  112. return ESpellCastProblem::INVALID;
  113. if(!battleDoWeKnowAbout(side.get()))
  114. {
  115. logGlobal->warn("You can't check if enemy can cast given spell!");
  116. return ESpellCastProblem::INVALID;
  117. }
  118. if(battleTacticDist())
  119. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  120. switch(mode)
  121. {
  122. case spells::Mode::HERO:
  123. {
  124. if(battleCastSpells(side.get()) > 0)
  125. return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
  126. auto hero = dynamic_cast<const CGHeroInstance *>(caster);
  127. if(!hero)
  128. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  129. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  130. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  131. }
  132. break;
  133. default:
  134. break;
  135. }
  136. return ESpellCastProblem::OK;
  137. }
  138. bool CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  139. {
  140. RETURN_IF_NOT_BATTLE(false);
  141. if(!battleGetSiegeLevel())
  142. return false;
  143. const std::string cachingStrNoWallPenalty = "type_NO_WALL_PENALTY";
  144. static const auto selectorNoWallPenalty = Selector::type()(Bonus::NO_WALL_PENALTY);
  145. if(shooter->hasBonus(selectorNoWallPenalty, cachingStrNoWallPenalty))
  146. return false;
  147. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  148. const int wallInDestLine = lineToWallHex(destHex.getY());
  149. const bool stackLeft = shooterPosition < wallInStackLine;
  150. const bool destRight = destHex > wallInDestLine;
  151. if (stackLeft && destRight) //shooting from outside to inside
  152. {
  153. int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  154. if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  155. row -= 2;
  156. const int wallPos = lineToWallHex(row);
  157. if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
  158. }
  159. return false;
  160. }
  161. si8 CBattleInfoCallback::battleCanTeleportTo(const battle::Unit * stack, BattleHex destHex, int telportLevel) const
  162. {
  163. RETURN_IF_NOT_BATTLE(false);
  164. if (!getAccesibility(stack).accessible(destHex, stack))
  165. return false;
  166. const ui8 siegeLevel = battleGetSiegeLevel();
  167. //check for wall
  168. //advanced teleport can pass wall of fort|citadel, expert - of castle
  169. if ((siegeLevel > CGTownInstance::NONE && telportLevel < 2) || (siegeLevel >= CGTownInstance::CASTLE && telportLevel < 3))
  170. return sameSideOfWall(stack->getPosition(), destHex);
  171. return true;
  172. }
  173. std::vector<PossiblePlayerBattleAction> CBattleInfoCallback::getClientActionsForStack(const CStack * stack, const BattleClientInterfaceData & data)
  174. {
  175. RETURN_IF_NOT_BATTLE(std::vector<PossiblePlayerBattleAction>());
  176. std::vector<PossiblePlayerBattleAction> allowedActionList;
  177. if(data.tacticsMode) //would "if(battleGetTacticDist() > 0)" work?
  178. {
  179. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_TACTICS);
  180. allowedActionList.push_back(PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK);
  181. }
  182. else
  183. {
  184. if(stack->canCast()) //TODO: check for battlefield effects that prevent casting?
  185. {
  186. if(stack->hasBonusOfType(Bonus::SPELLCASTER) && data.creatureSpellToCast != -1)
  187. {
  188. const CSpell *spell = SpellID(data.creatureSpellToCast).toSpell();
  189. PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE);
  190. allowedActionList.push_back(act);
  191. }
  192. if(stack->hasBonusOfType(Bonus::RANDOM_SPELLCASTER))
  193. allowedActionList.push_back(PossiblePlayerBattleAction::RANDOM_GENIE_SPELL);
  194. if(stack->hasBonusOfType(Bonus::DAEMON_SUMMONING))
  195. allowedActionList.push_back(PossiblePlayerBattleAction::RISE_DEMONS);
  196. }
  197. if(stack->canShoot())
  198. allowedActionList.push_back(PossiblePlayerBattleAction::SHOOT);
  199. if(stack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE))
  200. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK_AND_RETURN);
  201. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK); //all active stacks can attack
  202. allowedActionList.push_back(PossiblePlayerBattleAction::WALK_AND_ATTACK); //not all stacks can always walk, but we will check this elsewhere
  203. if(stack->canMove() && stack->Speed(0, true)) //probably no reason to try move war machines or bound stacks
  204. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_STACK);
  205. auto siegedTown = battleGetDefendedTown();
  206. if(siegedTown && siegedTown->hasFort() && stack->hasBonusOfType(Bonus::CATAPULT)) //TODO: check shots
  207. allowedActionList.push_back(PossiblePlayerBattleAction::CATAPULT);
  208. if(stack->hasBonusOfType(Bonus::HEALER))
  209. allowedActionList.push_back(PossiblePlayerBattleAction::HEAL);
  210. }
  211. return allowedActionList;
  212. }
  213. PossiblePlayerBattleAction CBattleInfoCallback::getCasterAction(const CSpell * spell, const spells::Caster * caster, spells::Mode mode) const
  214. {
  215. RETURN_IF_NOT_BATTLE(PossiblePlayerBattleAction::INVALID);
  216. PossiblePlayerBattleAction spellSelMode = PossiblePlayerBattleAction::ANY_LOCATION;
  217. const CSpell::TargetInfo ti(spell, caster->getSpellSchoolLevel(spell), mode);
  218. if(ti.massive || ti.type == spells::AimType::NO_TARGET)
  219. spellSelMode = PossiblePlayerBattleAction::NO_LOCATION;
  220. else if(ti.type == spells::AimType::LOCATION && ti.clearAffected)
  221. spellSelMode = PossiblePlayerBattleAction::FREE_LOCATION;
  222. else if(ti.type == spells::AimType::CREATURE)
  223. spellSelMode = PossiblePlayerBattleAction::AIMED_SPELL_CREATURE;
  224. else if(ti.type == spells::AimType::OBSTACLE)
  225. spellSelMode = PossiblePlayerBattleAction::OBSTACLE;
  226. return spellSelMode;
  227. }
  228. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  229. {
  230. std::set<BattleHex> attackedHexes;
  231. RETURN_IF_NOT_BATTLE(attackedHexes);
  232. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  233. for (BattleHex tile : at.hostileCreaturePositions)
  234. {
  235. const CStack * st = battleGetStackByPos(tile, true);
  236. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  237. {
  238. attackedHexes.insert(tile);
  239. }
  240. }
  241. for (BattleHex tile : at.friendlyCreaturePositions)
  242. {
  243. if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  244. {
  245. attackedHexes.insert(tile);
  246. }
  247. }
  248. return attackedHexes;
  249. }
  250. SpellID CBattleInfoCallback::battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const
  251. {
  252. switch (mode)
  253. {
  254. case RANDOM_GENIE:
  255. return getRandomBeneficialSpell(rand, stack); //target
  256. break;
  257. case RANDOM_AIMED:
  258. return getRandomCastedSpell(rand, stack); //caster
  259. break;
  260. default:
  261. logGlobal->error("Incorrect mode of battleGetRandomSpell (%d)", static_cast<int>(mode));
  262. return SpellID::NONE;
  263. }
  264. }
  265. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  266. {
  267. RETURN_IF_NOT_BATTLE(nullptr);
  268. for(auto s : battleGetAllStacks(true))
  269. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  270. return s;
  271. return nullptr;
  272. }
  273. const battle::Unit * CBattleInfoCallback::battleGetUnitByPos(BattleHex pos, bool onlyAlive) const
  274. {
  275. RETURN_IF_NOT_BATTLE(nullptr);
  276. auto ret = battleGetUnitsIf([=](const battle::Unit * unit)
  277. {
  278. return !unit->isGhost()
  279. && vstd::contains(battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()), pos)
  280. && (!onlyAlive || unit->alive());
  281. });
  282. if(!ret.empty())
  283. return ret.front();
  284. else
  285. return nullptr;
  286. }
  287. battle::Units CBattleInfoCallback::battleAliveUnits() const
  288. {
  289. return battleGetUnitsIf([](const battle::Unit * unit)
  290. {
  291. return unit->isValidTarget(false);
  292. });
  293. }
  294. battle::Units CBattleInfoCallback::battleAliveUnits(ui8 side) const
  295. {
  296. return battleGetUnitsIf([=](const battle::Unit * unit)
  297. {
  298. return unit->isValidTarget(false) && unit->unitSide() == side;
  299. });
  300. }
  301. //T is battle::Unit descendant
  302. template <typename T>
  303. const T * takeOneUnit(std::vector<const T*> & all, const int turn, int8_t & lastMoved, int phase)
  304. {
  305. const T * returnedUnit = nullptr;
  306. size_t currentUnitIndex = 0;
  307. for(size_t i = 0; i < all.size(); i++)
  308. {
  309. int32_t currentUnitSpeed = -1;
  310. int32_t returnedUnitSpeed = -1;
  311. if(returnedUnit)
  312. returnedUnitSpeed = returnedUnit->getInitiative(turn);
  313. if(all[i])
  314. {
  315. currentUnitSpeed = all[i]->getInitiative(turn);
  316. switch(phase)
  317. {
  318. case 1: // Faster first, attacker priority, higher slot first
  319. if(returnedUnit == nullptr || currentUnitSpeed > returnedUnitSpeed)
  320. {
  321. returnedUnit = all[i];
  322. currentUnitIndex = i;
  323. }
  324. else if(currentUnitSpeed == returnedUnitSpeed)
  325. {
  326. if(lastMoved == -1 && turn <= 0 && all[i]->unitSide() == BattleSide::ATTACKER
  327. && !(returnedUnit->unitSide() == all[i]->unitSide() && returnedUnit->unitSlot() < all[i]->unitSlot())) // Turn 0 attacker priority
  328. {
  329. returnedUnit = all[i];
  330. currentUnitIndex = i;
  331. }
  332. else if(lastMoved != -1 && all[i]->unitSide() != lastMoved
  333. && !(returnedUnit->unitSide() == all[i]->unitSide() && returnedUnit->unitSlot() < all[i]->unitSlot())) // Alternate equal speeds units
  334. {
  335. returnedUnit = all[i];
  336. currentUnitIndex = i;
  337. }
  338. }
  339. break;
  340. case 2: // Slower first, higher slot first
  341. case 3:
  342. if(returnedUnit == nullptr || currentUnitSpeed < returnedUnitSpeed)
  343. {
  344. returnedUnit = all[i];
  345. currentUnitIndex = i;
  346. }
  347. else if(currentUnitSpeed == returnedUnitSpeed && lastMoved != -1 && all[i]->unitSide() != lastMoved
  348. && !(returnedUnit->unitSide() == all[i]->unitSide() && returnedUnit->unitSlot() < all[i]->unitSlot())) // Alternate equal speeds units
  349. {
  350. returnedUnit = all[i];
  351. currentUnitIndex = i;
  352. }
  353. break;
  354. default:
  355. break;
  356. }
  357. }
  358. }
  359. if(!returnedUnit)
  360. return nullptr;
  361. all[currentUnitIndex] = nullptr;
  362. return returnedUnit;
  363. }
  364. void CBattleInfoCallback::battleGetTurnOrder(std::vector<battle::Units> & out, const size_t maxUnits, const int maxTurns, const int turn, int8_t lastMoved) const
  365. {
  366. RETURN_IF_NOT_BATTLE();
  367. if(maxUnits == 0 && maxTurns == 0)
  368. {
  369. logGlobal->error("Attempt to get infinite battle queue");
  370. return;
  371. }
  372. auto actualTurn = turn > 0 ? turn : 0;
  373. auto outputFull = [&]() -> bool
  374. {
  375. if(maxUnits == 0)
  376. return false;//no limit
  377. size_t outSize = 0;
  378. for(const auto & oneTurn : out)
  379. outSize += oneTurn.size();
  380. return outSize >= maxUnits;
  381. };
  382. out.emplace_back();
  383. //We'll split creatures with remaining movement to 4 buckets
  384. // [0] - turrets/catapult,
  385. // [1] - normal (unmoved) creatures, other war machines,
  386. // [2] - waited cres that had morale,
  387. // [3] - rest of waited cres
  388. std::array<battle::Units, 4> phase;
  389. const battle::Unit * active = battleActiveUnit();
  390. if(active)
  391. {
  392. //its first turn and active unit hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  393. if(turn == 0 && active->willMove() && !active->waited())
  394. {
  395. out.back().push_back(active);
  396. if(outputFull())
  397. return;
  398. }
  399. //its first or current turn, turn priority for active stack side
  400. //TODO: what if active stack mind-controlled?
  401. if(turn <= 0 && lastMoved < 0)
  402. lastMoved = active->unitSide();
  403. }
  404. auto all = battleGetUnitsIf([](const battle::Unit * unit)
  405. {
  406. return !unit->isGhost();
  407. });
  408. if(!vstd::contains_if(all, [](const battle::Unit * unit) { return unit->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  409. {
  410. //No unit will be able to move, battle is over.
  411. out.clear();
  412. return;
  413. }
  414. for(auto one : all)
  415. {
  416. if((actualTurn == 0 && !one->willMove()) //we are considering current round and unit won't move
  417. || (actualTurn > 0 && !one->canMove(turn)) //unit won't be able to move in later rounds
  418. || (actualTurn == 0 && one == active && !out.at(0).empty() && one == out.front().front())) //it's active unit already added at the beginning of queue
  419. {
  420. continue;
  421. }
  422. int p = one->battleQueuePhase(turn);
  423. phase[p].push_back(one);
  424. }
  425. boost::sort(phase[0], CMP_stack(0, actualTurn, lastMoved));
  426. std::copy(phase[0].begin(), phase[0].end(), std::back_inserter(out.back()));
  427. if(outputFull())
  428. return;
  429. for(int i = 1; i < 4; i++)
  430. boost::sort(phase[i], CMP_stack(i, actualTurn, lastMoved));
  431. int pi = 1;
  432. while(!outputFull() && pi < 4)
  433. {
  434. const battle::Unit * current = nullptr;
  435. if(phase[pi].empty())
  436. pi++;
  437. else
  438. {
  439. current = takeOneUnit(phase[pi], actualTurn, lastMoved, pi);
  440. if(!current)
  441. {
  442. pi++;
  443. }
  444. else
  445. {
  446. out.back().push_back(current);
  447. lastMoved = current->unitSide();
  448. }
  449. }
  450. }
  451. if(lastMoved < 0)
  452. lastMoved = BattleSide::ATTACKER;
  453. if(!outputFull() && (maxTurns == 0 || out.size() < maxTurns))
  454. battleGetTurnOrder(out, maxUnits, maxTurns, actualTurn + 1, lastMoved);
  455. }
  456. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit) const
  457. {
  458. RETURN_IF_NOT_BATTLE(std::vector<BattleHex>());
  459. if(!unit->getPosition().isValid()) //turrets
  460. return std::vector<BattleHex>();
  461. auto reachability = getReachability(unit);
  462. return battleGetAvailableHexes(reachability, unit);
  463. }
  464. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit) const
  465. {
  466. std::vector<BattleHex> ret;
  467. RETURN_IF_NOT_BATTLE(ret);
  468. if(!unit->getPosition().isValid()) //turrets
  469. return ret;
  470. auto unitSpeed = unit->Speed(0, true);
  471. const bool tacticPhase = battleTacticDist() && battleGetTacticsSide() == unit->unitSide();
  472. for(int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  473. {
  474. // If obstacles or other stacks makes movement impossible, it can't be helped.
  475. if(!cache.isReachable(i))
  476. continue;
  477. if(tacticPhase)
  478. {
  479. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  480. if(!isInTacticRange(i))
  481. continue;
  482. }
  483. else
  484. {
  485. //Not tactics phase -> destination must be reachable and within unit range.
  486. if(cache.distances[i] > (int)unitSpeed)
  487. continue;
  488. }
  489. ret.push_back(i);
  490. }
  491. return ret;
  492. }
  493. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool addOccupiable, std::vector<BattleHex> * attackable) const
  494. {
  495. std::vector<BattleHex> ret = battleGetAvailableHexes(unit);
  496. if(ret.empty())
  497. return ret;
  498. if(addOccupiable && unit->doubleWide())
  499. {
  500. std::vector<BattleHex> occupiable;
  501. for(auto hex : ret)
  502. occupiable.push_back(unit->occupiedHex(hex));
  503. vstd::concatenate(ret, occupiable);
  504. }
  505. if(attackable)
  506. {
  507. auto meleeAttackable = [&](BattleHex hex) -> bool
  508. {
  509. // Return true if given hex has at least one available neighbour.
  510. // Available hexes are already present in ret vector.
  511. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  512. {
  513. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  514. });
  515. return availableNeighbor != ret.end();
  516. };
  517. for(auto otherSt : battleAliveUnits(otherSide(unit->unitSide())))
  518. {
  519. if(!otherSt->isValidTarget(false))
  520. continue;
  521. std::vector<BattleHex> occupied = otherSt->getHexes();
  522. if(battleCanShoot(unit, otherSt->getPosition()))
  523. {
  524. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  525. continue;
  526. }
  527. for(BattleHex he : occupied)
  528. {
  529. if(meleeAttackable(he))
  530. attackable->push_back(he);
  531. }
  532. }
  533. }
  534. //adding occupiable likely adds duplicates to ret -> clean it up
  535. boost::sort(ret);
  536. ret.erase(boost::unique(ret).end(), ret.end());
  537. return ret;
  538. }
  539. bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
  540. {
  541. RETURN_IF_NOT_BATTLE(false);
  542. if(battleTacticDist())
  543. return false;
  544. if (!stack || !target)
  545. return false;
  546. if(!battleMatchOwner(stack, target))
  547. return false;
  548. auto &id = stack->getCreature()->idNumber;
  549. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  550. return false;
  551. return target->alive();
  552. }
  553. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker) const
  554. {
  555. RETURN_IF_NOT_BATTLE(false);
  556. if(battleTacticDist()) //no shooting during tactics
  557. return false;
  558. if (!attacker)
  559. return false;
  560. if (attacker->creatureIndex() == CreatureID::CATAPULT) //catapult cannot attack creatures
  561. return false;
  562. //forgetfulness
  563. TConstBonusListPtr forgetfulList = attacker->getBonuses(Selector::type()(Bonus::FORGETFULL));
  564. if(!forgetfulList->empty())
  565. {
  566. int forgetful = forgetfulList->valOfBonuses(Selector::type()(Bonus::FORGETFULL));
  567. //advanced+ level
  568. if(forgetful > 1)
  569. return false;
  570. }
  571. return attacker->canShoot() && (!battleIsUnitBlocked(attacker)
  572. || attacker->hasBonusOfType(Bonus::FREE_SHOOTING));
  573. }
  574. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, BattleHex dest) const
  575. {
  576. RETURN_IF_NOT_BATTLE(false);
  577. const battle::Unit * defender = battleGetUnitByPos(dest);
  578. if(!attacker || !defender)
  579. return false;
  580. if(battleMatchOwner(attacker, defender) && defender->alive())
  581. return battleCanShoot(attacker);
  582. return false;
  583. }
  584. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  585. {
  586. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  587. {
  588. auto noLimit = Selector::effectRange()(Bonus::NO_LIMIT);
  589. auto limitMatches = info.shooting
  590. ? Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT)
  591. : Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT);
  592. //any regular bonuses or just ones for melee/ranged
  593. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  594. };
  595. const IBonusBearer * attackerBonuses = info.attacker;
  596. const IBonusBearer * defenderBonuses = info.defender;
  597. double additiveBonus = 1.0 + info.additiveBonus;
  598. double multBonus = 1.0 * info.multBonus;
  599. double minDmg = 0.0;
  600. double maxDmg = 0.0;
  601. minDmg = info.attacker->getMinDamage(info.shooting);
  602. maxDmg = info.attacker->getMaxDamage(info.shooting);
  603. minDmg *= info.attacker->getCount(),
  604. maxDmg *= info.attacker->getCount();
  605. if(info.attacker->creatureIndex() == CreatureID::ARROW_TOWERS)
  606. {
  607. SiegeStuffThatShouldBeMovedToHandlers::retrieveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  608. TDmgRange unmodifiableTowerDamage = std::make_pair(int64_t(minDmg), int64_t(maxDmg));
  609. return unmodifiableTowerDamage;
  610. }
  611. const std::string cachingStrSiedgeWeapon = "type_SIEGE_WEAPON";
  612. static const auto selectorSiedgeWeapon = Selector::type()(Bonus::SIEGE_WEAPON);
  613. if(attackerBonuses->hasBonus(selectorSiedgeWeapon, cachingStrSiedgeWeapon) && info.attacker->creatureIndex() != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  614. { //minDmg and maxDmg are multiplied by hero attack + 1
  615. auto retrieveHeroPrimSkill = [&](int skill) -> int
  616. {
  617. std::shared_ptr<const Bonus> b = attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  618. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  619. };
  620. minDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  621. maxDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  622. }
  623. double attackDefenceDifference = 0.0;
  624. double multAttackReduction = 1.0 - battleBonusValue(attackerBonuses, Selector::type()(Bonus::GENERAL_ATTACK_REDUCTION)) / 100.0;
  625. attackDefenceDifference += info.attacker->getAttack(info.shooting) * multAttackReduction;
  626. double multDefenceReduction = 1.0 - battleBonusValue(attackerBonuses, Selector::type()(Bonus::ENEMY_DEFENCE_REDUCTION)) / 100.0;
  627. attackDefenceDifference -= info.defender->getDefense(info.shooting) * multDefenceReduction;
  628. const std::string cachingStrSlayer = "type_SLAYER";
  629. static const auto selectorSlayer = Selector::type()(Bonus::SLAYER);
  630. //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  631. auto slayerEffects = attackerBonuses->getBonuses(selectorSlayer, cachingStrSlayer);
  632. if(std::shared_ptr<const Bonus> slayerEffect = slayerEffects->getFirst(Selector::all))
  633. {
  634. std::vector<int32_t> affectedIds;
  635. const auto spLevel = slayerEffect->val;
  636. const CCreature * defenderType = info.defender->unitType();
  637. bool isAffected = false;
  638. for(const auto & b : defenderType->getBonusList())
  639. {
  640. if((b->type == Bonus::KING3 && spLevel >= 3) || //expert
  641. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  642. (b->type == Bonus::KING1 && spLevel >= 0)) //none or basic +
  643. {
  644. isAffected = true;
  645. break;
  646. }
  647. }
  648. if(isAffected)
  649. {
  650. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getLevelPower(spLevel);
  651. if(info.attacker->hasBonusOfType(Bonus::SPECIAL_PECULIAR_ENCHANT, SpellID::SLAYER))
  652. {
  653. ui8 attackerTier = info.attacker->unitType()->level;
  654. ui8 specialtyBonus = std::max(5 - attackerTier, 0);
  655. attackDefenceDifference += specialtyBonus;
  656. }
  657. }
  658. }
  659. //bonus from attack/defense skills
  660. if(attackDefenceDifference < 0) //decreasing dmg
  661. {
  662. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  663. multBonus *= 1.0 - dec;
  664. }
  665. else //increasing dmg
  666. {
  667. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  668. additiveBonus += inc;
  669. }
  670. const std::string cachingStrJousting = "type_JOUSTING";
  671. static const auto selectorJousting = Selector::type()(Bonus::JOUSTING);
  672. const std::string cachingStrChargeImmunity = "type_CHARGE_IMMUNITY";
  673. static const auto selectorChargeImmunity = Selector::type()(Bonus::CHARGE_IMMUNITY);
  674. //applying jousting bonus
  675. if(info.chargedFields > 0 && attackerBonuses->hasBonus(selectorJousting, cachingStrJousting) && !defenderBonuses->hasBonus(selectorChargeImmunity, cachingStrChargeImmunity))
  676. additiveBonus += info.chargedFields * 0.05;
  677. //handling secondary abilities and artifacts giving premies to them
  678. const std::string cachingStrArchery = "type_SECONDARY_SKILL_PREMYs_ARCHERY";
  679. static const auto selectorArchery = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY);
  680. const std::string cachingStrOffence = "type_SECONDARY_SKILL_PREMYs_OFFENCE";
  681. static const auto selectorOffence = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE);
  682. const std::string cachingStrArmorer = "type_SECONDARY_SKILL_PREMYs_ARMORER";
  683. static const auto selectorArmorer = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER);
  684. if(info.shooting)
  685. additiveBonus += attackerBonuses->valOfBonuses(selectorArchery, cachingStrArchery) / 100.0;
  686. else
  687. additiveBonus += attackerBonuses->valOfBonuses(selectorOffence, cachingStrOffence) / 100.0;
  688. multBonus *= (std::max(0, 100 - defenderBonuses->valOfBonuses(selectorArmorer, cachingStrArmorer))) / 100.0;
  689. //handling hate effect
  690. //assume that unit have only few HATE features and cache them all
  691. const std::string cachingStrHate = "type_HATE";
  692. static const auto selectorHate = Selector::type()(Bonus::HATE);
  693. auto allHateEffects = attackerBonuses->getBonuses(selectorHate, cachingStrHate);
  694. additiveBonus += allHateEffects->valOfBonuses(Selector::subtype()(info.defender->creatureIndex())) / 100.0;
  695. const std::string cachingStrMeleeReduction = "type_GENERAL_DAMAGE_REDUCTIONs_0";
  696. static const auto selectorMeleeReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 0);
  697. const std::string cachingStrRangedReduction = "type_GENERAL_DAMAGE_REDUCTIONs_1";
  698. static const auto selectorRangedReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 1);
  699. //handling spell effects
  700. if(!info.shooting) //eg. shield
  701. {
  702. multBonus *= (100 - defenderBonuses->valOfBonuses(selectorMeleeReduction, cachingStrMeleeReduction)) / 100.0;
  703. }
  704. else //eg. air shield
  705. {
  706. multBonus *= (100 - defenderBonuses->valOfBonuses(selectorRangedReduction, cachingStrRangedReduction)) / 100.0;
  707. }
  708. if(info.shooting)
  709. {
  710. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  711. //get list first, total value of 0 also counts
  712. TConstBonusListPtr forgetfulList = attackerBonuses->getBonuses(Selector::type()(Bonus::FORGETFULL),"type_FORGETFULL");
  713. if(!forgetfulList->empty())
  714. {
  715. int forgetful = forgetfulList->valOfBonuses(Selector::all);
  716. //none of basic level
  717. if(forgetful == 0 || forgetful == 1)
  718. multBonus *= 0.5;
  719. else
  720. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  721. }
  722. }
  723. const std::string cachingStrForcedMinDamage = "type_ALWAYS_MINIMUM_DAMAGE";
  724. static const auto selectorForcedMinDamage = Selector::type()(Bonus::ALWAYS_MINIMUM_DAMAGE);
  725. const std::string cachingStrForcedMaxDamage = "type_ALWAYS_MAXIMUM_DAMAGE";
  726. static const auto selectorForcedMaxDamage = Selector::type()(Bonus::ALWAYS_MAXIMUM_DAMAGE);
  727. TConstBonusListPtr curseEffects = attackerBonuses->getBonuses(selectorForcedMinDamage, cachingStrForcedMinDamage);
  728. TConstBonusListPtr blessEffects = attackerBonuses->getBonuses(selectorForcedMaxDamage, cachingStrForcedMaxDamage);
  729. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  730. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo<std::shared_ptr<Bonus>>))->additionalInfo[0] : 0;
  731. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  732. {
  733. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  734. }
  735. const std::string cachingStrAdvAirShield = "isAdvancedAirShield";
  736. auto isAdvancedAirShield = [](const Bonus* bonus)
  737. {
  738. return bonus->source == Bonus::SPELL_EFFECT
  739. && bonus->sid == SpellID::AIR_SHIELD
  740. && bonus->val >= SecSkillLevel::ADVANCED;
  741. };
  742. if(info.shooting)
  743. {
  744. //wall / distance penalty + advanced air shield
  745. BattleHex attackerPos = info.attackerPos.isValid() ? info.attackerPos : info.attacker->getPosition();
  746. BattleHex defenderPos = info.defenderPos.isValid() ? info.defenderPos : info.defender->getPosition();
  747. const bool distPenalty = battleHasDistancePenalty(attackerBonuses, attackerPos, defenderPos);
  748. const bool obstaclePenalty = battleHasWallPenalty(attackerBonuses, attackerPos, defenderPos);
  749. if(distPenalty || defenderBonuses->hasBonus(isAdvancedAirShield, cachingStrAdvAirShield))
  750. multBonus *= 0.5;
  751. if(obstaclePenalty)
  752. multBonus *= 0.5; //cumulative
  753. }
  754. else
  755. {
  756. const std::string cachingStrNoMeleePenalty = "type_NO_MELEE_PENALTY";
  757. static const auto selectorNoMeleePenalty = Selector::type()(Bonus::NO_MELEE_PENALTY);
  758. if(info.attacker->isShooter() && !attackerBonuses->hasBonus(selectorNoMeleePenalty, cachingStrNoMeleePenalty))
  759. multBonus *= 0.5;
  760. }
  761. // psychic elementals versus mind immune units 50%
  762. if(info.attacker->creatureIndex() == CreatureID::PSYCHIC_ELEMENTAL)
  763. {
  764. const std::string cachingStrMindImmunity = "type_MIND_IMMUNITY";
  765. static const auto selectorMindImmunity = Selector::type()(Bonus::MIND_IMMUNITY);
  766. if(defenderBonuses->hasBonus(selectorMindImmunity, cachingStrMindImmunity))
  767. multBonus *= 0.5;
  768. }
  769. // TODO attack on petrified unit 50%
  770. // blinded unit retaliates
  771. minDmg *= additiveBonus * multBonus;
  772. maxDmg *= additiveBonus * multBonus;
  773. if(curseEffects->size()) //curse handling (rest)
  774. {
  775. minDmg += curseBlessAdditiveModifier;
  776. maxDmg = minDmg;
  777. }
  778. else if(blessEffects->size()) //bless handling
  779. {
  780. maxDmg += curseBlessAdditiveModifier;
  781. minDmg = maxDmg;
  782. }
  783. TDmgRange returnedVal = std::make_pair(int64_t(minDmg), int64_t(maxDmg));
  784. //damage cannot be less than 1
  785. vstd::amax(returnedVal.first, 1);
  786. vstd::amax(returnedVal.second, 1);
  787. return returnedVal;
  788. }
  789. TDmgRange CBattleInfoCallback::battleEstimateDamage(const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  790. {
  791. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  792. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  793. const BattleAttackInfo bai(attacker, defender, shooting);
  794. return battleEstimateDamage(bai, retaliationDmg);
  795. }
  796. TDmgRange CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, TDmgRange * retaliationDmg) const
  797. {
  798. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  799. TDmgRange ret = calculateDmgRange(bai);
  800. if(retaliationDmg)
  801. {
  802. if(bai.shooting)
  803. {
  804. //FIXME: handle RANGED_RETALIATION
  805. retaliationDmg->first = retaliationDmg->second = 0;
  806. }
  807. else
  808. {
  809. //TODO: rewrite using boost::numeric::interval
  810. //TODO: rewire once more using interval-based fuzzy arithmetic
  811. int64_t TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  812. for (int i=0; i<2; ++i)
  813. {
  814. auto retaliationAttack = bai.reverse();
  815. int64_t dmg = ret.*pairElems[i];
  816. auto state = retaliationAttack.attacker->acquireState();
  817. state->damage(dmg);
  818. retaliationAttack.attacker = state.get();
  819. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  820. }
  821. }
  822. }
  823. return ret;
  824. }
  825. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  826. {
  827. std::vector<std::shared_ptr<const CObstacleInstance>> obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  828. RETURN_IF_NOT_BATTLE(obstacles);
  829. for(auto & obs : battleGetAllObstacles())
  830. {
  831. if(vstd::contains(obs->getBlockedTiles(), tile)
  832. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  833. {
  834. obstacles.push_back(obs);
  835. }
  836. }
  837. return obstacles;
  838. }
  839. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit) const
  840. {
  841. std::vector<std::shared_ptr<const CObstacleInstance>> affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  842. RETURN_IF_NOT_BATTLE(affectedObstacles);
  843. if(unit->alive())
  844. {
  845. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  846. if(unit->doubleWide())
  847. {
  848. BattleHex otherHex = unit->occupiedHex(unit->getPosition());
  849. if(otherHex.isValid())
  850. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  851. affectedObstacles.push_back(i);
  852. }
  853. for(auto hex : unit->getHexes())
  854. if(hex == ESiegeHex::GATE_BRIDGE)
  855. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  856. for(int i=0; i<affectedObstacles.size(); i++)
  857. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  858. affectedObstacles.erase(affectedObstacles.begin()+i);
  859. }
  860. return affectedObstacles;
  861. }
  862. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  863. {
  864. AccessibilityInfo ret;
  865. ret.fill(EAccessibility::ACCESSIBLE);
  866. //removing accessibility for side columns of hexes
  867. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  868. {
  869. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  870. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  871. }
  872. //special battlefields with logically unavailable tiles
  873. std::vector<BattleHex> impassableHexes;
  874. if(battleGetBattlefieldType().num == BFieldType::SHIP_TO_SHIP)
  875. {
  876. impassableHexes =
  877. {
  878. 6, 7, 8, 9,
  879. 24, 25, 26,
  880. 58, 59, 60,
  881. 75, 76, 77,
  882. 92, 93, 94,
  883. 109, 110, 111,
  884. 126, 127, 128,
  885. 159, 160, 161, 162, 163,
  886. 176, 177, 178, 179, 180
  887. };
  888. }
  889. for(auto hex : impassableHexes)
  890. ret[hex] = EAccessibility::UNAVAILABLE;
  891. //gate -> should be before stacks
  892. if(battleGetSiegeLevel() > 0)
  893. {
  894. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  895. switch(battleGetGateState())
  896. {
  897. case EGateState::CLOSED:
  898. accessability = EAccessibility::GATE;
  899. break;
  900. case EGateState::BLOCKED:
  901. accessability = EAccessibility::UNAVAILABLE;
  902. break;
  903. }
  904. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  905. }
  906. //tiles occupied by standing stacks
  907. for(auto unit : battleAliveUnits())
  908. {
  909. for(auto hex : unit->getHexes())
  910. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  911. ret[hex] = EAccessibility::ALIVE_STACK;
  912. }
  913. //obstacles
  914. for(const auto &obst : battleGetAllObstacles())
  915. {
  916. for(auto hex : obst->getBlockedTiles())
  917. ret[hex] = EAccessibility::OBSTACLE;
  918. }
  919. //walls
  920. if(battleGetSiegeLevel() > 0)
  921. {
  922. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  923. for(auto hex : permanentlyLocked)
  924. ret[hex] = EAccessibility::UNAVAILABLE;
  925. //TODO likely duplicated logic
  926. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] =
  927. {
  928. //which part of wall, which hex is blocked if this part of wall is not destroyed
  929. std::make_pair(2, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  930. std::make_pair(3, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  931. std::make_pair(4, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  932. std::make_pair(5, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  933. };
  934. for(auto & elem : lockedIfNotDestroyed)
  935. {
  936. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  937. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  938. }
  939. }
  940. return ret;
  941. }
  942. AccessibilityInfo CBattleInfoCallback::getAccesibility(const battle::Unit * stack) const
  943. {
  944. return getAccesibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  945. }
  946. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  947. {
  948. auto ret = getAccesibility();
  949. for(auto hex : accessibleHexes)
  950. if(hex.isValid())
  951. ret[hex] = EAccessibility::ACCESSIBLE;
  952. return ret;
  953. }
  954. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  955. {
  956. ReachabilityInfo ret;
  957. ret.accessibility = accessibility;
  958. ret.params = params;
  959. ret.predecessors.fill(BattleHex::INVALID);
  960. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  961. if(!params.startPosition.isValid()) //if got call for arrow turrets
  962. return ret;
  963. const std::set<BattleHex> obstacles = getStoppers(params.perspective);
  964. std::queue<BattleHex> hexq; //bfs queue
  965. //first element
  966. hexq.push(params.startPosition);
  967. ret.distances[params.startPosition] = 0;
  968. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache;
  969. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  970. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  971. while(!hexq.empty()) //bfs loop
  972. {
  973. const BattleHex curHex = hexq.front();
  974. hexq.pop();
  975. //walking stack can't step past the obstacles
  976. if(curHex != params.startPosition && isInObstacle(curHex, obstacles, params))
  977. continue;
  978. const int costToNeighbour = ret.distances[curHex.hex] + 1;
  979. for(BattleHex neighbour : BattleHex::neighbouringTilesCache[curHex.hex])
  980. {
  981. if(neighbour.isValid())
  982. {
  983. const int costFoundSoFar = ret.distances[neighbour.hex];
  984. if(accessibleCache[neighbour.hex] && costToNeighbour < costFoundSoFar)
  985. {
  986. hexq.push(neighbour);
  987. ret.distances[neighbour.hex] = costToNeighbour;
  988. ret.predecessors[neighbour.hex] = curHex;
  989. }
  990. }
  991. }
  992. }
  993. return ret;
  994. }
  995. bool CBattleInfoCallback::isInObstacle(
  996. BattleHex hex,
  997. const std::set<BattleHex> & obstacles,
  998. const ReachabilityInfo::Parameters & params) const
  999. {
  1000. auto occupiedHexes = battle::Unit::getHexes(hex, params.doubleWide, params.side);
  1001. for(auto occupiedHex : occupiedHexes)
  1002. {
  1003. if(vstd::contains(obstacles, occupiedHex))
  1004. {
  1005. if(occupiedHex == ESiegeHex::GATE_BRIDGE)
  1006. {
  1007. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  1008. return true;
  1009. }
  1010. else
  1011. return true;
  1012. }
  1013. }
  1014. return false;
  1015. }
  1016. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  1017. {
  1018. std::set<BattleHex> ret;
  1019. RETURN_IF_NOT_BATTLE(ret);
  1020. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  1021. {
  1022. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  1023. {
  1024. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  1025. }
  1026. }
  1027. return ret;
  1028. }
  1029. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  1030. {
  1031. auto reachability = getReachability(closest);
  1032. auto avHexes = battleGetAvailableHexes(reachability, closest);
  1033. // I hate std::pairs with their undescriptive member names first / second
  1034. struct DistStack
  1035. {
  1036. int distanceToPred;
  1037. BattleHex destination;
  1038. const battle::Unit * stack;
  1039. };
  1040. std::vector<DistStack> stackPairs;
  1041. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  1042. {
  1043. return unit->isValidTarget(false) && unit != closest;
  1044. });
  1045. for(const battle::Unit * st : possible)
  1046. {
  1047. for(BattleHex hex : avHexes)
  1048. if(CStack::isMeleeAttackPossible(closest, st, hex))
  1049. {
  1050. DistStack hlp = {reachability.distances[hex], hex, st};
  1051. stackPairs.push_back(hlp);
  1052. }
  1053. }
  1054. if (stackPairs.size())
  1055. {
  1056. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  1057. auto minimal = boost::min_element(stackPairs, comparator);
  1058. return std::make_pair(minimal->stack, minimal->destination);
  1059. }
  1060. else
  1061. return std::make_pair<const battle::Unit * , BattleHex>(nullptr, BattleHex::INVALID);
  1062. }
  1063. BattleHex CBattleInfoCallback::getAvaliableHex(CreatureID creID, ui8 side, int initialPos) const
  1064. {
  1065. bool twoHex = VLC->creh->objects[creID]->isDoubleWide();
  1066. int pos;
  1067. if (initialPos > -1)
  1068. pos = initialPos;
  1069. else //summon elementals depending on player side
  1070. {
  1071. if(side == BattleSide::ATTACKER)
  1072. pos = 0; //top left
  1073. else
  1074. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  1075. }
  1076. auto accessibility = getAccesibility();
  1077. std::set<BattleHex> occupyable;
  1078. for(int i = 0; i < accessibility.size(); i++)
  1079. if(accessibility.accessible(i, twoHex, side))
  1080. occupyable.insert(i);
  1081. if(occupyable.empty())
  1082. {
  1083. return BattleHex::INVALID; //all tiles are covered
  1084. }
  1085. return BattleHex::getClosestTile(side, pos, occupyable);
  1086. }
  1087. si8 CBattleInfoCallback::battleGetTacticDist() const
  1088. {
  1089. RETURN_IF_NOT_BATTLE(0);
  1090. //TODO get rid of this method
  1091. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  1092. return battleTacticDist();
  1093. return 0;
  1094. }
  1095. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  1096. {
  1097. RETURN_IF_NOT_BATTLE(false);
  1098. auto side = battleGetTacticsSide();
  1099. auto dist = battleGetTacticDist();
  1100. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  1101. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  1102. }
  1103. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  1104. {
  1105. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  1106. if(!battleDoWeKnowAbout(unit->unitSide()))
  1107. {
  1108. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1109. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1110. params.perspective = battleGetMySide();
  1111. }
  1112. return getReachability(params);
  1113. }
  1114. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  1115. {
  1116. if(params.flying)
  1117. return getFlyingReachability(params);
  1118. else
  1119. return makeBFS(getAccesibility(params.knownAccessible), params);
  1120. }
  1121. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  1122. {
  1123. ReachabilityInfo ret;
  1124. ret.accessibility = getAccesibility(params.knownAccessible);
  1125. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1126. {
  1127. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  1128. {
  1129. ret.predecessors[i] = params.startPosition;
  1130. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1131. }
  1132. }
  1133. return ret;
  1134. }
  1135. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const battle::Unit* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1136. {
  1137. //does not return hex attacked directly
  1138. //TODO: apply rotation to two-hex attackers
  1139. bool isAttacker = attacker->unitSide() == BattleSide::ATTACKER;
  1140. AttackableTiles at;
  1141. RETURN_IF_NOT_BATTLE(at);
  1142. const int WN = GameConstants::BFIELD_WIDTH;
  1143. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  1144. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  1145. bool reverse = isToReverse(hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  1146. if(reverse && attacker->doubleWide())
  1147. {
  1148. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  1149. }
  1150. if(attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  1151. {
  1152. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  1153. }
  1154. if(attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  1155. {
  1156. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  1157. for(BattleHex tile : hexes)
  1158. {
  1159. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  1160. {
  1161. auto st = battleGetUnitByPos(tile, true);
  1162. if(st && battleMatchOwner(st, attacker)) //only hostile stacks - does it work well with Berserk?
  1163. at.hostileCreaturePositions.insert(tile);
  1164. }
  1165. }
  1166. }
  1167. if(attacker->hasBonusOfType(Bonus::WIDE_BREATH))
  1168. {
  1169. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  1170. for(int i = 0; i<hexes.size(); i++)
  1171. {
  1172. if(hexes.at(i) == hex)
  1173. {
  1174. hexes.erase(hexes.begin() + i);
  1175. i = 0;
  1176. }
  1177. }
  1178. for(BattleHex tile : hexes)
  1179. {
  1180. //friendly stacks can also be damaged by Dragon Breath
  1181. auto st = battleGetUnitByPos(tile, true);
  1182. if(st && st != attacker)
  1183. at.friendlyCreaturePositions.insert(tile);
  1184. }
  1185. }
  1186. else if(attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  1187. {
  1188. int pos = BattleHex::mutualPosition(destinationTile, hex);
  1189. if(pos > -1) //only adjacent hexes are subject of dragon breath calculation
  1190. {
  1191. std::vector<BattleHex> hexes; //only one, in fact
  1192. int pseudoVector = destinationTile.hex - hex;
  1193. switch(pseudoVector)
  1194. {
  1195. case 1:
  1196. case -1:
  1197. BattleHex::checkAndPush(destinationTile.hex + pseudoVector, hexes);
  1198. break;
  1199. case WN: //17 //left-down or right-down
  1200. case -WN: //-17 //left-up or right-up
  1201. case WN + 1: //18 //right-down
  1202. case -WN + 1: //-16 //right-up
  1203. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : -1), hexes);
  1204. break;
  1205. case WN - 1: //16 //left-down
  1206. case -WN - 1: //-18 //left-up
  1207. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : 0), hexes);
  1208. break;
  1209. }
  1210. for(BattleHex tile : hexes)
  1211. {
  1212. //friendly stacks can also be damaged by Dragon Breath
  1213. auto st = battleGetUnitByPos(tile, true);
  1214. if(st != nullptr)
  1215. at.friendlyCreaturePositions.insert(tile);
  1216. }
  1217. }
  1218. }
  1219. return at;
  1220. }
  1221. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1222. {
  1223. //does not return hex attacked directly
  1224. AttackableTiles at;
  1225. RETURN_IF_NOT_BATTLE(at);
  1226. if(attacker->hasBonusOfType(Bonus::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1227. {
  1228. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1229. targetHexes.push_back(destinationTile);
  1230. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1231. }
  1232. return at;
  1233. }
  1234. std::vector<const battle::Unit*> CBattleInfoCallback::getAttackedBattleUnits(const battle::Unit* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1235. {
  1236. std::vector<const battle::Unit*> units;
  1237. RETURN_IF_NOT_BATTLE(units);
  1238. AttackableTiles at;
  1239. if (rangedAttack)
  1240. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1241. else
  1242. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1243. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1244. {
  1245. if (unit->isGhost() || !unit->alive())
  1246. return false;
  1247. for (BattleHex hex : battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()))
  1248. {
  1249. if (vstd::contains(at.hostileCreaturePositions, hex))
  1250. return true;
  1251. if (vstd::contains(at.friendlyCreaturePositions, hex))
  1252. return true;
  1253. }
  1254. return false;
  1255. });
  1256. return units;
  1257. }
  1258. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1259. {
  1260. std::set<const CStack*> attackedCres;
  1261. RETURN_IF_NOT_BATTLE(attackedCres);
  1262. AttackableTiles at;
  1263. if(rangedAttack)
  1264. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1265. else
  1266. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1267. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1268. {
  1269. const CStack * st = battleGetStackByPos(tile, true);
  1270. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1271. {
  1272. attackedCres.insert(st);
  1273. }
  1274. }
  1275. for (BattleHex tile : at.friendlyCreaturePositions)
  1276. {
  1277. const CStack * st = battleGetStackByPos(tile, true);
  1278. if(st) //friendly stacks can also be damaged by Dragon Breath
  1279. {
  1280. attackedCres.insert(st);
  1281. }
  1282. }
  1283. return attackedCres;
  1284. }
  1285. //TODO: this should apply also to mechanics and cursor interface
  1286. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1287. {
  1288. int fromX = hexFrom.getX();
  1289. int fromY = hexFrom.getY();
  1290. int toX = hexTo.getX();
  1291. int toY = hexTo.getY();
  1292. if (curDir) // attacker, facing right
  1293. {
  1294. if (fromX < toX)
  1295. return false;
  1296. if (fromX > toX)
  1297. return true;
  1298. if (fromY % 2 == 0 && toY % 2 == 1)
  1299. return true;
  1300. return false;
  1301. }
  1302. else // defender, facing left
  1303. {
  1304. if(fromX < toX)
  1305. return true;
  1306. if(fromX > toX)
  1307. return false;
  1308. if (fromY % 2 == 1 && toY % 2 == 0)
  1309. return true;
  1310. return false;
  1311. }
  1312. }
  1313. //TODO: this should apply also to mechanics and cursor interface
  1314. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1315. {
  1316. if (hexTo < 0 || hexFrom < 0) //turret
  1317. return false;
  1318. if (toDoubleWide)
  1319. {
  1320. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1321. {
  1322. if (toDir)
  1323. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1324. else
  1325. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1326. }
  1327. return false;
  1328. }
  1329. else
  1330. {
  1331. return isToReverseHlp(hexFrom, hexTo, curDir);
  1332. }
  1333. }
  1334. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1335. {
  1336. ReachabilityInfo::TDistances ret;
  1337. ret.fill(-1);
  1338. RETURN_IF_NOT_BATTLE(ret);
  1339. auto reachability = getReachability(unit);
  1340. boost::copy(reachability.distances, ret.begin());
  1341. return ret;
  1342. }
  1343. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1344. {
  1345. RETURN_IF_NOT_BATTLE(false);
  1346. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1347. static const auto selectorNoDistancePenalty = Selector::type()(Bonus::NO_DISTANCE_PENALTY);
  1348. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1349. return false;
  1350. if(auto target = battleGetUnitByPos(destHex, true))
  1351. {
  1352. //If any hex of target creature is within range, there is no penalty
  1353. for(auto hex : target->getHexes())
  1354. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1355. return false;
  1356. //TODO what about two-hex shooters?
  1357. }
  1358. else
  1359. {
  1360. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1361. return false;
  1362. }
  1363. return true;
  1364. }
  1365. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1366. {
  1367. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1368. return WallPartToHex(part);
  1369. }
  1370. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1371. {
  1372. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1373. return hexToWallPart(hex);
  1374. }
  1375. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1376. {
  1377. RETURN_IF_NOT_BATTLE(false);
  1378. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1379. wallPart != EWallPart::INVALID;
  1380. }
  1381. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1382. {
  1383. std::vector<BattleHex> attackableBattleHexes;
  1384. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1385. for(auto & wallPartPair : wallParts)
  1386. {
  1387. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1388. {
  1389. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1390. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1391. {
  1392. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1393. }
  1394. }
  1395. }
  1396. return attackableBattleHexes;
  1397. }
  1398. int32_t CBattleInfoCallback::battleGetSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  1399. {
  1400. RETURN_IF_NOT_BATTLE(-1);
  1401. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1402. int32_t ret = caster->getSpellCost(sp);
  1403. //checking for friendly stacks reducing cost of the spell and
  1404. //enemy stacks increasing it
  1405. int32_t manaReduction = 0;
  1406. int32_t manaIncrease = 0;
  1407. for(auto unit : battleAliveUnits())
  1408. {
  1409. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1410. {
  1411. vstd::amax(manaReduction, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1412. }
  1413. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1414. {
  1415. vstd::amax(manaIncrease, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1416. }
  1417. }
  1418. return ret - manaReduction + manaIncrease;
  1419. }
  1420. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, BattleHex destHex) const
  1421. {
  1422. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1423. }
  1424. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1425. {
  1426. RETURN_IF_NOT_BATTLE(false);
  1427. if(unit->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1428. return false;
  1429. for(auto adjacent : battleAdjacentUnits(unit))
  1430. {
  1431. if(adjacent->unitOwner() != unit->unitOwner()) //blocked by enemy stack
  1432. return true;
  1433. }
  1434. return false;
  1435. }
  1436. std::set<const battle::Unit *> CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1437. {
  1438. std::set<const battle::Unit *> ret;
  1439. RETURN_IF_NOT_BATTLE(ret);
  1440. for(auto hex : unit->getSurroundingHexes())
  1441. {
  1442. if(auto neighbour = battleGetUnitByPos(hex, true))
  1443. ret.insert(neighbour);
  1444. }
  1445. return ret;
  1446. }
  1447. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1448. {
  1449. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1450. //This is complete list. No spells from mods.
  1451. //todo: this should be Spellbook of caster Stack
  1452. static const std::set<SpellID> allPossibleSpells =
  1453. {
  1454. SpellID::AIR_SHIELD,
  1455. SpellID::ANTI_MAGIC,
  1456. SpellID::BLESS,
  1457. SpellID::BLOODLUST,
  1458. SpellID::COUNTERSTRIKE,
  1459. SpellID::CURE,
  1460. SpellID::FIRE_SHIELD,
  1461. SpellID::FORTUNE,
  1462. SpellID::HASTE,
  1463. SpellID::MAGIC_MIRROR,
  1464. SpellID::MIRTH,
  1465. SpellID::PRAYER,
  1466. SpellID::PRECISION,
  1467. SpellID::PROTECTION_FROM_AIR,
  1468. SpellID::PROTECTION_FROM_EARTH,
  1469. SpellID::PROTECTION_FROM_FIRE,
  1470. SpellID::PROTECTION_FROM_WATER,
  1471. SpellID::SHIELD,
  1472. SpellID::SLAYER,
  1473. SpellID::STONE_SKIN
  1474. };
  1475. std::vector<SpellID> beneficialSpells;
  1476. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1477. {
  1478. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1479. {
  1480. return pred(stack) && stack->owner != subject->owner && stack->isValidTarget(false);
  1481. });
  1482. if(stacks.empty())
  1483. return nullptr;
  1484. else
  1485. return stacks.front();
  1486. };
  1487. for(const SpellID spellID : allPossibleSpells)
  1488. {
  1489. std::stringstream cachingStr;
  1490. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1491. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1492. //TODO: this ability has special limitations
  1493. || !(spellID.toSpell()->canBeCast(this, spells::Mode::CREATURE_ACTIVE, subject)))
  1494. continue;
  1495. switch (spellID)
  1496. {
  1497. case SpellID::SHIELD:
  1498. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1499. {
  1500. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1501. {
  1502. return !stack->canShoot();
  1503. });
  1504. if (!walker)
  1505. continue;
  1506. }
  1507. break;
  1508. case SpellID::AIR_SHIELD: //only against active shooters
  1509. {
  1510. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1511. {
  1512. return stack->canShoot();
  1513. });
  1514. if (!shooter)
  1515. continue;
  1516. }
  1517. break;
  1518. case SpellID::ANTI_MAGIC:
  1519. case SpellID::MAGIC_MIRROR:
  1520. case SpellID::PROTECTION_FROM_AIR:
  1521. case SpellID::PROTECTION_FROM_EARTH:
  1522. case SpellID::PROTECTION_FROM_FIRE:
  1523. case SpellID::PROTECTION_FROM_WATER:
  1524. {
  1525. const ui8 enemySide = 1 - subject->side;
  1526. //todo: only if enemy has spellbook
  1527. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1528. continue;
  1529. }
  1530. break;
  1531. case SpellID::CURE: //only damaged units
  1532. {
  1533. //do not cast on affected by debuffs
  1534. if(!subject->canBeHealed())
  1535. continue;
  1536. }
  1537. break;
  1538. case SpellID::BLOODLUST:
  1539. {
  1540. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1541. continue;
  1542. }
  1543. break;
  1544. case SpellID::PRECISION:
  1545. {
  1546. if(!subject->canShoot())
  1547. continue;
  1548. }
  1549. break;
  1550. case SpellID::SLAYER://only if monsters are present
  1551. {
  1552. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1553. {
  1554. const auto isKing = Selector::type()(Bonus::KING1)
  1555. .Or(Selector::type()(Bonus::KING2))
  1556. .Or(Selector::type()(Bonus::KING3));
  1557. return stack->hasBonus(isKing);
  1558. });
  1559. if (!kingMonster)
  1560. continue;
  1561. }
  1562. break;
  1563. }
  1564. beneficialSpells.push_back(spellID);
  1565. }
  1566. if(!beneficialSpells.empty())
  1567. {
  1568. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1569. }
  1570. else
  1571. {
  1572. return SpellID::NONE;
  1573. }
  1574. }
  1575. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1576. {
  1577. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1578. TConstBonusListPtr bl = caster->getBonuses(Selector::type()(Bonus::SPELLCASTER));
  1579. if (!bl->size())
  1580. return SpellID::NONE;
  1581. int totalWeight = 0;
  1582. for(auto b : *bl)
  1583. {
  1584. totalWeight += std::max(b->additionalInfo[0], 1); //minimal chance to cast is 1
  1585. }
  1586. int randomPos = rand.nextInt(totalWeight - 1);
  1587. for(auto b : *bl)
  1588. {
  1589. randomPos -= std::max(b->additionalInfo[0], 1);
  1590. if(randomPos < 0)
  1591. {
  1592. return SpellID(b->subtype);
  1593. }
  1594. }
  1595. return SpellID::NONE;
  1596. }
  1597. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1598. {
  1599. RETURN_IF_NOT_BATTLE(-3);
  1600. if(!battleCanSurrender(Player))
  1601. return -1;
  1602. const auto sideOpt = playerToSide(Player);
  1603. if(!sideOpt)
  1604. return -1;
  1605. const auto side = sideOpt.get();
  1606. int ret = 0;
  1607. double discount = 0;
  1608. for(auto unit : battleAliveUnits(side))
  1609. ret += unit->getRawSurrenderCost();
  1610. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1611. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1612. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1613. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1614. return ret;
  1615. }
  1616. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1617. {
  1618. const IBonusBearer * node = nullptr;
  1619. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1620. node = h;
  1621. else
  1622. node = getBattleNode();
  1623. if(!node)
  1624. return 0;
  1625. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_BELOW));
  1626. if(b->size())
  1627. return b->totalValue();
  1628. return 0;
  1629. }
  1630. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1631. {
  1632. const IBonusBearer *node = nullptr;
  1633. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1634. node = h;
  1635. else
  1636. node = getBattleNode();
  1637. if(!node)
  1638. return GameConstants::SPELL_LEVELS;
  1639. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1640. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_ABOVE));
  1641. if(b->size())
  1642. return b->totalValue();
  1643. return GameConstants::SPELL_LEVELS;
  1644. }
  1645. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1646. {
  1647. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1648. {
  1649. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(Bonus::SIEGE_WEAPON);
  1650. });
  1651. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1652. for(auto & unit : units)
  1653. {
  1654. //todo: move SIEGE_WEAPON check to Unit state
  1655. hasUnit.at(unit->unitSide()) = true;
  1656. if(hasUnit[0] && hasUnit[1])
  1657. return boost::none;
  1658. }
  1659. hasUnit = {false, false};
  1660. for(auto & unit : units)
  1661. {
  1662. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1663. {
  1664. hasUnit.at(unit->unitSide()) = true;
  1665. }
  1666. }
  1667. if(!hasUnit[0] && !hasUnit[1])
  1668. return 2;
  1669. if(!hasUnit[1])
  1670. return 0;
  1671. else
  1672. return 1;
  1673. }