2
0

BattleFieldController.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. /*
  2. * BattleFieldController.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 "BattleFieldController.h"
  12. #include "BattleInterface.h"
  13. #include "BattleWindow.h"
  14. #include "BattleActionsController.h"
  15. #include "BattleInterfaceClasses.h"
  16. #include "BattleEffectsController.h"
  17. #include "BattleSiegeController.h"
  18. #include "BattleStacksController.h"
  19. #include "BattleObstacleController.h"
  20. #include "BattleProjectileController.h"
  21. #include "BattleRenderer.h"
  22. #include "../CPlayerInterface.h"
  23. #include "../render/CAnimation.h"
  24. #include "../render/Canvas.h"
  25. #include "../render/IImage.h"
  26. #include "../render/IRenderHandler.h"
  27. #include "../GameEngine.h"
  28. #include "../gui/CursorHandler.h"
  29. #include "../adventureMap/CInGameConsole.h"
  30. #include "../client/render/CAnimation.h"
  31. #include "../../CCallback.h"
  32. #include "../../lib/BattleFieldHandler.h"
  33. #include "../../lib/CConfigHandler.h"
  34. #include "../../lib/CStack.h"
  35. #include "../../lib/spells/ISpellMechanics.h"
  36. namespace HexMasks
  37. {
  38. // mask definitions that has set to 1 the edges present in the hex edges highlight image
  39. /*
  40. /\
  41. 0 1
  42. / \
  43. | |
  44. 5 2
  45. | |
  46. \ /
  47. 4 3
  48. \/
  49. */
  50. enum HexEdgeMasks {
  51. empty = 0b000000, // empty used when wanting to keep indexes the same but no highlight should be displayed
  52. topLeft = 0b000001,
  53. topRight = 0b000010,
  54. right = 0b000100,
  55. bottomRight = 0b001000,
  56. bottomLeft = 0b010000,
  57. left = 0b100000,
  58. top = 0b000011,
  59. bottom = 0b011000,
  60. topRightHalfCorner = 0b000110,
  61. bottomRightHalfCorner = 0b001100,
  62. bottomLeftHalfCorner = 0b110000,
  63. topLeftHalfCorner = 0b100001,
  64. rightTopAndBottom = 0b001010, // special case, right half can be drawn instead of only top and bottom
  65. leftTopAndBottom = 0b010001, // special case, left half can be drawn instead of only top and bottom
  66. rightHalf = 0b001110,
  67. leftHalf = 0b110001,
  68. topRightCorner = 0b000111,
  69. bottomRightCorner = 0b011100,
  70. bottomLeftCorner = 0b111000,
  71. topLeftCorner = 0b100011
  72. };
  73. }
  74. static const std::map<int, int> hexEdgeMaskToFrameIndex =
  75. {
  76. { HexMasks::empty, 0 },
  77. { HexMasks::topLeft, 1 },
  78. { HexMasks::topRight, 2 },
  79. { HexMasks::right, 3 },
  80. { HexMasks::bottomRight, 4 },
  81. { HexMasks::bottomLeft, 5 },
  82. { HexMasks::left, 6 },
  83. { HexMasks::top, 7 },
  84. { HexMasks::bottom, 8 },
  85. { HexMasks::topRightHalfCorner, 9 },
  86. { HexMasks::bottomRightHalfCorner, 10 },
  87. { HexMasks::bottomLeftHalfCorner, 11 },
  88. { HexMasks::topLeftHalfCorner, 12 },
  89. { HexMasks::rightTopAndBottom, 13 },
  90. { HexMasks::leftTopAndBottom, 14 },
  91. { HexMasks::rightHalf, 13 },
  92. { HexMasks::leftHalf, 14 },
  93. { HexMasks::topRightCorner, 15 },
  94. { HexMasks::bottomRightCorner, 16 },
  95. { HexMasks::bottomLeftCorner, 17 },
  96. { HexMasks::topLeftCorner, 18 }
  97. };
  98. BattleFieldController::BattleFieldController(BattleInterface & owner):
  99. owner(owner)
  100. {
  101. OBJECT_CONSTRUCTION;
  102. //preparing cells and hexes
  103. cellBorder = ENGINE->renderHandler().loadImage(ImagePath::builtin("CCELLGRD.BMP"), EImageBlitMode::COLORKEY);
  104. cellShade = ENGINE->renderHandler().loadImage(ImagePath::builtin("CCELLSHD.BMP"), EImageBlitMode::SIMPLE);
  105. cellUnitMovementHighlight = ENGINE->renderHandler().loadImage(ImagePath::builtin("UnitMovementHighlight.PNG"), EImageBlitMode::COLORKEY);
  106. cellUnitMaxMovementHighlight = ENGINE->renderHandler().loadImage(ImagePath::builtin("UnitMaxMovementHighlight.PNG"), EImageBlitMode::COLORKEY);
  107. attackCursors = ENGINE->renderHandler().loadAnimation(AnimationPath::builtin("CRCOMBAT"), EImageBlitMode::COLORKEY);
  108. spellCursors = ENGINE->renderHandler().loadAnimation(AnimationPath::builtin("CRSPELL"), EImageBlitMode::COLORKEY);
  109. rangedFullDamageLimitImages = ENGINE->renderHandler().loadAnimation(AnimationPath::builtin("battle/rangeHighlights/rangeHighlightsGreen.json"), EImageBlitMode::COLORKEY);
  110. shootingRangeLimitImages = ENGINE->renderHandler().loadAnimation(AnimationPath::builtin("battle/rangeHighlights/rangeHighlightsRed.json"), EImageBlitMode::COLORKEY);
  111. if(!owner.siegeController)
  112. {
  113. auto bfieldType = owner.getBattle()->battleGetBattlefieldType();
  114. if(bfieldType == BattleField::NONE)
  115. logGlobal->error("Invalid battlefield returned for current battle");
  116. else
  117. background = ENGINE->renderHandler().loadImage(bfieldType.getInfo()->graphics, EImageBlitMode::OPAQUE);
  118. }
  119. else
  120. {
  121. auto backgroundName = owner.siegeController->getBattleBackgroundName();
  122. background = ENGINE->renderHandler().loadImage(backgroundName, EImageBlitMode::OPAQUE);
  123. }
  124. pos.w = background->width();
  125. pos.h = background->height();
  126. backgroundWithHexes = std::make_unique<Canvas>(Point(background->width(), background->height()), CanvasScalingPolicy::AUTO);
  127. updateAccessibleHexes();
  128. addUsedEvents(LCLICK | SHOW_POPUP | MOVE | TIME | GESTURE);
  129. }
  130. void BattleFieldController::activate()
  131. {
  132. LOCPLINT->cingconsole->pos = this->pos;
  133. CIntObject::activate();
  134. }
  135. void BattleFieldController::createHeroes()
  136. {
  137. OBJECT_CONSTRUCTION;
  138. // create heroes as part of our constructor for correct positioning inside battlefield
  139. if(owner.attackingHeroInstance)
  140. owner.attackingHero = std::make_shared<BattleHero>(owner, owner.attackingHeroInstance, false);
  141. if(owner.defendingHeroInstance)
  142. owner.defendingHero = std::make_shared<BattleHero>(owner, owner.defendingHeroInstance, true);
  143. }
  144. void BattleFieldController::gesture(bool on, const Point & initialPosition, const Point & finalPosition)
  145. {
  146. if (!on && pos.isInside(finalPosition))
  147. clickPressed(finalPosition);
  148. }
  149. void BattleFieldController::gesturePanning(const Point & initialPosition, const Point & currentPosition, const Point & lastUpdateDistance)
  150. {
  151. Point distance = currentPosition - initialPosition;
  152. if (distance.length() < settings["battle"]["swipeAttackDistance"].Float())
  153. hoveredHex = getHexAtPosition(initialPosition);
  154. else
  155. hoveredHex = BattleHex::INVALID;
  156. currentAttackOriginPoint = currentPosition;
  157. if (pos.isInside(initialPosition))
  158. owner.actionsController->onHexHovered(getHoveredHex());
  159. }
  160. void BattleFieldController::mouseMoved(const Point & cursorPosition, const Point & lastUpdateDistance)
  161. {
  162. hoveredHex = getHexAtPosition(cursorPosition);
  163. currentAttackOriginPoint = cursorPosition;
  164. if (pos.isInside(cursorPosition))
  165. owner.actionsController->onHexHovered(getHoveredHex());
  166. else
  167. owner.actionsController->onHoverEnded();
  168. }
  169. void BattleFieldController::clickPressed(const Point & cursorPosition)
  170. {
  171. BattleHex selectedHex = getHoveredHex();
  172. if (selectedHex != BattleHex::INVALID)
  173. owner.actionsController->onHexLeftClicked(selectedHex);
  174. }
  175. void BattleFieldController::showPopupWindow(const Point & cursorPosition)
  176. {
  177. BattleHex selectedHex = getHoveredHex();
  178. if (selectedHex != BattleHex::INVALID)
  179. owner.actionsController->onHexRightClicked(selectedHex);
  180. }
  181. void BattleFieldController::renderBattlefield(Canvas & canvas)
  182. {
  183. Canvas clippedCanvas(canvas, pos);
  184. showBackground(clippedCanvas);
  185. BattleRenderer renderer(owner);
  186. renderer.execute(clippedCanvas);
  187. owner.projectilesController->render(clippedCanvas);
  188. }
  189. void BattleFieldController::showBackground(Canvas & canvas)
  190. {
  191. if (owner.stacksController->getActiveStack() != nullptr )
  192. showBackgroundImageWithHexes(canvas);
  193. else
  194. showBackgroundImage(canvas);
  195. showHighlightedHexes(canvas);
  196. }
  197. void BattleFieldController::showBackgroundImage(Canvas & canvas)
  198. {
  199. canvas.draw(background, Point(0, 0));
  200. owner.obstacleController->showAbsoluteObstacles(canvas);
  201. if ( owner.siegeController )
  202. owner.siegeController->showAbsoluteObstacles(canvas);
  203. if (settings["battle"]["cellBorders"].Bool())
  204. {
  205. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  206. {
  207. if ( i % GameConstants::BFIELD_WIDTH == 0)
  208. continue;
  209. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  210. continue;
  211. canvas.draw(cellBorder, hexPositionLocal(i).topLeft());
  212. }
  213. }
  214. }
  215. void BattleFieldController::showBackgroundImageWithHexes(Canvas & canvas)
  216. {
  217. canvas.draw(*backgroundWithHexes, Point(0, 0));
  218. }
  219. void BattleFieldController::redrawBackgroundWithHexes()
  220. {
  221. const CStack *activeStack = owner.stacksController->getActiveStack();
  222. BattleHexArray attackableHexes;
  223. if(activeStack)
  224. occupiableHexes = owner.getBattle()->battleGetAvailableHexes(activeStack, false, true, &attackableHexes);
  225. // prepare background graphic with hexes and shaded hexes
  226. backgroundWithHexes->draw(background, Point(0,0));
  227. owner.obstacleController->showAbsoluteObstacles(*backgroundWithHexes);
  228. if(owner.siegeController)
  229. owner.siegeController->showAbsoluteObstacles(*backgroundWithHexes);
  230. // show shaded hexes for active's stack valid movement and the hexes that it can attack
  231. if(settings["battle"]["stackRange"].Bool())
  232. {
  233. BattleHexArray hexesToShade = occupiableHexes;
  234. hexesToShade.insert(attackableHexes);
  235. for(const BattleHex & hex : hexesToShade)
  236. {
  237. showHighlightedHex(*backgroundWithHexes, cellShade, hex, false);
  238. }
  239. }
  240. // draw cell borders
  241. if(settings["battle"]["cellBorders"].Bool())
  242. {
  243. for(int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  244. {
  245. if(i % GameConstants::BFIELD_WIDTH == 0)
  246. continue;
  247. if(i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  248. continue;
  249. backgroundWithHexes->draw(cellBorder, hexPositionLocal(i).topLeft());
  250. }
  251. }
  252. }
  253. void BattleFieldController::showHighlightedHex(Canvas & canvas, std::shared_ptr<IImage> highlight, const BattleHex & hex, bool darkBorder)
  254. {
  255. Point hexPos = hexPositionLocal(hex).topLeft();
  256. canvas.draw(highlight, hexPos);
  257. if(!darkBorder && settings["battle"]["cellBorders"].Bool())
  258. canvas.draw(cellBorder, hexPos);
  259. }
  260. BattleHexArray BattleFieldController::getHighlightedHexesForActiveStack()
  261. {
  262. if(!owner.stacksController->getActiveStack())
  263. return BattleHexArray();
  264. if(!settings["battle"]["stackRange"].Bool())
  265. return BattleHexArray();
  266. auto hoveredHex = getHoveredHex();
  267. return owner.getBattle()->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex);
  268. }
  269. BattleHexArray BattleFieldController::getMovementRangeForHoveredStack()
  270. {
  271. if (!owner.stacksController->getActiveStack())
  272. return BattleHexArray();
  273. if (!settings["battle"]["movementHighlightOnHover"].Bool() && !ENGINE->isKeyboardShiftDown())
  274. return BattleHexArray();
  275. auto hoveredStack = getHoveredStack();
  276. if(hoveredStack)
  277. return owner.getBattle()->battleGetAvailableHexes(hoveredStack, true, true, nullptr);
  278. else
  279. return BattleHexArray();
  280. }
  281. BattleHexArray BattleFieldController::getHighlightedHexesForSpellRange()
  282. {
  283. BattleHexArray result;
  284. auto hoveredHex = getHoveredHex();
  285. const spells::Caster *caster = nullptr;
  286. const CSpell *spell = nullptr;
  287. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  288. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  289. caster = owner.actionsController->getCurrentSpellcaster();
  290. if(caster && spell) //when casting spell
  291. {
  292. // printing shaded hex(es)
  293. spells::BattleCast event(owner.getBattle().get(), caster, mode, spell);
  294. auto shadedHexes = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
  295. for(const BattleHex & shadedHex : shadedHexes)
  296. {
  297. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  298. result.insert(shadedHex);
  299. }
  300. }
  301. return result;
  302. }
  303. BattleHexArray BattleFieldController::getHighlightedHexesForMovementTarget()
  304. {
  305. const CStack * stack = owner.stacksController->getActiveStack();
  306. auto hoveredHex = getHoveredHex();
  307. if(!stack)
  308. return {};
  309. BattleHexArray availableHexes = owner.getBattle()->battleGetAvailableHexes(stack, false, false, nullptr);
  310. auto hoveredStack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  311. if(owner.getBattle()->battleCanAttack(stack, hoveredStack, hoveredHex))
  312. {
  313. if(isTileAttackable(hoveredHex))
  314. {
  315. BattleHex attackFromHex = fromWhichHexAttack(hoveredHex);
  316. if(stack->doubleWide())
  317. return {attackFromHex, stack->occupiedHex(attackFromHex)};
  318. else
  319. return {attackFromHex};
  320. }
  321. }
  322. if(availableHexes.contains(hoveredHex))
  323. {
  324. if(stack->doubleWide())
  325. return {hoveredHex, stack->occupiedHex(hoveredHex)};
  326. else
  327. return {hoveredHex};
  328. }
  329. if(stack->doubleWide())
  330. {
  331. for(const auto & hex : availableHexes)
  332. {
  333. if(stack->occupiedHex(hex) == hoveredHex)
  334. return {hoveredHex, hex};
  335. }
  336. }
  337. return {};
  338. }
  339. // Range limit highlight helpers
  340. BattleHexArray BattleFieldController::getRangeHexes(const BattleHex & sourceHex, uint8_t distance) const
  341. {
  342. BattleHexArray rangeHexes;
  343. if (!settings["battle"]["rangeLimitHighlightOnHover"].Bool() && !ENGINE->isKeyboardShiftDown())
  344. return rangeHexes;
  345. // get only battlefield hexes that are within the given distance
  346. for(auto i = 0; i < GameConstants::BFIELD_SIZE; i++)
  347. {
  348. BattleHex hex(i);
  349. if(hex.isAvailable() && BattleHex::getDistance(sourceHex, hex) <= distance)
  350. rangeHexes.insert(hex);
  351. }
  352. return rangeHexes;
  353. }
  354. BattleHexArray BattleFieldController::getRangeLimitHexes(const BattleHex & sourceHex, const BattleHexArray & rangeHexes, uint8_t distanceToLimit) const
  355. {
  356. BattleHexArray rangeLimitHexes;
  357. // from range hexes get only the ones at the limit
  358. for(auto & hex : rangeHexes)
  359. {
  360. if(BattleHex::getDistance(sourceHex, hex) == distanceToLimit)
  361. rangeLimitHexes.insert(hex);
  362. }
  363. return rangeLimitHexes;
  364. }
  365. bool BattleFieldController::isHexInRangeLimit(const BattleHex & hex, const BattleHexArray & rangeLimitHexes, int * hexIndexInRangeLimit) const
  366. {
  367. bool hexInRangeLimit = false;
  368. if(!rangeLimitHexes.empty())
  369. {
  370. auto pos = std::find(rangeLimitHexes.begin(), rangeLimitHexes.end(), hex);
  371. *hexIndexInRangeLimit = std::distance(rangeLimitHexes.begin(), pos);
  372. hexInRangeLimit = pos != rangeLimitHexes.end();
  373. }
  374. return hexInRangeLimit;
  375. }
  376. std::vector<std::vector<BattleHex::EDir>> BattleFieldController::getOutsideNeighbourDirectionsForLimitHexes(
  377. const BattleHexArray & wholeRangeHexes, const BattleHexArray & rangeLimitHexes) const
  378. {
  379. std::vector<std::vector<BattleHex::EDir>> output;
  380. if(wholeRangeHexes.empty())
  381. return output;
  382. for(const auto & hex : rangeLimitHexes)
  383. {
  384. // get all neighbours and their directions
  385. const BattleHexArray & neighbouringTiles = hex.getAllNeighbouringTiles();
  386. std::vector<BattleHex::EDir> outsideNeighbourDirections;
  387. // for each neighbour add to output only the valid ones and only that are not found in range Hexes
  388. for(auto direction = 0; direction < 6; direction++)
  389. {
  390. if(!neighbouringTiles[direction].isAvailable())
  391. continue;
  392. if(!wholeRangeHexes.contains(neighbouringTiles[direction]))
  393. outsideNeighbourDirections.push_back(BattleHex::EDir(direction)); // push direction
  394. }
  395. output.push_back(outsideNeighbourDirections);
  396. }
  397. return output;
  398. }
  399. std::vector<std::shared_ptr<IImage>> BattleFieldController::calculateRangeLimitHighlightImages(std::vector<std::vector<BattleHex::EDir>> hexesNeighbourDirections, std::shared_ptr<CAnimation> limitImages)
  400. {
  401. std::vector<std::shared_ptr<IImage>> output; // if no image is to be shown an empty image is still added to help with traverssing the range
  402. if(hexesNeighbourDirections.empty())
  403. return output;
  404. for(auto & directions : hexesNeighbourDirections)
  405. {
  406. std::bitset<6> mask;
  407. // convert directions to mask
  408. for(auto direction : directions)
  409. mask.set(direction);
  410. uint8_t imageKey = static_cast<uint8_t>(mask.to_ulong());
  411. output.push_back(limitImages->getImage(hexEdgeMaskToFrameIndex.at(imageKey)));
  412. }
  413. return output;
  414. }
  415. void BattleFieldController::calculateRangeLimitAndHighlightImages(uint8_t distance, std::shared_ptr<CAnimation> rangeLimitImages, BattleHexArray & rangeLimitHexes, std::vector<std::shared_ptr<IImage>> & rangeLimitHexesHighlights)
  416. {
  417. BattleHexArray rangeHexes = getRangeHexes(hoveredHex, distance);
  418. rangeLimitHexes = getRangeLimitHexes(hoveredHex, rangeHexes, distance);
  419. std::vector<std::vector<BattleHex::EDir>> rangeLimitNeighbourDirections = getOutsideNeighbourDirectionsForLimitHexes(rangeHexes, rangeLimitHexes);
  420. rangeLimitHexesHighlights = calculateRangeLimitHighlightImages(rangeLimitNeighbourDirections, rangeLimitImages);
  421. }
  422. void BattleFieldController::showHighlightedHexes(Canvas & canvas)
  423. {
  424. BattleHexArray rangedFullDamageLimitHexes;
  425. BattleHexArray shootingRangeLimitHexes;
  426. std::vector<std::shared_ptr<IImage>> rangedFullDamageLimitHexesHighlights;
  427. std::vector<std::shared_ptr<IImage>> shootingRangeLimitHexesHighlights;
  428. BattleHexArray hoveredStackMovementRangeHexes = getMovementRangeForHoveredStack();
  429. BattleHexArray hoveredSpellHexes = getHighlightedHexesForSpellRange();
  430. BattleHexArray hoveredMoveHexes = getHighlightedHexesForMovementTarget();
  431. BattleHex hoveredHex = getHoveredHex();
  432. BattleHexArray hoveredMouseHex = hoveredHex.isAvailable() ? BattleHexArray({ hoveredHex }) : BattleHexArray();
  433. const CStack * hoveredStack = getHoveredStack();
  434. if(!hoveredStack && hoveredHex == BattleHex::INVALID)
  435. return;
  436. // skip range limit calculations if unit hovered is not a shooter
  437. if(hoveredStack && hoveredStack->isShooter())
  438. {
  439. // calculate array with highlight images for ranged full damage limit
  440. auto rangedFullDamageDistance = hoveredStack->getRangedFullDamageDistance();
  441. calculateRangeLimitAndHighlightImages(rangedFullDamageDistance, rangedFullDamageLimitImages, rangedFullDamageLimitHexes, rangedFullDamageLimitHexesHighlights);
  442. // calculate array with highlight images for shooting range limit
  443. auto shootingRangeDistance = hoveredStack->getShootingRangeDistance();
  444. calculateRangeLimitAndHighlightImages(shootingRangeDistance, shootingRangeLimitImages, shootingRangeLimitHexes, shootingRangeLimitHexesHighlights);
  445. }
  446. bool useSpellRangeForMouse = hoveredHex != BattleHex::INVALID
  447. && (owner.actionsController->currentActionSpellcasting(getHoveredHex())
  448. || owner.actionsController->creatureSpellcastingModeActive()); //at least shooting with SPELL_LIKE_ATTACK can operate in spellcasting mode without being actual spellcast
  449. bool useMoveRangeForMouse = !hoveredMoveHexes.empty() || !settings["battle"]["mouseShadow"].Bool();
  450. const auto & hoveredMouseHexes = useSpellRangeForMouse ? hoveredSpellHexes : ( useMoveRangeForMouse ? hoveredMoveHexes : hoveredMouseHex);
  451. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; ++hex)
  452. {
  453. bool stackMovement = hoveredStackMovementRangeHexes.contains(hex);
  454. bool mouse = hoveredMouseHexes.contains(hex);
  455. // calculate if hex is Ranged Full Damage Limit and its position in highlight array
  456. int hexIndexInRangedFullDamageLimit = 0;
  457. bool hexInRangedFullDamageLimit = isHexInRangeLimit(hex, rangedFullDamageLimitHexes, &hexIndexInRangedFullDamageLimit);
  458. // calculate if hex is Shooting Range Limit and its position in highlight array
  459. int hexIndexInShootingRangeLimit = 0;
  460. bool hexInShootingRangeLimit = isHexInRangeLimit(hex, shootingRangeLimitHexes, &hexIndexInShootingRangeLimit);
  461. if(stackMovement && mouse) // area where hovered stackMovement can move shown with highlight. Because also affected by mouse cursor, shade as well
  462. {
  463. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  464. showHighlightedHex(canvas, cellShade, hex, true);
  465. }
  466. if(!stackMovement && mouse) // hexes affected only at mouse cursor shown as shaded
  467. {
  468. showHighlightedHex(canvas, cellShade, hex, true);
  469. }
  470. if(stackMovement && !mouse) // hexes where hovered stackMovement can move shown with highlight
  471. {
  472. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  473. }
  474. if(hexInRangedFullDamageLimit)
  475. {
  476. showHighlightedHex(canvas, rangedFullDamageLimitHexesHighlights[hexIndexInRangedFullDamageLimit], hex, false);
  477. }
  478. if(hexInShootingRangeLimit)
  479. {
  480. showHighlightedHex(canvas, shootingRangeLimitHexesHighlights[hexIndexInShootingRangeLimit], hex, false);
  481. }
  482. }
  483. }
  484. Rect BattleFieldController::hexPositionLocal(const BattleHex & hex) const
  485. {
  486. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  487. int y = 86 + 42 *hex.getY();
  488. int w = cellShade->width();
  489. int h = cellShade->height();
  490. return Rect(x, y, w, h);
  491. }
  492. Rect BattleFieldController::hexPositionAbsolute(const BattleHex & hex) const
  493. {
  494. return hexPositionLocal(hex) + pos.topLeft();
  495. }
  496. bool BattleFieldController::isPixelInHex(Point const & position)
  497. {
  498. return !cellShade->isTransparent(position);
  499. }
  500. BattleHex BattleFieldController::getHoveredHex()
  501. {
  502. return hoveredHex;
  503. }
  504. const CStack* BattleFieldController::getHoveredStack()
  505. {
  506. auto hoveredHex = getHoveredHex();
  507. const CStack* hoveredStack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  508. if(owner.windowObject->getQueueHoveredUnitId().has_value())
  509. {
  510. auto stacks = owner.getBattle()->battleGetAllStacks();
  511. for(const CStack * stack : stacks)
  512. if(stack->unitId() == *owner.windowObject->getQueueHoveredUnitId())
  513. hoveredStack = stack;
  514. }
  515. return hoveredStack;
  516. }
  517. BattleHex BattleFieldController::getHexAtPosition(Point hoverPos)
  518. {
  519. if (owner.attackingHero)
  520. {
  521. if (owner.attackingHero->pos.isInside(hoverPos))
  522. return BattleHex::HERO_ATTACKER;
  523. }
  524. if (owner.defendingHero)
  525. {
  526. if (owner.attackingHero->pos.isInside(hoverPos))
  527. return BattleHex::HERO_DEFENDER;
  528. }
  529. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  530. {
  531. Rect hexPosition = hexPositionAbsolute(h);
  532. if (!hexPosition.isInside(hoverPos))
  533. continue;
  534. if (isPixelInHex(hoverPos - hexPosition.topLeft()))
  535. return h;
  536. }
  537. return BattleHex::INVALID;
  538. }
  539. BattleHex::EDir BattleFieldController::selectAttackDirection(const BattleHex & myNumber) const
  540. {
  541. const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
  542. const BattleHexArray & neighbours = myNumber.getAllNeighbouringTiles();
  543. // 0 1
  544. // 5 x 2
  545. // 4 3
  546. // if true - our current stack can move into this hex (and attack)
  547. std::array<bool, 8> attackAvailability;
  548. if (doubleWide)
  549. {
  550. // For double-hexes we need to ensure that both hexes needed for this direction are occupyable:
  551. // | -0- | -1- | -2- | -3- | -4- | -5- | -6- | -7-
  552. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  553. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  554. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  555. for (size_t i : { 1, 2, 3})
  556. {
  557. BattleHex target = neighbours[i].cloneInDirection(BattleHex::RIGHT, false);
  558. attackAvailability[i] = neighbours[i].isValid() && occupiableHexes.contains(neighbours[i]) && target.isValid() && occupiableHexes.contains(target);
  559. }
  560. for (size_t i : { 4, 5, 0})
  561. {
  562. BattleHex target = neighbours[i].cloneInDirection(BattleHex::LEFT, false);
  563. attackAvailability[i] = neighbours[i].isValid() && occupiableHexes.contains(neighbours[i]) && target.isValid() && occupiableHexes.contains(target);
  564. }
  565. attackAvailability[6] = neighbours[0].isValid() && neighbours[1].isValid() && occupiableHexes.contains(neighbours[0]) && occupiableHexes.contains(neighbours[1]);
  566. attackAvailability[7] = neighbours[3].isValid() && neighbours[4].isValid() && occupiableHexes.contains(neighbours[3]) && occupiableHexes.contains(neighbours[4]);
  567. }
  568. else
  569. {
  570. for (size_t i = 0; i < 6; ++i)
  571. attackAvailability[i] = neighbours[i].isValid() && occupiableHexes.contains(neighbours[i]);
  572. attackAvailability[6] = false;
  573. attackAvailability[7] = false;
  574. }
  575. // Zero available tiles to attack from
  576. if ( vstd::find(attackAvailability, true) == attackAvailability.end())
  577. {
  578. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  579. return BattleHex::NONE;
  580. }
  581. // For each valid direction, select position to test against
  582. std::array<Point, 8> testPoint;
  583. for (size_t i = 0; i < 6; ++i)
  584. if (attackAvailability[i])
  585. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  586. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  587. if (attackAvailability[6])
  588. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  589. if (attackAvailability[7])
  590. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  591. // Compute distance between tested position & cursor position and pick nearest
  592. std::array<int, 8> distance2;
  593. for (size_t i = 0; i < 8; ++i)
  594. if (attackAvailability[i])
  595. distance2[i] = (testPoint[i].y - currentAttackOriginPoint.y)*(testPoint[i].y - currentAttackOriginPoint.y) + (testPoint[i].x - currentAttackOriginPoint.x)*(testPoint[i].x - currentAttackOriginPoint.x);
  596. size_t nearest = -1;
  597. for (size_t i = 0; i < 8; ++i)
  598. if (attackAvailability[i] && (nearest == -1 || distance2[i] < distance2[nearest]) )
  599. nearest = i;
  600. assert(nearest != -1);
  601. return BattleHex::EDir(nearest);
  602. }
  603. BattleHex BattleFieldController::fromWhichHexAttack(const BattleHex & attackTarget)
  604. {
  605. BattleHex::EDir direction = selectAttackDirection(attackTarget);
  606. const CStack * attacker = owner.stacksController->getActiveStack();
  607. assert(direction != BattleHex::NONE);
  608. assert(attacker);
  609. if (!attacker->doubleWide())
  610. {
  611. assert(direction != BattleHex::BOTTOM);
  612. assert(direction != BattleHex::TOP);
  613. return attackTarget.cloneInDirection(direction);
  614. }
  615. else
  616. {
  617. // We need to find position of right hex of double-hex creature (or left for defending side)
  618. // | TOP_LEFT |TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP |BOTTOM
  619. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  620. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  621. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  622. switch (direction)
  623. {
  624. case BattleHex::TOP_LEFT:
  625. case BattleHex::LEFT:
  626. case BattleHex::BOTTOM_LEFT:
  627. {
  628. if ( attacker->unitSide() == BattleSide::ATTACKER )
  629. return attackTarget.cloneInDirection(direction);
  630. else
  631. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::LEFT);
  632. }
  633. case BattleHex::TOP_RIGHT:
  634. case BattleHex::RIGHT:
  635. case BattleHex::BOTTOM_RIGHT:
  636. {
  637. if ( attacker->unitSide() == BattleSide::ATTACKER )
  638. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::RIGHT);
  639. else
  640. return attackTarget.cloneInDirection(direction);
  641. }
  642. case BattleHex::TOP:
  643. {
  644. if ( attacker->unitSide() == BattleSide::ATTACKER )
  645. return attackTarget.cloneInDirection(BattleHex::TOP_RIGHT);
  646. else
  647. return attackTarget.cloneInDirection(BattleHex::TOP_LEFT);
  648. }
  649. case BattleHex::BOTTOM:
  650. {
  651. if ( attacker->unitSide() == BattleSide::ATTACKER )
  652. return attackTarget.cloneInDirection(BattleHex::BOTTOM_RIGHT);
  653. else
  654. return attackTarget.cloneInDirection(BattleHex::BOTTOM_LEFT);
  655. }
  656. default:
  657. assert(0);
  658. return BattleHex::INVALID;
  659. }
  660. }
  661. }
  662. bool BattleFieldController::isTileAttackable(const BattleHex & number) const
  663. {
  664. if(!number.isValid())
  665. return false;
  666. for (auto & elem : occupiableHexes)
  667. {
  668. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  669. return true;
  670. }
  671. return false;
  672. }
  673. void BattleFieldController::updateAccessibleHexes()
  674. {
  675. auto accessibility = owner.getBattle()->getAccessibility();
  676. for(int i = 0; i < accessibility.size(); i++)
  677. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE || (accessibility[i] == EAccessibility::SIDE_COLUMN));
  678. }
  679. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  680. {
  681. return stackCountOutsideHexes[number.toInt()];
  682. }
  683. void BattleFieldController::showAll(Canvas & to)
  684. {
  685. show(to);
  686. }
  687. void BattleFieldController::tick(uint32_t msPassed)
  688. {
  689. updateAccessibleHexes();
  690. owner.stacksController->tick(msPassed);
  691. owner.obstacleController->tick(msPassed);
  692. owner.projectilesController->tick(msPassed);
  693. }
  694. void BattleFieldController::show(Canvas & to)
  695. {
  696. CanvasClipRectGuard guard(to, pos);
  697. renderBattlefield(to);
  698. if (isActive() && isGesturing() && getHoveredHex() != BattleHex::INVALID)
  699. {
  700. auto combatCursorIndex = ENGINE->cursor().get<Cursor::Combat>();
  701. if (combatCursorIndex)
  702. {
  703. auto combatImageIndex = static_cast<size_t>(*combatCursorIndex);
  704. to.draw(attackCursors->getImage(combatImageIndex), hexPositionAbsolute(getHoveredHex()).center() - ENGINE->cursor().getPivotOffsetCombat(combatImageIndex));
  705. return;
  706. }
  707. auto spellCursorIndex = ENGINE->cursor().get<Cursor::Spellcast>();
  708. if (spellCursorIndex)
  709. {
  710. auto spellImageIndex = static_cast<size_t>(*spellCursorIndex);
  711. to.draw(spellCursors->getImage(spellImageIndex), hexPositionAbsolute(getHoveredHex()).center() - ENGINE->cursor().getPivotOffsetSpellcast());
  712. return;
  713. }
  714. }
  715. }
  716. bool BattleFieldController::receiveEvent(const Point & position, int eventType) const
  717. {
  718. if (eventType == HOVER)
  719. return true;
  720. return CIntObject::receiveEvent(position, eventType);
  721. }