BattleFieldController.cpp 27 KB

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