2
0

BattleFieldController.cpp 27 KB

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