BattleFieldController.cpp 28 KB

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