BattleFieldController.cpp 30 KB

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