BattleFieldController.cpp 29 KB

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