BattleFieldController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  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::ALPHA);
  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()));
  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. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  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. std::vector<BattleHex> 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. std::vector<BattleHex> hexesToShade = occupiableHexes;
  236. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  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. std::set<BattleHex> BattleFieldController::getHighlightedHexesForActiveStack()
  263. {
  264. std::set<BattleHex> result;
  265. if(!owner.stacksController->getActiveStack())
  266. return result;
  267. if(!settings["battle"]["stackRange"].Bool())
  268. return result;
  269. auto hoveredHex = getHoveredHex();
  270. std::set<BattleHex> set = owner.getBattle()->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex);
  271. for(BattleHex hex : set)
  272. result.insert(hex);
  273. return result;
  274. }
  275. std::set<BattleHex> BattleFieldController::getMovementRangeForHoveredStack()
  276. {
  277. std::set<BattleHex> 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. std::vector<BattleHex> v = owner.getBattle()->battleGetAvailableHexes(hoveredStack, true, true, nullptr);
  286. for(BattleHex hex : v)
  287. result.insert(hex);
  288. }
  289. return result;
  290. }
  291. std::set<BattleHex> BattleFieldController::getHighlightedHexesForSpellRange()
  292. {
  293. std::set<BattleHex> result;
  294. auto hoveredHex = getHoveredHex();
  295. if(!settings["battle"]["mouseShadow"].Bool())
  296. return result;
  297. const spells::Caster *caster = nullptr;
  298. const CSpell *spell = nullptr;
  299. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  300. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  301. caster = owner.actionsController->getCurrentSpellcaster();
  302. if(caster && spell) //when casting spell
  303. {
  304. // printing shaded hex(es)
  305. spells::BattleCast event(owner.getBattle().get(), caster, mode, spell);
  306. auto shadedHexes = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
  307. for(BattleHex shadedHex : shadedHexes)
  308. {
  309. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  310. result.insert(shadedHex);
  311. }
  312. }
  313. return result;
  314. }
  315. std::set<BattleHex> BattleFieldController::getHighlightedHexesForMovementTarget()
  316. {
  317. const CStack * stack = owner.stacksController->getActiveStack();
  318. auto hoveredHex = getHoveredHex();
  319. if(!stack)
  320. return {};
  321. std::vector<BattleHex> availableHexes = owner.getBattle()->battleGetAvailableHexes(stack, false, false, nullptr);
  322. auto hoveredStack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  323. if(owner.getBattle()->battleCanAttack(stack, hoveredStack, hoveredHex))
  324. {
  325. if(isTileAttackable(hoveredHex))
  326. {
  327. BattleHex attackFromHex = fromWhichHexAttack(hoveredHex);
  328. if(stack->doubleWide())
  329. return {attackFromHex, stack->occupiedHex(attackFromHex)};
  330. else
  331. return {attackFromHex};
  332. }
  333. }
  334. if(vstd::contains(availableHexes, hoveredHex))
  335. {
  336. if(stack->doubleWide())
  337. return {hoveredHex, stack->occupiedHex(hoveredHex)};
  338. else
  339. return {hoveredHex};
  340. }
  341. if(stack->doubleWide())
  342. {
  343. for(auto const & hex : availableHexes)
  344. {
  345. if(stack->occupiedHex(hex) == hoveredHex)
  346. return {hoveredHex, hex};
  347. }
  348. }
  349. return {};
  350. }
  351. // Range limit highlight helpers
  352. std::vector<BattleHex> BattleFieldController::getRangeHexes(BattleHex sourceHex, uint8_t distance)
  353. {
  354. std::vector<BattleHex> rangeHexes;
  355. if (!settings["battle"]["rangeLimitHighlightOnHover"].Bool() && !GH.isKeyboardShiftDown())
  356. return rangeHexes;
  357. // get only battlefield hexes that are within the given distance
  358. for(auto i = 0; i < GameConstants::BFIELD_SIZE; i++)
  359. {
  360. BattleHex hex(i);
  361. if(hex.isAvailable() && BattleHex::getDistance(sourceHex, hex) <= distance)
  362. rangeHexes.push_back(hex);
  363. }
  364. return rangeHexes;
  365. }
  366. std::vector<BattleHex> BattleFieldController::getRangeLimitHexes(BattleHex hoveredHex, std::vector<BattleHex> rangeHexes, uint8_t distanceToLimit)
  367. {
  368. std::vector<BattleHex> rangeLimitHexes;
  369. // from range hexes get only the ones at the limit
  370. for(auto & hex : rangeHexes)
  371. {
  372. if(BattleHex::getDistance(hoveredHex, hex) == distanceToLimit)
  373. rangeLimitHexes.push_back(hex);
  374. }
  375. return rangeLimitHexes;
  376. }
  377. bool BattleFieldController::IsHexInRangeLimit(BattleHex hex, std::vector<BattleHex> & rangeLimitHexes, int * hexIndexInRangeLimit)
  378. {
  379. bool hexInRangeLimit = false;
  380. if(!rangeLimitHexes.empty())
  381. {
  382. auto pos = std::find(rangeLimitHexes.begin(), rangeLimitHexes.end(), hex);
  383. *hexIndexInRangeLimit = std::distance(rangeLimitHexes.begin(), pos);
  384. hexInRangeLimit = pos != rangeLimitHexes.end();
  385. }
  386. return hexInRangeLimit;
  387. }
  388. std::vector<std::vector<BattleHex::EDir>> BattleFieldController::getOutsideNeighbourDirectionsForLimitHexes(std::vector<BattleHex> wholeRangeHexes, std::vector<BattleHex> rangeLimitHexes)
  389. {
  390. std::vector<std::vector<BattleHex::EDir>> output;
  391. if(wholeRangeHexes.empty())
  392. return output;
  393. for(auto & hex : rangeLimitHexes)
  394. {
  395. // get all neighbours and their directions
  396. auto neighbouringTiles = hex.allNeighbouringTiles();
  397. std::vector<BattleHex::EDir> outsideNeighbourDirections;
  398. // for each neighbour add to output only the valid ones and only that are not found in range Hexes
  399. for(auto direction = 0; direction < 6; direction++)
  400. {
  401. if(!neighbouringTiles[direction].isAvailable())
  402. continue;
  403. auto it = std::find(wholeRangeHexes.begin(), wholeRangeHexes.end(), neighbouringTiles[direction]);
  404. if(it == wholeRangeHexes.end())
  405. outsideNeighbourDirections.push_back(BattleHex::EDir(direction)); // push direction
  406. }
  407. output.push_back(outsideNeighbourDirections);
  408. }
  409. return output;
  410. }
  411. std::vector<std::shared_ptr<IImage>> BattleFieldController::calculateRangeLimitHighlightImages(std::vector<std::vector<BattleHex::EDir>> hexesNeighbourDirections, std::shared_ptr<CAnimation> limitImages)
  412. {
  413. 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
  414. if(hexesNeighbourDirections.empty())
  415. return output;
  416. for(auto & directions : hexesNeighbourDirections)
  417. {
  418. std::bitset<6> mask;
  419. // convert directions to mask
  420. for(auto direction : directions)
  421. mask.set(direction);
  422. uint8_t imageKey = static_cast<uint8_t>(mask.to_ulong());
  423. output.push_back(limitImages->getImage(hexEdgeMaskToFrameIndex.at(imageKey)));
  424. }
  425. return output;
  426. }
  427. void BattleFieldController::calculateRangeLimitAndHighlightImages(uint8_t distance, std::shared_ptr<CAnimation> rangeLimitImages, std::vector<BattleHex> & rangeLimitHexes, std::vector<std::shared_ptr<IImage>> & rangeLimitHexesHighlights)
  428. {
  429. std::vector<BattleHex> rangeHexes = getRangeHexes(hoveredHex, distance);
  430. rangeLimitHexes = getRangeLimitHexes(hoveredHex, rangeHexes, distance);
  431. std::vector<std::vector<BattleHex::EDir>> rangeLimitNeighbourDirections = getOutsideNeighbourDirectionsForLimitHexes(rangeHexes, rangeLimitHexes);
  432. rangeLimitHexesHighlights = calculateRangeLimitHighlightImages(rangeLimitNeighbourDirections, rangeLimitImages);
  433. }
  434. void BattleFieldController::showHighlightedHexes(Canvas & canvas)
  435. {
  436. std::vector<BattleHex> rangedFullDamageLimitHexes;
  437. std::vector<BattleHex> shootingRangeLimitHexes;
  438. std::vector<std::shared_ptr<IImage>> rangedFullDamageLimitHexesHighlights;
  439. std::vector<std::shared_ptr<IImage>> shootingRangeLimitHexesHighlights;
  440. std::set<BattleHex> hoveredStackMovementRangeHexes = getMovementRangeForHoveredStack();
  441. std::set<BattleHex> hoveredSpellHexes = getHighlightedHexesForSpellRange();
  442. std::set<BattleHex> hoveredMoveHexes = getHighlightedHexesForMovementTarget();
  443. BattleHex hoveredHex = getHoveredHex();
  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. auto const & hoveredMouseHexes = hoveredHex != BattleHex::INVALID && owner.actionsController->currentActionSpellcasting(getHoveredHex()) ? hoveredSpellHexes : hoveredMoveHexes;
  458. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; ++hex)
  459. {
  460. bool stackMovement = hoveredStackMovementRangeHexes.count(hex);
  461. bool mouse = hoveredMouseHexes.count(hex);
  462. // calculate if hex is Ranged Full Damage Limit and its position in highlight array
  463. int hexIndexInRangedFullDamageLimit = 0;
  464. bool hexInRangedFullDamageLimit = IsHexInRangeLimit(hex, rangedFullDamageLimitHexes, &hexIndexInRangedFullDamageLimit);
  465. // calculate if hex is Shooting Range Limit and its position in highlight array
  466. int hexIndexInShootingRangeLimit = 0;
  467. bool hexInShootingRangeLimit = IsHexInRangeLimit(hex, shootingRangeLimitHexes, &hexIndexInShootingRangeLimit);
  468. if(stackMovement && mouse) // area where hovered stackMovement can move shown with highlight. Because also affected by mouse cursor, shade as well
  469. {
  470. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  471. showHighlightedHex(canvas, cellShade, hex, true);
  472. }
  473. if(!stackMovement && mouse) // hexes affected only at mouse cursor shown as shaded
  474. {
  475. showHighlightedHex(canvas, cellShade, hex, true);
  476. }
  477. if(stackMovement && !mouse) // hexes where hovered stackMovement can move shown with highlight
  478. {
  479. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  480. }
  481. if(hexInRangedFullDamageLimit)
  482. {
  483. showHighlightedHex(canvas, rangedFullDamageLimitHexesHighlights[hexIndexInRangedFullDamageLimit], hex, false);
  484. }
  485. if(hexInShootingRangeLimit)
  486. {
  487. showHighlightedHex(canvas, shootingRangeLimitHexesHighlights[hexIndexInShootingRangeLimit], hex, false);
  488. }
  489. }
  490. }
  491. Rect BattleFieldController::hexPositionLocal(BattleHex hex) const
  492. {
  493. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  494. int y = 86 + 42 *hex.getY();
  495. int w = cellShade->width();
  496. int h = cellShade->height();
  497. return Rect(x, y, w, h);
  498. }
  499. Rect BattleFieldController::hexPositionAbsolute(BattleHex hex) const
  500. {
  501. return hexPositionLocal(hex) + pos.topLeft();
  502. }
  503. bool BattleFieldController::isPixelInHex(Point const & position)
  504. {
  505. return !cellShade->isTransparent(position);
  506. }
  507. BattleHex BattleFieldController::getHoveredHex()
  508. {
  509. return hoveredHex;
  510. }
  511. const CStack* BattleFieldController::getHoveredStack()
  512. {
  513. auto hoveredHex = getHoveredHex();
  514. const CStack* hoveredStack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  515. if(owner.windowObject->getQueueHoveredUnitId().has_value())
  516. {
  517. auto stacks = owner.getBattle()->battleGetAllStacks();
  518. for(const CStack * stack : stacks)
  519. if(stack->unitId() == *owner.windowObject->getQueueHoveredUnitId())
  520. hoveredStack = stack;
  521. }
  522. return hoveredStack;
  523. }
  524. BattleHex BattleFieldController::getHexAtPosition(Point hoverPos)
  525. {
  526. if (owner.attackingHero)
  527. {
  528. if (owner.attackingHero->pos.isInside(hoverPos))
  529. return BattleHex::HERO_ATTACKER;
  530. }
  531. if (owner.defendingHero)
  532. {
  533. if (owner.attackingHero->pos.isInside(hoverPos))
  534. return BattleHex::HERO_DEFENDER;
  535. }
  536. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  537. {
  538. Rect hexPosition = hexPositionAbsolute(h);
  539. if (!hexPosition.isInside(hoverPos))
  540. continue;
  541. if (isPixelInHex(hoverPos - hexPosition.topLeft()))
  542. return h;
  543. }
  544. return BattleHex::INVALID;
  545. }
  546. BattleHex::EDir BattleFieldController::selectAttackDirection(BattleHex myNumber)
  547. {
  548. const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
  549. auto neighbours = myNumber.allNeighbouringTiles();
  550. // 0 1
  551. // 5 x 2
  552. // 4 3
  553. // if true - our current stack can move into this hex (and attack)
  554. std::array<bool, 8> attackAvailability;
  555. if (doubleWide)
  556. {
  557. // For double-hexes we need to ensure that both hexes needed for this direction are occupyable:
  558. // | -0- | -1- | -2- | -3- | -4- | -5- | -6- | -7-
  559. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  560. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  561. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  562. for (size_t i : { 1, 2, 3})
  563. attackAvailability[i] = vstd::contains(occupiableHexes, neighbours[i]) && vstd::contains(occupiableHexes, neighbours[i].cloneInDirection(BattleHex::RIGHT, false));
  564. for (size_t i : { 4, 5, 0})
  565. attackAvailability[i] = vstd::contains(occupiableHexes, neighbours[i]) && vstd::contains(occupiableHexes, neighbours[i].cloneInDirection(BattleHex::LEFT, false));
  566. attackAvailability[6] = vstd::contains(occupiableHexes, neighbours[0]) && vstd::contains(occupiableHexes, neighbours[1]);
  567. attackAvailability[7] = vstd::contains(occupiableHexes, neighbours[3]) && vstd::contains(occupiableHexes, neighbours[4]);
  568. }
  569. else
  570. {
  571. for (size_t i = 0; i < 6; ++i)
  572. attackAvailability[i] = vstd::contains(occupiableHexes, neighbours[i]);
  573. attackAvailability[6] = false;
  574. attackAvailability[7] = false;
  575. }
  576. // Zero available tiles to attack from
  577. if ( vstd::find(attackAvailability, true) == attackAvailability.end())
  578. {
  579. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  580. return BattleHex::NONE;
  581. }
  582. // For each valid direction, select position to test against
  583. std::array<Point, 8> testPoint;
  584. for (size_t i = 0; i < 6; ++i)
  585. if (attackAvailability[i])
  586. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  587. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  588. if (attackAvailability[6])
  589. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  590. if (attackAvailability[7])
  591. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  592. // Compute distance between tested position & cursor position and pick nearest
  593. std::array<int, 8> distance2;
  594. for (size_t i = 0; i < 8; ++i)
  595. if (attackAvailability[i])
  596. distance2[i] = (testPoint[i].y - currentAttackOriginPoint.y)*(testPoint[i].y - currentAttackOriginPoint.y) + (testPoint[i].x - currentAttackOriginPoint.x)*(testPoint[i].x - currentAttackOriginPoint.x);
  597. size_t nearest = -1;
  598. for (size_t i = 0; i < 8; ++i)
  599. if (attackAvailability[i] && (nearest == -1 || distance2[i] < distance2[nearest]) )
  600. nearest = i;
  601. assert(nearest != -1);
  602. return BattleHex::EDir(nearest);
  603. }
  604. BattleHex BattleFieldController::fromWhichHexAttack(BattleHex attackTarget)
  605. {
  606. BattleHex::EDir direction = selectAttackDirection(getHoveredHex());
  607. const CStack * attacker = owner.stacksController->getActiveStack();
  608. assert(direction != BattleHex::NONE);
  609. assert(attacker);
  610. if (!attacker->doubleWide())
  611. {
  612. assert(direction != BattleHex::BOTTOM);
  613. assert(direction != BattleHex::TOP);
  614. return attackTarget.cloneInDirection(direction);
  615. }
  616. else
  617. {
  618. // We need to find position of right hex of double-hex creature (or left for defending side)
  619. // | TOP_LEFT |TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP |BOTTOM
  620. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  621. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  622. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  623. switch (direction)
  624. {
  625. case BattleHex::TOP_LEFT:
  626. case BattleHex::LEFT:
  627. case BattleHex::BOTTOM_LEFT:
  628. {
  629. if ( attacker->unitSide() == BattleSide::ATTACKER )
  630. return attackTarget.cloneInDirection(direction);
  631. else
  632. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::LEFT);
  633. }
  634. case BattleHex::TOP_RIGHT:
  635. case BattleHex::RIGHT:
  636. case BattleHex::BOTTOM_RIGHT:
  637. {
  638. if ( attacker->unitSide() == BattleSide::ATTACKER )
  639. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::RIGHT);
  640. else
  641. return attackTarget.cloneInDirection(direction);
  642. }
  643. case BattleHex::TOP:
  644. {
  645. if ( attacker->unitSide() == BattleSide::ATTACKER )
  646. return attackTarget.cloneInDirection(BattleHex::TOP_RIGHT);
  647. else
  648. return attackTarget.cloneInDirection(BattleHex::TOP_LEFT);
  649. }
  650. case BattleHex::BOTTOM:
  651. {
  652. if ( attacker->unitSide() == BattleSide::ATTACKER )
  653. return attackTarget.cloneInDirection(BattleHex::BOTTOM_RIGHT);
  654. else
  655. return attackTarget.cloneInDirection(BattleHex::BOTTOM_LEFT);
  656. }
  657. default:
  658. assert(0);
  659. return BattleHex::INVALID;
  660. }
  661. }
  662. }
  663. bool BattleFieldController::isTileAttackable(const BattleHex & number) const
  664. {
  665. for (auto & elem : occupiableHexes)
  666. {
  667. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  668. return true;
  669. }
  670. return false;
  671. }
  672. void BattleFieldController::updateAccessibleHexes()
  673. {
  674. auto accessibility = owner.getBattle()->getAccessibility();
  675. for(int i = 0; i < accessibility.size(); i++)
  676. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE || (accessibility[i] == EAccessibility::SIDE_COLUMN));
  677. }
  678. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  679. {
  680. return stackCountOutsideHexes[number];
  681. }
  682. void BattleFieldController::showAll(Canvas & to)
  683. {
  684. show(to);
  685. }
  686. void BattleFieldController::tick(uint32_t msPassed)
  687. {
  688. updateAccessibleHexes();
  689. owner.stacksController->tick(msPassed);
  690. owner.obstacleController->tick(msPassed);
  691. owner.projectilesController->tick(msPassed);
  692. }
  693. void BattleFieldController::show(Canvas & to)
  694. {
  695. CSDL_Ext::CClipRectGuard guard(to.getInternalSurface(), pos);
  696. renderBattlefield(to);
  697. if (isActive() && isGesturing() && getHoveredHex() != BattleHex::INVALID)
  698. {
  699. auto combatCursorIndex = CCS->curh->get<Cursor::Combat>();
  700. if (combatCursorIndex)
  701. {
  702. auto combatImageIndex = static_cast<size_t>(*combatCursorIndex);
  703. to.draw(attackCursors->getImage(combatImageIndex), hexPositionAbsolute(getHoveredHex()).center() - CCS->curh->getPivotOffsetCombat(combatImageIndex));
  704. return;
  705. }
  706. auto spellCursorIndex = CCS->curh->get<Cursor::Spellcast>();
  707. if (spellCursorIndex)
  708. {
  709. auto spellImageIndex = static_cast<size_t>(*spellCursorIndex);
  710. to.draw(spellCursors->getImage(spellImageIndex), hexPositionAbsolute(getHoveredHex()).center() - CCS->curh->getPivotOffsetSpellcast());
  711. return;
  712. }
  713. }
  714. }
  715. bool BattleFieldController::receiveEvent(const Point & position, int eventType) const
  716. {
  717. if (eventType == HOVER)
  718. return true;
  719. return CIntObject::receiveEvent(position, eventType);
  720. }