BattleFieldController.cpp 18 KB

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