BattleFieldController.cpp 30 KB

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