CBattleInfoCallback.cpp 62 KB

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