BattleFieldController.cpp 30 KB

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