BattleFieldController.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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/Canvas.h"
  24. #include "../render/IImage.h"
  25. #include "../renderSDL/SDL_Extensions.h"
  26. #include "../gui/CGuiHandler.h"
  27. #include "../gui/CursorHandler.h"
  28. #include "../adventureMap/CInGameConsole.h"
  29. #include "../../CCallback.h"
  30. #include "../../lib/BattleFieldHandler.h"
  31. #include "../../lib/CConfigHandler.h"
  32. #include "../../lib/CStack.h"
  33. #include "../../lib/spells/ISpellMechanics.h"
  34. #include <SDL_events.h>
  35. BattleFieldController::BattleFieldController(BattleInterface & owner):
  36. owner(owner)
  37. {
  38. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  39. strongInterest = true;
  40. //preparing cells and hexes
  41. cellBorder = IImage::createFromFile("CCELLGRD.BMP", EImageBlitMode::COLORKEY);
  42. cellShade = IImage::createFromFile("CCELLSHD.BMP");
  43. if(!owner.siegeController)
  44. {
  45. auto bfieldType = owner.curInt->cb->battleGetBattlefieldType();
  46. if(bfieldType == BattleField::NONE)
  47. logGlobal->error("Invalid battlefield returned for current battle");
  48. else
  49. background = IImage::createFromFile(bfieldType.getInfo()->graphics, EImageBlitMode::OPAQUE);
  50. }
  51. else
  52. {
  53. std::string backgroundName = owner.siegeController->getBattleBackgroundName();
  54. background = IImage::createFromFile(backgroundName, EImageBlitMode::OPAQUE);
  55. }
  56. pos.w = background->width();
  57. pos.h = background->height();
  58. backgroundWithHexes = std::make_unique<Canvas>(Point(background->width(), background->height()));
  59. auto accessibility = owner.curInt->cb->getAccesibility();
  60. for(int i = 0; i < accessibility.size(); i++)
  61. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  62. addUsedEvents(LCLICK | RCLICK | MOVE);
  63. LOCPLINT->cingconsole->pos = this->pos;
  64. }
  65. void BattleFieldController::createHeroes()
  66. {
  67. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  68. // create heroes as part of our constructor for correct positioning inside battlefield
  69. if(owner.attackingHeroInstance)
  70. owner.attackingHero = std::make_shared<BattleHero>(owner, owner.attackingHeroInstance, false);
  71. if(owner.defendingHeroInstance)
  72. owner.defendingHero = std::make_shared<BattleHero>(owner, owner.defendingHeroInstance, true);
  73. }
  74. void BattleFieldController::mouseMoved(const Point & cursorPosition)
  75. {
  76. if (!pos.isInside(cursorPosition))
  77. {
  78. owner.actionsController->onHoverEnded();
  79. return;
  80. }
  81. BattleHex selectedHex = getHoveredHex();
  82. owner.actionsController->onHexHovered(selectedHex);
  83. }
  84. void BattleFieldController::clickLeft(tribool down, bool previousState)
  85. {
  86. if(!down)
  87. {
  88. BattleHex selectedHex = getHoveredHex();
  89. if (selectedHex != BattleHex::INVALID)
  90. owner.actionsController->onHexLeftClicked(selectedHex);
  91. }
  92. }
  93. void BattleFieldController::clickRight(tribool down, bool previousState)
  94. {
  95. if(down)
  96. {
  97. BattleHex selectedHex = getHoveredHex();
  98. if (selectedHex != BattleHex::INVALID)
  99. owner.actionsController->onHexRightClicked(selectedHex);
  100. }
  101. }
  102. void BattleFieldController::renderBattlefield(Canvas & canvas)
  103. {
  104. Canvas clippedCanvas(canvas, pos);
  105. showBackground(clippedCanvas);
  106. BattleRenderer renderer(owner);
  107. renderer.execute(clippedCanvas);
  108. owner.projectilesController->showProjectiles(clippedCanvas);
  109. }
  110. void BattleFieldController::showBackground(Canvas & canvas)
  111. {
  112. if (owner.stacksController->getActiveStack() != nullptr ) //&& creAnims[stacksController->getActiveStack()->ID]->isIdle() //show everything with range
  113. showBackgroundImageWithHexes(canvas);
  114. else
  115. showBackgroundImage(canvas);
  116. showHighlightedHexes(canvas);
  117. }
  118. void BattleFieldController::showBackgroundImage(Canvas & canvas)
  119. {
  120. canvas.draw(background, Point(0, 0));
  121. owner.obstacleController->showAbsoluteObstacles(canvas);
  122. if ( owner.siegeController )
  123. owner.siegeController->showAbsoluteObstacles(canvas);
  124. if (settings["battle"]["cellBorders"].Bool())
  125. {
  126. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  127. {
  128. if ( i % GameConstants::BFIELD_WIDTH == 0)
  129. continue;
  130. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  131. continue;
  132. canvas.draw(cellBorder, hexPositionLocal(i).topLeft());
  133. }
  134. }
  135. }
  136. void BattleFieldController::showBackgroundImageWithHexes(Canvas & canvas)
  137. {
  138. canvas.draw(*backgroundWithHexes.get(), Point(0, 0));
  139. }
  140. void BattleFieldController::redrawBackgroundWithHexes()
  141. {
  142. const CStack *activeStack = owner.stacksController->getActiveStack();
  143. std::vector<BattleHex> attackableHexes;
  144. if (activeStack)
  145. occupyableHexes = owner.curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
  146. auto accessibility = owner.curInt->cb->getAccesibility();
  147. for(int i = 0; i < accessibility.size(); i++)
  148. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  149. //prepare background graphic with hexes and shaded hexes
  150. backgroundWithHexes->draw(background, Point(0,0));
  151. owner.obstacleController->showAbsoluteObstacles(*backgroundWithHexes);
  152. if ( owner.siegeController )
  153. owner.siegeController->showAbsoluteObstacles(*backgroundWithHexes);
  154. if (settings["battle"]["stackRange"].Bool())
  155. {
  156. std::vector<BattleHex> hexesToShade = occupyableHexes;
  157. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  158. for (BattleHex hex : hexesToShade)
  159. {
  160. backgroundWithHexes->draw(cellShade, hexPositionLocal(hex).topLeft());
  161. }
  162. }
  163. if(settings["battle"]["cellBorders"].Bool())
  164. {
  165. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  166. {
  167. if ( i % GameConstants::BFIELD_WIDTH == 0)
  168. continue;
  169. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  170. continue;
  171. backgroundWithHexes->draw(cellBorder, hexPositionLocal(i).topLeft());
  172. }
  173. }
  174. }
  175. void BattleFieldController::showHighlightedHex(Canvas & canvas, BattleHex hex, bool darkBorder)
  176. {
  177. Point hexPos = hexPositionLocal(hex).topLeft();
  178. canvas.draw(cellShade, hexPos);
  179. if(!darkBorder && settings["battle"]["cellBorders"].Bool())
  180. canvas.draw(cellBorder, hexPos);
  181. }
  182. std::set<BattleHex> BattleFieldController::getHighlightedHexesStackRange()
  183. {
  184. std::set<BattleHex> result;
  185. if ( !owner.stacksController->getActiveStack())
  186. return result;
  187. if ( !settings["battle"]["stackRange"].Bool())
  188. return result;
  189. auto hoveredHex = getHoveredHex();
  190. std::set<BattleHex> set = owner.curInt->cb->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex, attackingHex);
  191. for(BattleHex hex : set)
  192. result.insert(hex);
  193. // display the movement shadow of stack under mouse
  194. const CStack * const hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  195. if(hoveredStack && hoveredStack != owner.stacksController->getActiveStack())
  196. {
  197. std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(hoveredStack, true, nullptr);
  198. for(BattleHex hex : v)
  199. result.insert(hex);
  200. }
  201. return result;
  202. }
  203. std::set<BattleHex> BattleFieldController::getHighlightedHexesSpellRange()
  204. {
  205. std::set<BattleHex> result;
  206. auto hoveredHex = getHoveredHex();
  207. if(!settings["battle"]["mouseShadow"].Bool())
  208. return result;
  209. const spells::Caster *caster = nullptr;
  210. const CSpell *spell = nullptr;
  211. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  212. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  213. caster = owner.actionsController->getCurrentSpellcaster();
  214. if(caster && spell) //when casting spell
  215. {
  216. // printing shaded hex(es)
  217. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  218. auto shaded = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
  219. for(BattleHex shadedHex : shaded)
  220. {
  221. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  222. result.insert(shadedHex);
  223. }
  224. }
  225. return result;
  226. }
  227. std::set<BattleHex> BattleFieldController::getHighlightedHexesMovementTarget()
  228. {
  229. const CStack * stack = owner.stacksController->getActiveStack();
  230. auto hoveredHex = getHoveredHex();
  231. if (stack)
  232. {
  233. std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(stack, false, nullptr);
  234. auto hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  235. if(owner.curInt->cb->battleCanAttack(stack, hoveredStack, hoveredHex))
  236. {
  237. if (isTileAttackable(hoveredHex))
  238. {
  239. BattleHex attackFromHex = fromWhichHexAttack(hoveredHex);
  240. if (stack->doubleWide())
  241. return {attackFromHex, stack->occupiedHex(attackFromHex)};
  242. else
  243. return {attackFromHex};
  244. }
  245. }
  246. if (vstd::contains(v,hoveredHex))
  247. {
  248. if (stack->doubleWide())
  249. return {hoveredHex, stack->occupiedHex(hoveredHex)};
  250. else
  251. return {hoveredHex};
  252. }
  253. if (stack->doubleWide())
  254. {
  255. for (auto const & hex : v)
  256. {
  257. if (stack->occupiedHex(hex) == hoveredHex)
  258. return { hoveredHex, hex };
  259. }
  260. }
  261. }
  262. return {};
  263. }
  264. void BattleFieldController::showHighlightedHexes(Canvas & canvas)
  265. {
  266. std::set<BattleHex> hoveredStack = getHighlightedHexesStackRange();
  267. std::set<BattleHex> hoveredSpell = getHighlightedHexesSpellRange();
  268. std::set<BattleHex> hoveredMove = getHighlightedHexesMovementTarget();
  269. if (getHoveredHex() == BattleHex::INVALID)
  270. return;
  271. auto const & hoveredMouse = owner.actionsController->currentActionSpellcasting(getHoveredHex()) ? hoveredSpell : hoveredMove;
  272. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  273. {
  274. bool stack = hoveredStack.count(b);
  275. bool mouse = hoveredMouse.count(b);
  276. if ( stack && mouse )
  277. {
  278. // area where enemy stack can move AND affected by mouse cursor - create darker highlight by blitting twice
  279. showHighlightedHex(canvas, b, true);
  280. showHighlightedHex(canvas, b, true);
  281. }
  282. if ( !stack && mouse )
  283. {
  284. showHighlightedHex(canvas, b, true);
  285. }
  286. if ( stack && !mouse )
  287. {
  288. showHighlightedHex(canvas, b, false);
  289. }
  290. }
  291. }
  292. Rect BattleFieldController::hexPositionLocal(BattleHex hex) const
  293. {
  294. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  295. int y = 86 + 42 *hex.getY();
  296. int w = cellShade->width();
  297. int h = cellShade->height();
  298. return Rect(x, y, w, h);
  299. }
  300. Rect BattleFieldController::hexPositionAbsolute(BattleHex hex) const
  301. {
  302. return hexPositionLocal(hex) + pos.topLeft();
  303. }
  304. bool BattleFieldController::isPixelInHex(Point const & position)
  305. {
  306. return !cellShade->isTransparent(position);
  307. }
  308. BattleHex BattleFieldController::getHoveredHex()
  309. {
  310. Point hoverPos = GH.getCursorPosition();
  311. if (owner.attackingHero)
  312. {
  313. if (owner.attackingHero->pos.isInside(hoverPos))
  314. return BattleHex::HERO_ATTACKER;
  315. }
  316. if (owner.defendingHero)
  317. {
  318. if (owner.attackingHero->pos.isInside(hoverPos))
  319. return BattleHex::HERO_DEFENDER;
  320. }
  321. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  322. {
  323. Rect hexPosition = hexPositionAbsolute(h);
  324. if (!hexPosition.isInside(hoverPos))
  325. continue;
  326. if (isPixelInHex(hoverPos - hexPosition.topLeft()))
  327. return h;
  328. }
  329. return BattleHex::INVALID;
  330. }
  331. void BattleFieldController::setBattleCursor(BattleHex myNumber)
  332. {
  333. Point cursorPos = CCS->curh->position();
  334. std::vector<Cursor::Combat> sectorCursor = {
  335. Cursor::Combat::HIT_SOUTHEAST,
  336. Cursor::Combat::HIT_SOUTHWEST,
  337. Cursor::Combat::HIT_WEST,
  338. Cursor::Combat::HIT_NORTHWEST,
  339. Cursor::Combat::HIT_NORTHEAST,
  340. Cursor::Combat::HIT_EAST,
  341. Cursor::Combat::HIT_SOUTH,
  342. Cursor::Combat::HIT_NORTH,
  343. };
  344. auto direction = static_cast<size_t>(selectAttackDirection(myNumber, cursorPos));
  345. assert(direction != -1);
  346. if (direction != -1)
  347. CCS->curh->set(sectorCursor[direction]);
  348. }
  349. BattleHex::EDir BattleFieldController::selectAttackDirection(BattleHex myNumber, const Point & cursorPos)
  350. {
  351. const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
  352. auto neighbours = myNumber.allNeighbouringTiles();
  353. // 0 1
  354. // 5 x 2
  355. // 4 3
  356. // if true - our current stack can move into this hex (and attack)
  357. std::array<bool, 8> attackAvailability;
  358. if (doubleWide)
  359. {
  360. // For double-hexes we need to ensure that both hexes needed for this direction are occupyable:
  361. // | -0- | -1- | -2- | -3- | -4- | -5- | -6- | -7-
  362. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  363. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  364. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  365. for (size_t i : { 1, 2, 3})
  366. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]) && vstd::contains(occupyableHexes, neighbours[i].cloneInDirection(BattleHex::RIGHT, false));
  367. for (size_t i : { 4, 5, 0})
  368. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]) && vstd::contains(occupyableHexes, neighbours[i].cloneInDirection(BattleHex::LEFT, false));
  369. attackAvailability[6] = vstd::contains(occupyableHexes, neighbours[0]) && vstd::contains(occupyableHexes, neighbours[1]);
  370. attackAvailability[7] = vstd::contains(occupyableHexes, neighbours[3]) && vstd::contains(occupyableHexes, neighbours[4]);
  371. }
  372. else
  373. {
  374. for (size_t i = 0; i < 6; ++i)
  375. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]);
  376. attackAvailability[6] = false;
  377. attackAvailability[7] = false;
  378. }
  379. // Zero available tiles to attack from
  380. if ( vstd::find(attackAvailability, true) == attackAvailability.end())
  381. {
  382. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  383. return BattleHex::NONE;
  384. }
  385. // For each valid direction, select position to test against
  386. std::array<Point, 8> testPoint;
  387. for (size_t i = 0; i < 6; ++i)
  388. if (attackAvailability[i])
  389. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  390. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  391. if (attackAvailability[6])
  392. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  393. if (attackAvailability[7])
  394. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  395. // Compute distance between tested position & cursor position and pick nearest
  396. std::array<int, 8> distance2;
  397. for (size_t i = 0; i < 8; ++i)
  398. if (attackAvailability[i])
  399. distance2[i] = (testPoint[i].y - cursorPos.y)*(testPoint[i].y - cursorPos.y) + (testPoint[i].x - cursorPos.x)*(testPoint[i].x - cursorPos.x);
  400. size_t nearest = -1;
  401. for (size_t i = 0; i < 8; ++i)
  402. if (attackAvailability[i] && (nearest == -1 || distance2[i] < distance2[nearest]) )
  403. nearest = i;
  404. assert(nearest != -1);
  405. return BattleHex::EDir(nearest);
  406. }
  407. BattleHex BattleFieldController::fromWhichHexAttack(BattleHex attackTarget)
  408. {
  409. BattleHex::EDir direction = selectAttackDirection(attackTarget, CCS->curh->position());
  410. const CStack * attacker = owner.stacksController->getActiveStack();
  411. assert(direction != BattleHex::NONE);
  412. assert(attacker);
  413. if (!attacker->doubleWide())
  414. {
  415. assert(direction != BattleHex::BOTTOM);
  416. assert(direction != BattleHex::TOP);
  417. return attackTarget.cloneInDirection(direction);
  418. }
  419. else
  420. {
  421. // We need to find position of right hex of double-hex creature (or left for defending side)
  422. // | TOP_LEFT |TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP |BOTTOM
  423. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  424. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  425. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  426. switch (direction)
  427. {
  428. case BattleHex::TOP_LEFT:
  429. case BattleHex::LEFT:
  430. case BattleHex::BOTTOM_LEFT:
  431. {
  432. if ( attacker->side == BattleSide::ATTACKER )
  433. return attackTarget.cloneInDirection(direction);
  434. else
  435. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::LEFT);
  436. }
  437. case BattleHex::TOP_RIGHT:
  438. case BattleHex::RIGHT:
  439. case BattleHex::BOTTOM_RIGHT:
  440. {
  441. if ( attacker->side == BattleSide::ATTACKER )
  442. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::RIGHT);
  443. else
  444. return attackTarget.cloneInDirection(direction);
  445. }
  446. case BattleHex::TOP:
  447. {
  448. if ( attacker->side == BattleSide::ATTACKER )
  449. return attackTarget.cloneInDirection(BattleHex::TOP_RIGHT);
  450. else
  451. return attackTarget.cloneInDirection(BattleHex::TOP_LEFT);
  452. }
  453. case BattleHex::BOTTOM:
  454. {
  455. if ( attacker->side == BattleSide::ATTACKER )
  456. return attackTarget.cloneInDirection(BattleHex::BOTTOM_RIGHT);
  457. else
  458. return attackTarget.cloneInDirection(BattleHex::BOTTOM_LEFT);
  459. }
  460. default:
  461. assert(0);
  462. return BattleHex::INVALID;
  463. }
  464. }
  465. }
  466. bool BattleFieldController::isTileAttackable(const BattleHex & number) const
  467. {
  468. for (auto & elem : occupyableHexes)
  469. {
  470. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  471. return true;
  472. }
  473. return false;
  474. }
  475. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  476. {
  477. return stackCountOutsideHexes[number];
  478. }
  479. void BattleFieldController::showAll(SDL_Surface * to)
  480. {
  481. show(to);
  482. }
  483. void BattleFieldController::show(SDL_Surface * to)
  484. {
  485. owner.stacksController->update();
  486. owner.obstacleController->update();
  487. Canvas canvas(to);
  488. CSDL_Ext::CClipRectGuard guard(to, pos);
  489. renderBattlefield(canvas);
  490. }