BattleFieldController.cpp 30 KB

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